CompilerInvocation.cpp 188 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716
  1. //===- CompilerInvocation.cpp ---------------------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. #include "clang/Frontend/CompilerInvocation.h"
  9. #include "TestModuleFileExtension.h"
  10. #include "clang/Basic/Builtins.h"
  11. #include "clang/Basic/CharInfo.h"
  12. #include "clang/Basic/CodeGenOptions.h"
  13. #include "clang/Basic/CommentOptions.h"
  14. #include "clang/Basic/DebugInfoOptions.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/DiagnosticDriver.h"
  17. #include "clang/Basic/DiagnosticOptions.h"
  18. #include "clang/Basic/FileSystemOptions.h"
  19. #include "clang/Basic/LLVM.h"
  20. #include "clang/Basic/LangOptions.h"
  21. #include "clang/Basic/LangStandard.h"
  22. #include "clang/Basic/ObjCRuntime.h"
  23. #include "clang/Basic/Sanitizers.h"
  24. #include "clang/Basic/SourceLocation.h"
  25. #include "clang/Basic/TargetOptions.h"
  26. #include "clang/Basic/Version.h"
  27. #include "clang/Basic/Visibility.h"
  28. #include "clang/Basic/XRayInstr.h"
  29. #include "clang/Config/config.h"
  30. #include "clang/Driver/Driver.h"
  31. #include "clang/Driver/DriverDiagnostic.h"
  32. #include "clang/Driver/Options.h"
  33. #include "clang/Frontend/CommandLineSourceLoc.h"
  34. #include "clang/Frontend/DependencyOutputOptions.h"
  35. #include "clang/Frontend/FrontendDiagnostic.h"
  36. #include "clang/Frontend/FrontendOptions.h"
  37. #include "clang/Frontend/FrontendPluginRegistry.h"
  38. #include "clang/Frontend/MigratorOptions.h"
  39. #include "clang/Frontend/PreprocessorOutputOptions.h"
  40. #include "clang/Frontend/TextDiagnosticBuffer.h"
  41. #include "clang/Frontend/Utils.h"
  42. #include "clang/Lex/HeaderSearchOptions.h"
  43. #include "clang/Lex/PreprocessorOptions.h"
  44. #include "clang/Sema/CodeCompleteOptions.h"
  45. #include "clang/Serialization/ASTBitCodes.h"
  46. #include "clang/Serialization/ModuleFileExtension.h"
  47. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  48. #include "llvm/ADT/APInt.h"
  49. #include "llvm/ADT/ArrayRef.h"
  50. #include "llvm/ADT/CachedHashString.h"
  51. #include "llvm/ADT/DenseSet.h"
  52. #include "llvm/ADT/FloatingPointMode.h"
  53. #include "llvm/ADT/Hashing.h"
  54. #include "llvm/ADT/None.h"
  55. #include "llvm/ADT/Optional.h"
  56. #include "llvm/ADT/STLExtras.h"
  57. #include "llvm/ADT/SmallString.h"
  58. #include "llvm/ADT/SmallVector.h"
  59. #include "llvm/ADT/StringRef.h"
  60. #include "llvm/ADT/StringSwitch.h"
  61. #include "llvm/ADT/Triple.h"
  62. #include "llvm/ADT/Twine.h"
  63. #include "llvm/Config/llvm-config.h"
  64. #include "llvm/IR/DebugInfoMetadata.h"
  65. #include "llvm/Linker/Linker.h"
  66. #include "llvm/MC/MCTargetOptions.h"
  67. #include "llvm/Option/Arg.h"
  68. #include "llvm/Option/ArgList.h"
  69. #include "llvm/Option/OptSpecifier.h"
  70. #include "llvm/Option/OptTable.h"
  71. #include "llvm/Option/Option.h"
  72. #include "llvm/ProfileData/InstrProfReader.h"
  73. #include "llvm/Remarks/HotnessThresholdParser.h"
  74. #include "llvm/Support/CodeGen.h"
  75. #include "llvm/Support/Compiler.h"
  76. #include "llvm/Support/Error.h"
  77. #include "llvm/Support/ErrorHandling.h"
  78. #include "llvm/Support/ErrorOr.h"
  79. #include "llvm/Support/FileSystem.h"
  80. #include "llvm/Support/HashBuilder.h"
  81. #include "llvm/Support/Host.h"
  82. #include "llvm/Support/MathExtras.h"
  83. #include "llvm/Support/MemoryBuffer.h"
  84. #include "llvm/Support/Path.h"
  85. #include "llvm/Support/Process.h"
  86. #include "llvm/Support/Regex.h"
  87. #include "llvm/Support/VersionTuple.h"
  88. #include "llvm/Support/VirtualFileSystem.h"
  89. #include "llvm/Support/raw_ostream.h"
  90. #include "llvm/Target/TargetOptions.h"
  91. #include <algorithm>
  92. #include <atomic>
  93. #include <cassert>
  94. #include <cstddef>
  95. #include <cstring>
  96. #include <memory>
  97. #include <string>
  98. #include <tuple>
  99. #include <type_traits>
  100. #include <utility>
  101. #include <vector>
  102. using namespace clang;
  103. using namespace driver;
  104. using namespace options;
  105. using namespace llvm::opt;
  106. //===----------------------------------------------------------------------===//
  107. // Initialization.
  108. //===----------------------------------------------------------------------===//
  109. CompilerInvocationRefBase::CompilerInvocationRefBase()
  110. : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
  111. DiagnosticOpts(new DiagnosticOptions()),
  112. HeaderSearchOpts(new HeaderSearchOptions()),
  113. PreprocessorOpts(new PreprocessorOptions()),
  114. AnalyzerOpts(new AnalyzerOptions()) {}
  115. CompilerInvocationRefBase::CompilerInvocationRefBase(
  116. const CompilerInvocationRefBase &X)
  117. : LangOpts(new LangOptions(*X.getLangOpts())),
  118. TargetOpts(new TargetOptions(X.getTargetOpts())),
  119. DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
  120. HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
  121. PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())),
  122. AnalyzerOpts(new AnalyzerOptions(*X.getAnalyzerOpts())) {}
  123. CompilerInvocationRefBase::CompilerInvocationRefBase(
  124. CompilerInvocationRefBase &&X) = default;
  125. CompilerInvocationRefBase &
  126. CompilerInvocationRefBase::operator=(CompilerInvocationRefBase X) {
  127. LangOpts.swap(X.LangOpts);
  128. TargetOpts.swap(X.TargetOpts);
  129. DiagnosticOpts.swap(X.DiagnosticOpts);
  130. HeaderSearchOpts.swap(X.HeaderSearchOpts);
  131. PreprocessorOpts.swap(X.PreprocessorOpts);
  132. AnalyzerOpts.swap(X.AnalyzerOpts);
  133. return *this;
  134. }
  135. CompilerInvocationRefBase &
  136. CompilerInvocationRefBase::operator=(CompilerInvocationRefBase &&X) = default;
  137. CompilerInvocationRefBase::~CompilerInvocationRefBase() = default;
  138. //===----------------------------------------------------------------------===//
  139. // Normalizers
  140. //===----------------------------------------------------------------------===//
  141. #define SIMPLE_ENUM_VALUE_TABLE
  142. #include "clang/Driver/Options.inc"
  143. #undef SIMPLE_ENUM_VALUE_TABLE
  144. static llvm::Optional<bool> normalizeSimpleFlag(OptSpecifier Opt,
  145. unsigned TableIndex,
  146. const ArgList &Args,
  147. DiagnosticsEngine &Diags) {
  148. if (Args.hasArg(Opt))
  149. return true;
  150. return None;
  151. }
  152. static Optional<bool> normalizeSimpleNegativeFlag(OptSpecifier Opt, unsigned,
  153. const ArgList &Args,
  154. DiagnosticsEngine &) {
  155. if (Args.hasArg(Opt))
  156. return false;
  157. return None;
  158. }
  159. /// The tblgen-erated code passes in a fifth parameter of an arbitrary type, but
  160. /// denormalizeSimpleFlags never looks at it. Avoid bloating compile-time with
  161. /// unnecessary template instantiations and just ignore it with a variadic
  162. /// argument.
  163. static void denormalizeSimpleFlag(SmallVectorImpl<const char *> &Args,
  164. const char *Spelling,
  165. CompilerInvocation::StringAllocator,
  166. Option::OptionClass, unsigned, /*T*/...) {
  167. Args.push_back(Spelling);
  168. }
  169. template <typename T> static constexpr bool is_uint64_t_convertible() {
  170. return !std::is_same<T, uint64_t>::value &&
  171. llvm::is_integral_or_enum<T>::value;
  172. }
  173. template <typename T,
  174. std::enable_if_t<!is_uint64_t_convertible<T>(), bool> = false>
  175. static auto makeFlagToValueNormalizer(T Value) {
  176. return [Value](OptSpecifier Opt, unsigned, const ArgList &Args,
  177. DiagnosticsEngine &) -> Optional<T> {
  178. if (Args.hasArg(Opt))
  179. return Value;
  180. return None;
  181. };
  182. }
  183. template <typename T,
  184. std::enable_if_t<is_uint64_t_convertible<T>(), bool> = false>
  185. static auto makeFlagToValueNormalizer(T Value) {
  186. return makeFlagToValueNormalizer(uint64_t(Value));
  187. }
  188. static auto makeBooleanOptionNormalizer(bool Value, bool OtherValue,
  189. OptSpecifier OtherOpt) {
  190. return [Value, OtherValue, OtherOpt](OptSpecifier Opt, unsigned,
  191. const ArgList &Args,
  192. DiagnosticsEngine &) -> Optional<bool> {
  193. if (const Arg *A = Args.getLastArg(Opt, OtherOpt)) {
  194. return A->getOption().matches(Opt) ? Value : OtherValue;
  195. }
  196. return None;
  197. };
  198. }
  199. static auto makeBooleanOptionDenormalizer(bool Value) {
  200. return [Value](SmallVectorImpl<const char *> &Args, const char *Spelling,
  201. CompilerInvocation::StringAllocator, Option::OptionClass,
  202. unsigned, bool KeyPath) {
  203. if (KeyPath == Value)
  204. Args.push_back(Spelling);
  205. };
  206. }
  207. static void denormalizeStringImpl(SmallVectorImpl<const char *> &Args,
  208. const char *Spelling,
  209. CompilerInvocation::StringAllocator SA,
  210. Option::OptionClass OptClass, unsigned,
  211. const Twine &Value) {
  212. switch (OptClass) {
  213. case Option::SeparateClass:
  214. case Option::JoinedOrSeparateClass:
  215. case Option::JoinedAndSeparateClass:
  216. Args.push_back(Spelling);
  217. Args.push_back(SA(Value));
  218. break;
  219. case Option::JoinedClass:
  220. case Option::CommaJoinedClass:
  221. Args.push_back(SA(Twine(Spelling) + Value));
  222. break;
  223. default:
  224. llvm_unreachable("Cannot denormalize an option with option class "
  225. "incompatible with string denormalization.");
  226. }
  227. }
  228. template <typename T>
  229. static void
  230. denormalizeString(SmallVectorImpl<const char *> &Args, const char *Spelling,
  231. CompilerInvocation::StringAllocator SA,
  232. Option::OptionClass OptClass, unsigned TableIndex, T Value) {
  233. denormalizeStringImpl(Args, Spelling, SA, OptClass, TableIndex, Twine(Value));
  234. }
  235. static Optional<SimpleEnumValue>
  236. findValueTableByName(const SimpleEnumValueTable &Table, StringRef Name) {
  237. for (int I = 0, E = Table.Size; I != E; ++I)
  238. if (Name == Table.Table[I].Name)
  239. return Table.Table[I];
  240. return None;
  241. }
  242. static Optional<SimpleEnumValue>
  243. findValueTableByValue(const SimpleEnumValueTable &Table, unsigned Value) {
  244. for (int I = 0, E = Table.Size; I != E; ++I)
  245. if (Value == Table.Table[I].Value)
  246. return Table.Table[I];
  247. return None;
  248. }
  249. static llvm::Optional<unsigned> normalizeSimpleEnum(OptSpecifier Opt,
  250. unsigned TableIndex,
  251. const ArgList &Args,
  252. DiagnosticsEngine &Diags) {
  253. assert(TableIndex < SimpleEnumValueTablesSize);
  254. const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
  255. auto *Arg = Args.getLastArg(Opt);
  256. if (!Arg)
  257. return None;
  258. StringRef ArgValue = Arg->getValue();
  259. if (auto MaybeEnumVal = findValueTableByName(Table, ArgValue))
  260. return MaybeEnumVal->Value;
  261. Diags.Report(diag::err_drv_invalid_value)
  262. << Arg->getAsString(Args) << ArgValue;
  263. return None;
  264. }
  265. static void denormalizeSimpleEnumImpl(SmallVectorImpl<const char *> &Args,
  266. const char *Spelling,
  267. CompilerInvocation::StringAllocator SA,
  268. Option::OptionClass OptClass,
  269. unsigned TableIndex, unsigned Value) {
  270. assert(TableIndex < SimpleEnumValueTablesSize);
  271. const SimpleEnumValueTable &Table = SimpleEnumValueTables[TableIndex];
  272. if (auto MaybeEnumVal = findValueTableByValue(Table, Value)) {
  273. denormalizeString(Args, Spelling, SA, OptClass, TableIndex,
  274. MaybeEnumVal->Name);
  275. } else {
  276. llvm_unreachable("The simple enum value was not correctly defined in "
  277. "the tablegen option description");
  278. }
  279. }
  280. template <typename T>
  281. static void denormalizeSimpleEnum(SmallVectorImpl<const char *> &Args,
  282. const char *Spelling,
  283. CompilerInvocation::StringAllocator SA,
  284. Option::OptionClass OptClass,
  285. unsigned TableIndex, T Value) {
  286. return denormalizeSimpleEnumImpl(Args, Spelling, SA, OptClass, TableIndex,
  287. static_cast<unsigned>(Value));
  288. }
  289. static Optional<std::string> normalizeString(OptSpecifier Opt, int TableIndex,
  290. const ArgList &Args,
  291. DiagnosticsEngine &Diags) {
  292. auto *Arg = Args.getLastArg(Opt);
  293. if (!Arg)
  294. return None;
  295. return std::string(Arg->getValue());
  296. }
  297. template <typename IntTy>
  298. static Optional<IntTy> normalizeStringIntegral(OptSpecifier Opt, int,
  299. const ArgList &Args,
  300. DiagnosticsEngine &Diags) {
  301. auto *Arg = Args.getLastArg(Opt);
  302. if (!Arg)
  303. return None;
  304. IntTy Res;
  305. if (StringRef(Arg->getValue()).getAsInteger(0, Res)) {
  306. Diags.Report(diag::err_drv_invalid_int_value)
  307. << Arg->getAsString(Args) << Arg->getValue();
  308. return None;
  309. }
  310. return Res;
  311. }
  312. static Optional<std::vector<std::string>>
  313. normalizeStringVector(OptSpecifier Opt, int, const ArgList &Args,
  314. DiagnosticsEngine &) {
  315. return Args.getAllArgValues(Opt);
  316. }
  317. static void denormalizeStringVector(SmallVectorImpl<const char *> &Args,
  318. const char *Spelling,
  319. CompilerInvocation::StringAllocator SA,
  320. Option::OptionClass OptClass,
  321. unsigned TableIndex,
  322. const std::vector<std::string> &Values) {
  323. switch (OptClass) {
  324. case Option::CommaJoinedClass: {
  325. std::string CommaJoinedValue;
  326. if (!Values.empty()) {
  327. CommaJoinedValue.append(Values.front());
  328. for (const std::string &Value : llvm::drop_begin(Values, 1)) {
  329. CommaJoinedValue.append(",");
  330. CommaJoinedValue.append(Value);
  331. }
  332. }
  333. denormalizeString(Args, Spelling, SA, Option::OptionClass::JoinedClass,
  334. TableIndex, CommaJoinedValue);
  335. break;
  336. }
  337. case Option::JoinedClass:
  338. case Option::SeparateClass:
  339. case Option::JoinedOrSeparateClass:
  340. for (const std::string &Value : Values)
  341. denormalizeString(Args, Spelling, SA, OptClass, TableIndex, Value);
  342. break;
  343. default:
  344. llvm_unreachable("Cannot denormalize an option with option class "
  345. "incompatible with string vector denormalization.");
  346. }
  347. }
  348. static Optional<std::string> normalizeTriple(OptSpecifier Opt, int TableIndex,
  349. const ArgList &Args,
  350. DiagnosticsEngine &Diags) {
  351. auto *Arg = Args.getLastArg(Opt);
  352. if (!Arg)
  353. return None;
  354. return llvm::Triple::normalize(Arg->getValue());
  355. }
  356. template <typename T, typename U>
  357. static T mergeForwardValue(T KeyPath, U Value) {
  358. return static_cast<T>(Value);
  359. }
  360. template <typename T, typename U> static T mergeMaskValue(T KeyPath, U Value) {
  361. return KeyPath | Value;
  362. }
  363. template <typename T> static T extractForwardValue(T KeyPath) {
  364. return KeyPath;
  365. }
  366. template <typename T, typename U, U Value>
  367. static T extractMaskValue(T KeyPath) {
  368. return ((KeyPath & Value) == Value) ? static_cast<T>(Value) : T();
  369. }
  370. #define PARSE_OPTION_WITH_MARSHALLING( \
  371. ARGS, DIAGS, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  372. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX) \
  373. if ((FLAGS)&options::CC1Option) { \
  374. KEYPATH = MERGER(KEYPATH, DEFAULT_VALUE); \
  375. if (IMPLIED_CHECK) \
  376. KEYPATH = MERGER(KEYPATH, IMPLIED_VALUE); \
  377. if (SHOULD_PARSE) \
  378. if (auto MaybeValue = NORMALIZER(OPT_##ID, TABLE_INDEX, ARGS, DIAGS)) \
  379. KEYPATH = \
  380. MERGER(KEYPATH, static_cast<decltype(KEYPATH)>(*MaybeValue)); \
  381. }
  382. // Capture the extracted value as a lambda argument to avoid potential issues
  383. // with lifetime extension of the reference.
  384. #define GENERATE_OPTION_WITH_MARSHALLING( \
  385. ARGS, STRING_ALLOCATOR, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, \
  386. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, \
  387. TABLE_INDEX) \
  388. if ((FLAGS)&options::CC1Option) { \
  389. [&](const auto &Extracted) { \
  390. if (ALWAYS_EMIT || \
  391. (Extracted != \
  392. static_cast<decltype(KEYPATH)>((IMPLIED_CHECK) ? (IMPLIED_VALUE) \
  393. : (DEFAULT_VALUE)))) \
  394. DENORMALIZER(ARGS, SPELLING, STRING_ALLOCATOR, Option::KIND##Class, \
  395. TABLE_INDEX, Extracted); \
  396. }(EXTRACTOR(KEYPATH)); \
  397. }
  398. static StringRef GetInputKindName(InputKind IK);
  399. static bool FixupInvocation(CompilerInvocation &Invocation,
  400. DiagnosticsEngine &Diags, const ArgList &Args,
  401. InputKind IK) {
  402. unsigned NumErrorsBefore = Diags.getNumErrors();
  403. LangOptions &LangOpts = *Invocation.getLangOpts();
  404. CodeGenOptions &CodeGenOpts = Invocation.getCodeGenOpts();
  405. TargetOptions &TargetOpts = Invocation.getTargetOpts();
  406. FrontendOptions &FrontendOpts = Invocation.getFrontendOpts();
  407. CodeGenOpts.XRayInstrumentFunctions = LangOpts.XRayInstrument;
  408. CodeGenOpts.XRayAlwaysEmitCustomEvents = LangOpts.XRayAlwaysEmitCustomEvents;
  409. CodeGenOpts.XRayAlwaysEmitTypedEvents = LangOpts.XRayAlwaysEmitTypedEvents;
  410. CodeGenOpts.DisableFree = FrontendOpts.DisableFree;
  411. FrontendOpts.GenerateGlobalModuleIndex = FrontendOpts.UseGlobalModuleIndex;
  412. if (FrontendOpts.ShowStats)
  413. CodeGenOpts.ClearASTBeforeBackend = false;
  414. LangOpts.SanitizeCoverage = CodeGenOpts.hasSanitizeCoverage();
  415. LangOpts.ForceEmitVTables = CodeGenOpts.ForceEmitVTables;
  416. LangOpts.SpeculativeLoadHardening = CodeGenOpts.SpeculativeLoadHardening;
  417. LangOpts.CurrentModule = LangOpts.ModuleName;
  418. llvm::Triple T(TargetOpts.Triple);
  419. llvm::Triple::ArchType Arch = T.getArch();
  420. CodeGenOpts.CodeModel = TargetOpts.CodeModel;
  421. if (LangOpts.getExceptionHandling() !=
  422. LangOptions::ExceptionHandlingKind::None &&
  423. T.isWindowsMSVCEnvironment())
  424. Diags.Report(diag::err_fe_invalid_exception_model)
  425. << static_cast<unsigned>(LangOpts.getExceptionHandling()) << T.str();
  426. if (LangOpts.AppleKext && !LangOpts.CPlusPlus)
  427. Diags.Report(diag::warn_c_kext);
  428. if (Args.hasArg(OPT_fconcepts_ts))
  429. Diags.Report(diag::warn_fe_concepts_ts_flag);
  430. if (LangOpts.NewAlignOverride &&
  431. !llvm::isPowerOf2_32(LangOpts.NewAlignOverride)) {
  432. Arg *A = Args.getLastArg(OPT_fnew_alignment_EQ);
  433. Diags.Report(diag::err_fe_invalid_alignment)
  434. << A->getAsString(Args) << A->getValue();
  435. LangOpts.NewAlignOverride = 0;
  436. }
  437. // Prevent the user from specifying both -fsycl-is-device and -fsycl-is-host.
  438. if (LangOpts.SYCLIsDevice && LangOpts.SYCLIsHost)
  439. Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fsycl-is-device"
  440. << "-fsycl-is-host";
  441. if (Args.hasArg(OPT_fgnu89_inline) && LangOpts.CPlusPlus)
  442. Diags.Report(diag::err_drv_argument_not_allowed_with)
  443. << "-fgnu89-inline" << GetInputKindName(IK);
  444. if (Args.hasArg(OPT_fgpu_allow_device_init) && !LangOpts.HIP)
  445. Diags.Report(diag::warn_ignored_hip_only_option)
  446. << Args.getLastArg(OPT_fgpu_allow_device_init)->getAsString(Args);
  447. if (Args.hasArg(OPT_gpu_max_threads_per_block_EQ) && !LangOpts.HIP)
  448. Diags.Report(diag::warn_ignored_hip_only_option)
  449. << Args.getLastArg(OPT_gpu_max_threads_per_block_EQ)->getAsString(Args);
  450. // -cl-strict-aliasing needs to emit diagnostic in the case where CL > 1.0.
  451. // This option should be deprecated for CL > 1.0 because
  452. // this option was added for compatibility with OpenCL 1.0.
  453. if (Args.getLastArg(OPT_cl_strict_aliasing) &&
  454. (LangOpts.getOpenCLCompatibleVersion() > 100))
  455. Diags.Report(diag::warn_option_invalid_ocl_version)
  456. << LangOpts.getOpenCLVersionString()
  457. << Args.getLastArg(OPT_cl_strict_aliasing)->getAsString(Args);
  458. if (Arg *A = Args.getLastArg(OPT_fdefault_calling_conv_EQ)) {
  459. auto DefaultCC = LangOpts.getDefaultCallingConv();
  460. bool emitError = (DefaultCC == LangOptions::DCC_FastCall ||
  461. DefaultCC == LangOptions::DCC_StdCall) &&
  462. Arch != llvm::Triple::x86;
  463. emitError |= (DefaultCC == LangOptions::DCC_VectorCall ||
  464. DefaultCC == LangOptions::DCC_RegCall) &&
  465. !T.isX86();
  466. if (emitError)
  467. Diags.Report(diag::err_drv_argument_not_allowed_with)
  468. << A->getSpelling() << T.getTriple();
  469. }
  470. if (!CodeGenOpts.ProfileRemappingFile.empty() && CodeGenOpts.LegacyPassManager)
  471. Diags.Report(diag::err_drv_argument_only_allowed_with)
  472. << Args.getLastArg(OPT_fprofile_remapping_file_EQ)->getAsString(Args)
  473. << "-fno-legacy-pass-manager";
  474. return Diags.getNumErrors() == NumErrorsBefore;
  475. }
  476. //===----------------------------------------------------------------------===//
  477. // Deserialization (from args)
  478. //===----------------------------------------------------------------------===//
  479. static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
  480. DiagnosticsEngine &Diags) {
  481. unsigned DefaultOpt = llvm::CodeGenOpt::None;
  482. if ((IK.getLanguage() == Language::OpenCL ||
  483. IK.getLanguage() == Language::OpenCLCXX) &&
  484. !Args.hasArg(OPT_cl_opt_disable))
  485. DefaultOpt = llvm::CodeGenOpt::Default;
  486. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  487. if (A->getOption().matches(options::OPT_O0))
  488. return llvm::CodeGenOpt::None;
  489. if (A->getOption().matches(options::OPT_Ofast))
  490. return llvm::CodeGenOpt::Aggressive;
  491. assert(A->getOption().matches(options::OPT_O));
  492. StringRef S(A->getValue());
  493. if (S == "s" || S == "z")
  494. return llvm::CodeGenOpt::Default;
  495. if (S == "g")
  496. return llvm::CodeGenOpt::Less;
  497. return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
  498. }
  499. return DefaultOpt;
  500. }
  501. static unsigned getOptimizationLevelSize(ArgList &Args) {
  502. if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
  503. if (A->getOption().matches(options::OPT_O)) {
  504. switch (A->getValue()[0]) {
  505. default:
  506. return 0;
  507. case 's':
  508. return 1;
  509. case 'z':
  510. return 2;
  511. }
  512. }
  513. }
  514. return 0;
  515. }
  516. static void GenerateArg(SmallVectorImpl<const char *> &Args,
  517. llvm::opt::OptSpecifier OptSpecifier,
  518. CompilerInvocation::StringAllocator SA) {
  519. Option Opt = getDriverOptTable().getOption(OptSpecifier);
  520. denormalizeSimpleFlag(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
  521. Option::OptionClass::FlagClass, 0);
  522. }
  523. static void GenerateArg(SmallVectorImpl<const char *> &Args,
  524. llvm::opt::OptSpecifier OptSpecifier,
  525. const Twine &Value,
  526. CompilerInvocation::StringAllocator SA) {
  527. Option Opt = getDriverOptTable().getOption(OptSpecifier);
  528. denormalizeString(Args, SA(Opt.getPrefix() + Opt.getName()), SA,
  529. Opt.getKind(), 0, Value);
  530. }
  531. // Parse command line arguments into CompilerInvocation.
  532. using ParseFn =
  533. llvm::function_ref<bool(CompilerInvocation &, ArrayRef<const char *>,
  534. DiagnosticsEngine &, const char *)>;
  535. // Generate command line arguments from CompilerInvocation.
  536. using GenerateFn = llvm::function_ref<void(
  537. CompilerInvocation &, SmallVectorImpl<const char *> &,
  538. CompilerInvocation::StringAllocator)>;
  539. // May perform round-trip of command line arguments. By default, the round-trip
  540. // is enabled in assert builds. This can be overwritten at run-time via the
  541. // "-round-trip-args" and "-no-round-trip-args" command line flags.
  542. // During round-trip, the command line arguments are parsed into a dummy
  543. // instance of CompilerInvocation which is used to generate the command line
  544. // arguments again. The real CompilerInvocation instance is then created by
  545. // parsing the generated arguments, not the original ones.
  546. static bool RoundTrip(ParseFn Parse, GenerateFn Generate,
  547. CompilerInvocation &RealInvocation,
  548. CompilerInvocation &DummyInvocation,
  549. ArrayRef<const char *> CommandLineArgs,
  550. DiagnosticsEngine &Diags, const char *Argv0) {
  551. #ifndef NDEBUG
  552. bool DoRoundTripDefault = true;
  553. #else
  554. bool DoRoundTripDefault = false;
  555. #endif
  556. bool DoRoundTrip = DoRoundTripDefault;
  557. for (const auto *Arg : CommandLineArgs) {
  558. if (Arg == StringRef("-round-trip-args"))
  559. DoRoundTrip = true;
  560. if (Arg == StringRef("-no-round-trip-args"))
  561. DoRoundTrip = false;
  562. }
  563. // If round-trip was not requested, simply run the parser with the real
  564. // invocation diagnostics.
  565. if (!DoRoundTrip)
  566. return Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
  567. // Serializes quoted (and potentially escaped) arguments.
  568. auto SerializeArgs = [](ArrayRef<const char *> Args) {
  569. std::string Buffer;
  570. llvm::raw_string_ostream OS(Buffer);
  571. for (const char *Arg : Args) {
  572. llvm::sys::printArg(OS, Arg, /*Quote=*/true);
  573. OS << ' ';
  574. }
  575. OS.flush();
  576. return Buffer;
  577. };
  578. // Setup a dummy DiagnosticsEngine.
  579. DiagnosticsEngine DummyDiags(new DiagnosticIDs(), new DiagnosticOptions());
  580. DummyDiags.setClient(new TextDiagnosticBuffer());
  581. // Run the first parse on the original arguments with the dummy invocation and
  582. // diagnostics.
  583. if (!Parse(DummyInvocation, CommandLineArgs, DummyDiags, Argv0) ||
  584. DummyDiags.getNumWarnings() != 0) {
  585. // If the first parse did not succeed, it must be user mistake (invalid
  586. // command line arguments). We won't be able to generate arguments that
  587. // would reproduce the same result. Let's fail again with the real
  588. // invocation and diagnostics, so all side-effects of parsing are visible.
  589. unsigned NumWarningsBefore = Diags.getNumWarnings();
  590. auto Success = Parse(RealInvocation, CommandLineArgs, Diags, Argv0);
  591. if (!Success || Diags.getNumWarnings() != NumWarningsBefore)
  592. return Success;
  593. // Parse with original options and diagnostics succeeded even though it
  594. // shouldn't have. Something is off.
  595. Diags.Report(diag::err_cc1_round_trip_fail_then_ok);
  596. Diags.Report(diag::note_cc1_round_trip_original)
  597. << SerializeArgs(CommandLineArgs);
  598. return false;
  599. }
  600. // Setup string allocator.
  601. llvm::BumpPtrAllocator Alloc;
  602. llvm::StringSaver StringPool(Alloc);
  603. auto SA = [&StringPool](const Twine &Arg) {
  604. return StringPool.save(Arg).data();
  605. };
  606. // Generate arguments from the dummy invocation. If Generate is the
  607. // inverse of Parse, the newly generated arguments must have the same
  608. // semantics as the original.
  609. SmallVector<const char *> GeneratedArgs1;
  610. Generate(DummyInvocation, GeneratedArgs1, SA);
  611. // Run the second parse, now on the generated arguments, and with the real
  612. // invocation and diagnostics. The result is what we will end up using for the
  613. // rest of compilation, so if Generate is not inverse of Parse, something down
  614. // the line will break.
  615. bool Success2 = Parse(RealInvocation, GeneratedArgs1, Diags, Argv0);
  616. // The first parse on original arguments succeeded, but second parse of
  617. // generated arguments failed. Something must be wrong with the generator.
  618. if (!Success2) {
  619. Diags.Report(diag::err_cc1_round_trip_ok_then_fail);
  620. Diags.Report(diag::note_cc1_round_trip_generated)
  621. << 1 << SerializeArgs(GeneratedArgs1);
  622. return false;
  623. }
  624. // Generate arguments again, this time from the options we will end up using
  625. // for the rest of the compilation.
  626. SmallVector<const char *> GeneratedArgs2;
  627. Generate(RealInvocation, GeneratedArgs2, SA);
  628. // Compares two lists of generated arguments.
  629. auto Equal = [](const ArrayRef<const char *> A,
  630. const ArrayRef<const char *> B) {
  631. return std::equal(A.begin(), A.end(), B.begin(), B.end(),
  632. [](const char *AElem, const char *BElem) {
  633. return StringRef(AElem) == StringRef(BElem);
  634. });
  635. };
  636. // If we generated different arguments from what we assume are two
  637. // semantically equivalent CompilerInvocations, the Generate function may
  638. // be non-deterministic.
  639. if (!Equal(GeneratedArgs1, GeneratedArgs2)) {
  640. Diags.Report(diag::err_cc1_round_trip_mismatch);
  641. Diags.Report(diag::note_cc1_round_trip_generated)
  642. << 1 << SerializeArgs(GeneratedArgs1);
  643. Diags.Report(diag::note_cc1_round_trip_generated)
  644. << 2 << SerializeArgs(GeneratedArgs2);
  645. return false;
  646. }
  647. Diags.Report(diag::remark_cc1_round_trip_generated)
  648. << 1 << SerializeArgs(GeneratedArgs1);
  649. Diags.Report(diag::remark_cc1_round_trip_generated)
  650. << 2 << SerializeArgs(GeneratedArgs2);
  651. return Success2;
  652. }
  653. static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
  654. OptSpecifier GroupWithValue,
  655. std::vector<std::string> &Diagnostics) {
  656. for (auto *A : Args.filtered(Group)) {
  657. if (A->getOption().getKind() == Option::FlagClass) {
  658. // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
  659. // its name (minus the "W" or "R" at the beginning) to the diagnostics.
  660. Diagnostics.push_back(
  661. std::string(A->getOption().getName().drop_front(1)));
  662. } else if (A->getOption().matches(GroupWithValue)) {
  663. // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic
  664. // group. Add only the group name to the diagnostics.
  665. Diagnostics.push_back(
  666. std::string(A->getOption().getName().drop_front(1).rtrim("=-")));
  667. } else {
  668. // Otherwise, add its value (for OPT_W_Joined and similar).
  669. Diagnostics.push_back(A->getValue());
  670. }
  671. }
  672. }
  673. // Parse the Static Analyzer configuration. If \p Diags is set to nullptr,
  674. // it won't verify the input.
  675. static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
  676. DiagnosticsEngine *Diags);
  677. static void getAllNoBuiltinFuncValues(ArgList &Args,
  678. std::vector<std::string> &Funcs) {
  679. std::vector<std::string> Values = Args.getAllArgValues(OPT_fno_builtin_);
  680. auto BuiltinEnd = llvm::partition(Values, Builtin::Context::isBuiltinFunc);
  681. Funcs.insert(Funcs.end(), Values.begin(), BuiltinEnd);
  682. }
  683. static void GenerateAnalyzerArgs(AnalyzerOptions &Opts,
  684. SmallVectorImpl<const char *> &Args,
  685. CompilerInvocation::StringAllocator SA) {
  686. const AnalyzerOptions *AnalyzerOpts = &Opts;
  687. #define ANALYZER_OPTION_WITH_MARSHALLING( \
  688. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  689. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  690. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  691. MERGER, EXTRACTOR, TABLE_INDEX) \
  692. GENERATE_OPTION_WITH_MARSHALLING( \
  693. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  694. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  695. #include "clang/Driver/Options.inc"
  696. #undef ANALYZER_OPTION_WITH_MARSHALLING
  697. if (Opts.AnalysisStoreOpt != RegionStoreModel) {
  698. switch (Opts.AnalysisStoreOpt) {
  699. #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
  700. case NAME##Model: \
  701. GenerateArg(Args, OPT_analyzer_store, CMDFLAG, SA); \
  702. break;
  703. #include "clang/StaticAnalyzer/Core/Analyses.def"
  704. default:
  705. llvm_unreachable("Tried to generate unknown analysis store.");
  706. }
  707. }
  708. if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel) {
  709. switch (Opts.AnalysisConstraintsOpt) {
  710. #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
  711. case NAME##Model: \
  712. GenerateArg(Args, OPT_analyzer_constraints, CMDFLAG, SA); \
  713. break;
  714. #include "clang/StaticAnalyzer/Core/Analyses.def"
  715. default:
  716. llvm_unreachable("Tried to generate unknown analysis constraint.");
  717. }
  718. }
  719. if (Opts.AnalysisDiagOpt != PD_HTML) {
  720. switch (Opts.AnalysisDiagOpt) {
  721. #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
  722. case PD_##NAME: \
  723. GenerateArg(Args, OPT_analyzer_output, CMDFLAG, SA); \
  724. break;
  725. #include "clang/StaticAnalyzer/Core/Analyses.def"
  726. default:
  727. llvm_unreachable("Tried to generate unknown analysis diagnostic client.");
  728. }
  729. }
  730. if (Opts.AnalysisPurgeOpt != PurgeStmt) {
  731. switch (Opts.AnalysisPurgeOpt) {
  732. #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
  733. case NAME: \
  734. GenerateArg(Args, OPT_analyzer_purge, CMDFLAG, SA); \
  735. break;
  736. #include "clang/StaticAnalyzer/Core/Analyses.def"
  737. default:
  738. llvm_unreachable("Tried to generate unknown analysis purge mode.");
  739. }
  740. }
  741. if (Opts.InliningMode != NoRedundancy) {
  742. switch (Opts.InliningMode) {
  743. #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
  744. case NAME: \
  745. GenerateArg(Args, OPT_analyzer_inlining_mode, CMDFLAG, SA); \
  746. break;
  747. #include "clang/StaticAnalyzer/Core/Analyses.def"
  748. default:
  749. llvm_unreachable("Tried to generate unknown analysis inlining mode.");
  750. }
  751. }
  752. for (const auto &CP : Opts.CheckersAndPackages) {
  753. OptSpecifier Opt =
  754. CP.second ? OPT_analyzer_checker : OPT_analyzer_disable_checker;
  755. GenerateArg(Args, Opt, CP.first, SA);
  756. }
  757. AnalyzerOptions ConfigOpts;
  758. parseAnalyzerConfigs(ConfigOpts, nullptr);
  759. for (const auto &C : Opts.Config) {
  760. // Don't generate anything that came from parseAnalyzerConfigs. It would be
  761. // redundant and may not be valid on the command line.
  762. auto Entry = ConfigOpts.Config.find(C.getKey());
  763. if (Entry != ConfigOpts.Config.end() && Entry->getValue() == C.getValue())
  764. continue;
  765. GenerateArg(Args, OPT_analyzer_config, C.getKey() + "=" + C.getValue(), SA);
  766. }
  767. // Nothing to generate for FullCompilerInvocation.
  768. }
  769. static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
  770. DiagnosticsEngine &Diags) {
  771. unsigned NumErrorsBefore = Diags.getNumErrors();
  772. AnalyzerOptions *AnalyzerOpts = &Opts;
  773. #define ANALYZER_OPTION_WITH_MARSHALLING( \
  774. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  775. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  776. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  777. MERGER, EXTRACTOR, TABLE_INDEX) \
  778. PARSE_OPTION_WITH_MARSHALLING( \
  779. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  780. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  781. #include "clang/Driver/Options.inc"
  782. #undef ANALYZER_OPTION_WITH_MARSHALLING
  783. if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
  784. StringRef Name = A->getValue();
  785. AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
  786. #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
  787. .Case(CMDFLAG, NAME##Model)
  788. #include "clang/StaticAnalyzer/Core/Analyses.def"
  789. .Default(NumStores);
  790. if (Value == NumStores) {
  791. Diags.Report(diag::err_drv_invalid_value)
  792. << A->getAsString(Args) << Name;
  793. } else {
  794. Opts.AnalysisStoreOpt = Value;
  795. }
  796. }
  797. if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
  798. StringRef Name = A->getValue();
  799. AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
  800. #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
  801. .Case(CMDFLAG, NAME##Model)
  802. #include "clang/StaticAnalyzer/Core/Analyses.def"
  803. .Default(NumConstraints);
  804. if (Value == NumConstraints) {
  805. Diags.Report(diag::err_drv_invalid_value)
  806. << A->getAsString(Args) << Name;
  807. } else {
  808. Opts.AnalysisConstraintsOpt = Value;
  809. }
  810. }
  811. if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
  812. StringRef Name = A->getValue();
  813. AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
  814. #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
  815. .Case(CMDFLAG, PD_##NAME)
  816. #include "clang/StaticAnalyzer/Core/Analyses.def"
  817. .Default(NUM_ANALYSIS_DIAG_CLIENTS);
  818. if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
  819. Diags.Report(diag::err_drv_invalid_value)
  820. << A->getAsString(Args) << Name;
  821. } else {
  822. Opts.AnalysisDiagOpt = Value;
  823. }
  824. }
  825. if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
  826. StringRef Name = A->getValue();
  827. AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
  828. #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
  829. .Case(CMDFLAG, NAME)
  830. #include "clang/StaticAnalyzer/Core/Analyses.def"
  831. .Default(NumPurgeModes);
  832. if (Value == NumPurgeModes) {
  833. Diags.Report(diag::err_drv_invalid_value)
  834. << A->getAsString(Args) << Name;
  835. } else {
  836. Opts.AnalysisPurgeOpt = Value;
  837. }
  838. }
  839. if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
  840. StringRef Name = A->getValue();
  841. AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
  842. #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
  843. .Case(CMDFLAG, NAME)
  844. #include "clang/StaticAnalyzer/Core/Analyses.def"
  845. .Default(NumInliningModes);
  846. if (Value == NumInliningModes) {
  847. Diags.Report(diag::err_drv_invalid_value)
  848. << A->getAsString(Args) << Name;
  849. } else {
  850. Opts.InliningMode = Value;
  851. }
  852. }
  853. Opts.CheckersAndPackages.clear();
  854. for (const Arg *A :
  855. Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) {
  856. A->claim();
  857. bool IsEnabled = A->getOption().getID() == OPT_analyzer_checker;
  858. // We can have a list of comma separated checker names, e.g:
  859. // '-analyzer-checker=cocoa,unix'
  860. StringRef CheckerAndPackageList = A->getValue();
  861. SmallVector<StringRef, 16> CheckersAndPackages;
  862. CheckerAndPackageList.split(CheckersAndPackages, ",");
  863. for (const StringRef &CheckerOrPackage : CheckersAndPackages)
  864. Opts.CheckersAndPackages.emplace_back(std::string(CheckerOrPackage),
  865. IsEnabled);
  866. }
  867. // Go through the analyzer configuration options.
  868. for (const auto *A : Args.filtered(OPT_analyzer_config)) {
  869. // We can have a list of comma separated config names, e.g:
  870. // '-analyzer-config key1=val1,key2=val2'
  871. StringRef configList = A->getValue();
  872. SmallVector<StringRef, 4> configVals;
  873. configList.split(configVals, ",");
  874. for (const auto &configVal : configVals) {
  875. StringRef key, val;
  876. std::tie(key, val) = configVal.split("=");
  877. if (val.empty()) {
  878. Diags.Report(SourceLocation(),
  879. diag::err_analyzer_config_no_value) << configVal;
  880. break;
  881. }
  882. if (val.contains('=')) {
  883. Diags.Report(SourceLocation(),
  884. diag::err_analyzer_config_multiple_values)
  885. << configVal;
  886. break;
  887. }
  888. // TODO: Check checker options too, possibly in CheckerRegistry.
  889. // Leave unknown non-checker configs unclaimed.
  890. if (!key.contains(":") && Opts.isUnknownAnalyzerConfig(key)) {
  891. if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
  892. Diags.Report(diag::err_analyzer_config_unknown) << key;
  893. continue;
  894. }
  895. A->claim();
  896. Opts.Config[key] = std::string(val);
  897. }
  898. }
  899. if (Opts.ShouldEmitErrorsOnInvalidConfigValue)
  900. parseAnalyzerConfigs(Opts, &Diags);
  901. else
  902. parseAnalyzerConfigs(Opts, nullptr);
  903. llvm::raw_string_ostream os(Opts.FullCompilerInvocation);
  904. for (unsigned i = 0; i < Args.getNumInputArgStrings(); ++i) {
  905. if (i != 0)
  906. os << " ";
  907. os << Args.getArgString(i);
  908. }
  909. os.flush();
  910. return Diags.getNumErrors() == NumErrorsBefore;
  911. }
  912. static StringRef getStringOption(AnalyzerOptions::ConfigTable &Config,
  913. StringRef OptionName, StringRef DefaultVal) {
  914. return Config.insert({OptionName, std::string(DefaultVal)}).first->second;
  915. }
  916. static void initOption(AnalyzerOptions::ConfigTable &Config,
  917. DiagnosticsEngine *Diags,
  918. StringRef &OptionField, StringRef Name,
  919. StringRef DefaultVal) {
  920. // String options may be known to invalid (e.g. if the expected string is a
  921. // file name, but the file does not exist), those will have to be checked in
  922. // parseConfigs.
  923. OptionField = getStringOption(Config, Name, DefaultVal);
  924. }
  925. static void initOption(AnalyzerOptions::ConfigTable &Config,
  926. DiagnosticsEngine *Diags,
  927. bool &OptionField, StringRef Name, bool DefaultVal) {
  928. auto PossiblyInvalidVal = llvm::StringSwitch<Optional<bool>>(
  929. getStringOption(Config, Name, (DefaultVal ? "true" : "false")))
  930. .Case("true", true)
  931. .Case("false", false)
  932. .Default(None);
  933. if (!PossiblyInvalidVal) {
  934. if (Diags)
  935. Diags->Report(diag::err_analyzer_config_invalid_input)
  936. << Name << "a boolean";
  937. else
  938. OptionField = DefaultVal;
  939. } else
  940. OptionField = PossiblyInvalidVal.getValue();
  941. }
  942. static void initOption(AnalyzerOptions::ConfigTable &Config,
  943. DiagnosticsEngine *Diags,
  944. unsigned &OptionField, StringRef Name,
  945. unsigned DefaultVal) {
  946. OptionField = DefaultVal;
  947. bool HasFailed = getStringOption(Config, Name, std::to_string(DefaultVal))
  948. .getAsInteger(0, OptionField);
  949. if (Diags && HasFailed)
  950. Diags->Report(diag::err_analyzer_config_invalid_input)
  951. << Name << "an unsigned";
  952. }
  953. static void parseAnalyzerConfigs(AnalyzerOptions &AnOpts,
  954. DiagnosticsEngine *Diags) {
  955. // TODO: There's no need to store the entire configtable, it'd be plenty
  956. // enough tostore checker options.
  957. #define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
  958. initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEFAULT_VAL);
  959. #define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
  960. SHALLOW_VAL, DEEP_VAL) \
  961. switch (AnOpts.getUserMode()) { \
  962. case UMK_Shallow: \
  963. initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, SHALLOW_VAL); \
  964. break; \
  965. case UMK_Deep: \
  966. initOption(AnOpts.Config, Diags, AnOpts.NAME, CMDFLAG, DEEP_VAL); \
  967. break; \
  968. } \
  969. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
  970. #undef ANALYZER_OPTION
  971. #undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
  972. // At this point, AnalyzerOptions is configured. Let's validate some options.
  973. // FIXME: Here we try to validate the silenced checkers or packages are valid.
  974. // The current approach only validates the registered checkers which does not
  975. // contain the runtime enabled checkers and optimally we would validate both.
  976. if (!AnOpts.RawSilencedCheckersAndPackages.empty()) {
  977. std::vector<StringRef> Checkers =
  978. AnOpts.getRegisteredCheckers(/*IncludeExperimental=*/true);
  979. std::vector<StringRef> Packages =
  980. AnOpts.getRegisteredPackages(/*IncludeExperimental=*/true);
  981. SmallVector<StringRef, 16> CheckersAndPackages;
  982. AnOpts.RawSilencedCheckersAndPackages.split(CheckersAndPackages, ";");
  983. for (const StringRef &CheckerOrPackage : CheckersAndPackages) {
  984. if (Diags) {
  985. bool IsChecker = CheckerOrPackage.contains('.');
  986. bool IsValidName = IsChecker
  987. ? llvm::is_contained(Checkers, CheckerOrPackage)
  988. : llvm::is_contained(Packages, CheckerOrPackage);
  989. if (!IsValidName)
  990. Diags->Report(diag::err_unknown_analyzer_checker_or_package)
  991. << CheckerOrPackage;
  992. }
  993. AnOpts.SilencedCheckersAndPackages.emplace_back(CheckerOrPackage);
  994. }
  995. }
  996. if (!Diags)
  997. return;
  998. if (AnOpts.ShouldTrackConditionsDebug && !AnOpts.ShouldTrackConditions)
  999. Diags->Report(diag::err_analyzer_config_invalid_input)
  1000. << "track-conditions-debug" << "'track-conditions' to also be enabled";
  1001. if (!AnOpts.CTUDir.empty() && !llvm::sys::fs::is_directory(AnOpts.CTUDir))
  1002. Diags->Report(diag::err_analyzer_config_invalid_input) << "ctu-dir"
  1003. << "a filename";
  1004. if (!AnOpts.ModelPath.empty() &&
  1005. !llvm::sys::fs::is_directory(AnOpts.ModelPath))
  1006. Diags->Report(diag::err_analyzer_config_invalid_input) << "model-path"
  1007. << "a filename";
  1008. }
  1009. /// Generate a remark argument. This is an inverse of `ParseOptimizationRemark`.
  1010. static void
  1011. GenerateOptimizationRemark(SmallVectorImpl<const char *> &Args,
  1012. CompilerInvocation::StringAllocator SA,
  1013. OptSpecifier OptEQ, StringRef Name,
  1014. const CodeGenOptions::OptRemark &Remark) {
  1015. if (Remark.hasValidPattern()) {
  1016. GenerateArg(Args, OptEQ, Remark.Pattern, SA);
  1017. } else if (Remark.Kind == CodeGenOptions::RK_Enabled) {
  1018. GenerateArg(Args, OPT_R_Joined, Name, SA);
  1019. } else if (Remark.Kind == CodeGenOptions::RK_Disabled) {
  1020. GenerateArg(Args, OPT_R_Joined, StringRef("no-") + Name, SA);
  1021. }
  1022. }
  1023. /// Parse a remark command line argument. It may be missing, disabled/enabled by
  1024. /// '-R[no-]group' or specified with a regular expression by '-Rgroup=regexp'.
  1025. /// On top of that, it can be disabled/enabled globally by '-R[no-]everything'.
  1026. static CodeGenOptions::OptRemark
  1027. ParseOptimizationRemark(DiagnosticsEngine &Diags, ArgList &Args,
  1028. OptSpecifier OptEQ, StringRef Name) {
  1029. CodeGenOptions::OptRemark Result;
  1030. auto InitializeResultPattern = [&Diags, &Args, &Result](const Arg *A,
  1031. StringRef Pattern) {
  1032. Result.Pattern = Pattern.str();
  1033. std::string RegexError;
  1034. Result.Regex = std::make_shared<llvm::Regex>(Result.Pattern);
  1035. if (!Result.Regex->isValid(RegexError)) {
  1036. Diags.Report(diag::err_drv_optimization_remark_pattern)
  1037. << RegexError << A->getAsString(Args);
  1038. return false;
  1039. }
  1040. return true;
  1041. };
  1042. for (Arg *A : Args) {
  1043. if (A->getOption().matches(OPT_R_Joined)) {
  1044. StringRef Value = A->getValue();
  1045. if (Value == Name)
  1046. Result.Kind = CodeGenOptions::RK_Enabled;
  1047. else if (Value == "everything")
  1048. Result.Kind = CodeGenOptions::RK_EnabledEverything;
  1049. else if (Value.split('-') == std::make_pair(StringRef("no"), Name))
  1050. Result.Kind = CodeGenOptions::RK_Disabled;
  1051. else if (Value == "no-everything")
  1052. Result.Kind = CodeGenOptions::RK_DisabledEverything;
  1053. else
  1054. continue;
  1055. if (Result.Kind == CodeGenOptions::RK_Disabled ||
  1056. Result.Kind == CodeGenOptions::RK_DisabledEverything) {
  1057. Result.Pattern = "";
  1058. Result.Regex = nullptr;
  1059. } else {
  1060. InitializeResultPattern(A, ".*");
  1061. }
  1062. } else if (A->getOption().matches(OptEQ)) {
  1063. Result.Kind = CodeGenOptions::RK_WithPattern;
  1064. if (!InitializeResultPattern(A, A->getValue()))
  1065. return CodeGenOptions::OptRemark();
  1066. }
  1067. }
  1068. return Result;
  1069. }
  1070. static bool parseDiagnosticLevelMask(StringRef FlagName,
  1071. const std::vector<std::string> &Levels,
  1072. DiagnosticsEngine &Diags,
  1073. DiagnosticLevelMask &M) {
  1074. bool Success = true;
  1075. for (const auto &Level : Levels) {
  1076. DiagnosticLevelMask const PM =
  1077. llvm::StringSwitch<DiagnosticLevelMask>(Level)
  1078. .Case("note", DiagnosticLevelMask::Note)
  1079. .Case("remark", DiagnosticLevelMask::Remark)
  1080. .Case("warning", DiagnosticLevelMask::Warning)
  1081. .Case("error", DiagnosticLevelMask::Error)
  1082. .Default(DiagnosticLevelMask::None);
  1083. if (PM == DiagnosticLevelMask::None) {
  1084. Success = false;
  1085. Diags.Report(diag::err_drv_invalid_value) << FlagName << Level;
  1086. }
  1087. M = M | PM;
  1088. }
  1089. return Success;
  1090. }
  1091. static void parseSanitizerKinds(StringRef FlagName,
  1092. const std::vector<std::string> &Sanitizers,
  1093. DiagnosticsEngine &Diags, SanitizerSet &S) {
  1094. for (const auto &Sanitizer : Sanitizers) {
  1095. SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false);
  1096. if (K == SanitizerMask())
  1097. Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer;
  1098. else
  1099. S.set(K, true);
  1100. }
  1101. }
  1102. static SmallVector<StringRef, 4> serializeSanitizerKinds(SanitizerSet S) {
  1103. SmallVector<StringRef, 4> Values;
  1104. serializeSanitizerSet(S, Values);
  1105. return Values;
  1106. }
  1107. static void parseXRayInstrumentationBundle(StringRef FlagName, StringRef Bundle,
  1108. ArgList &Args, DiagnosticsEngine &D,
  1109. XRayInstrSet &S) {
  1110. llvm::SmallVector<StringRef, 2> BundleParts;
  1111. llvm::SplitString(Bundle, BundleParts, ",");
  1112. for (const auto &B : BundleParts) {
  1113. auto Mask = parseXRayInstrValue(B);
  1114. if (Mask == XRayInstrKind::None)
  1115. if (B != "none")
  1116. D.Report(diag::err_drv_invalid_value) << FlagName << Bundle;
  1117. else
  1118. S.Mask = Mask;
  1119. else if (Mask == XRayInstrKind::All)
  1120. S.Mask = Mask;
  1121. else
  1122. S.set(Mask, true);
  1123. }
  1124. }
  1125. static std::string serializeXRayInstrumentationBundle(const XRayInstrSet &S) {
  1126. llvm::SmallVector<StringRef, 2> BundleParts;
  1127. serializeXRayInstrValue(S, BundleParts);
  1128. std::string Buffer;
  1129. llvm::raw_string_ostream OS(Buffer);
  1130. llvm::interleave(BundleParts, OS, [&OS](StringRef Part) { OS << Part; }, ",");
  1131. return Buffer;
  1132. }
  1133. // Set the profile kind using fprofile-instrument-use-path.
  1134. static void setPGOUseInstrumentor(CodeGenOptions &Opts,
  1135. const Twine &ProfileName) {
  1136. auto ReaderOrErr = llvm::IndexedInstrProfReader::create(ProfileName);
  1137. // In error, return silently and let Clang PGOUse report the error message.
  1138. if (auto E = ReaderOrErr.takeError()) {
  1139. llvm::consumeError(std::move(E));
  1140. Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
  1141. return;
  1142. }
  1143. std::unique_ptr<llvm::IndexedInstrProfReader> PGOReader =
  1144. std::move(ReaderOrErr.get());
  1145. if (PGOReader->isIRLevelProfile()) {
  1146. if (PGOReader->hasCSIRLevelProfile())
  1147. Opts.setProfileUse(CodeGenOptions::ProfileCSIRInstr);
  1148. else
  1149. Opts.setProfileUse(CodeGenOptions::ProfileIRInstr);
  1150. } else
  1151. Opts.setProfileUse(CodeGenOptions::ProfileClangInstr);
  1152. }
  1153. void CompilerInvocation::GenerateCodeGenArgs(
  1154. const CodeGenOptions &Opts, SmallVectorImpl<const char *> &Args,
  1155. StringAllocator SA, const llvm::Triple &T, const std::string &OutputFile,
  1156. const LangOptions *LangOpts) {
  1157. const CodeGenOptions &CodeGenOpts = Opts;
  1158. if (Opts.OptimizationLevel == 0)
  1159. GenerateArg(Args, OPT_O0, SA);
  1160. else
  1161. GenerateArg(Args, OPT_O, Twine(Opts.OptimizationLevel), SA);
  1162. #define CODEGEN_OPTION_WITH_MARSHALLING( \
  1163. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1164. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1165. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1166. MERGER, EXTRACTOR, TABLE_INDEX) \
  1167. GENERATE_OPTION_WITH_MARSHALLING( \
  1168. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  1169. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  1170. #include "clang/Driver/Options.inc"
  1171. #undef CODEGEN_OPTION_WITH_MARSHALLING
  1172. if (Opts.OptimizationLevel > 0) {
  1173. if (Opts.Inlining == CodeGenOptions::NormalInlining)
  1174. GenerateArg(Args, OPT_finline_functions, SA);
  1175. else if (Opts.Inlining == CodeGenOptions::OnlyHintInlining)
  1176. GenerateArg(Args, OPT_finline_hint_functions, SA);
  1177. else if (Opts.Inlining == CodeGenOptions::OnlyAlwaysInlining)
  1178. GenerateArg(Args, OPT_fno_inline, SA);
  1179. }
  1180. if (Opts.DirectAccessExternalData && LangOpts->PICLevel != 0)
  1181. GenerateArg(Args, OPT_fdirect_access_external_data, SA);
  1182. else if (!Opts.DirectAccessExternalData && LangOpts->PICLevel == 0)
  1183. GenerateArg(Args, OPT_fno_direct_access_external_data, SA);
  1184. Optional<StringRef> DebugInfoVal;
  1185. switch (Opts.DebugInfo) {
  1186. case codegenoptions::DebugLineTablesOnly:
  1187. DebugInfoVal = "line-tables-only";
  1188. break;
  1189. case codegenoptions::DebugDirectivesOnly:
  1190. DebugInfoVal = "line-directives-only";
  1191. break;
  1192. case codegenoptions::DebugInfoConstructor:
  1193. DebugInfoVal = "constructor";
  1194. break;
  1195. case codegenoptions::LimitedDebugInfo:
  1196. DebugInfoVal = "limited";
  1197. break;
  1198. case codegenoptions::FullDebugInfo:
  1199. DebugInfoVal = "standalone";
  1200. break;
  1201. case codegenoptions::UnusedTypeInfo:
  1202. DebugInfoVal = "unused-types";
  1203. break;
  1204. case codegenoptions::NoDebugInfo: // default value
  1205. DebugInfoVal = None;
  1206. break;
  1207. case codegenoptions::LocTrackingOnly: // implied value
  1208. DebugInfoVal = None;
  1209. break;
  1210. }
  1211. if (DebugInfoVal)
  1212. GenerateArg(Args, OPT_debug_info_kind_EQ, *DebugInfoVal, SA);
  1213. for (const auto &Prefix : Opts.DebugPrefixMap)
  1214. GenerateArg(Args, OPT_fdebug_prefix_map_EQ,
  1215. Prefix.first + "=" + Prefix.second, SA);
  1216. for (const auto &Prefix : Opts.CoveragePrefixMap)
  1217. GenerateArg(Args, OPT_fcoverage_prefix_map_EQ,
  1218. Prefix.first + "=" + Prefix.second, SA);
  1219. if (Opts.NewStructPathTBAA)
  1220. GenerateArg(Args, OPT_new_struct_path_tbaa, SA);
  1221. if (Opts.OptimizeSize == 1)
  1222. GenerateArg(Args, OPT_O, "s", SA);
  1223. else if (Opts.OptimizeSize == 2)
  1224. GenerateArg(Args, OPT_O, "z", SA);
  1225. // SimplifyLibCalls is set only in the absence of -fno-builtin and
  1226. // -ffreestanding. We'll consider that when generating them.
  1227. // NoBuiltinFuncs are generated by LangOptions.
  1228. if (Opts.UnrollLoops && Opts.OptimizationLevel <= 1)
  1229. GenerateArg(Args, OPT_funroll_loops, SA);
  1230. else if (!Opts.UnrollLoops && Opts.OptimizationLevel > 1)
  1231. GenerateArg(Args, OPT_fno_unroll_loops, SA);
  1232. if (!Opts.BinutilsVersion.empty())
  1233. GenerateArg(Args, OPT_fbinutils_version_EQ, Opts.BinutilsVersion, SA);
  1234. if (Opts.DebugNameTable ==
  1235. static_cast<unsigned>(llvm::DICompileUnit::DebugNameTableKind::GNU))
  1236. GenerateArg(Args, OPT_ggnu_pubnames, SA);
  1237. else if (Opts.DebugNameTable ==
  1238. static_cast<unsigned>(
  1239. llvm::DICompileUnit::DebugNameTableKind::Default))
  1240. GenerateArg(Args, OPT_gpubnames, SA);
  1241. auto TNK = Opts.getDebugSimpleTemplateNames();
  1242. if (TNK != codegenoptions::DebugTemplateNamesKind::Full) {
  1243. if (TNK == codegenoptions::DebugTemplateNamesKind::Simple)
  1244. GenerateArg(Args, OPT_gsimple_template_names_EQ, "simple", SA);
  1245. else if (TNK == codegenoptions::DebugTemplateNamesKind::Mangled)
  1246. GenerateArg(Args, OPT_gsimple_template_names_EQ, "mangled", SA);
  1247. }
  1248. // ProfileInstrumentUsePath is marshalled automatically, no need to generate
  1249. // it or PGOUseInstrumentor.
  1250. if (Opts.TimePasses) {
  1251. if (Opts.TimePassesPerRun)
  1252. GenerateArg(Args, OPT_ftime_report_EQ, "per-pass-run", SA);
  1253. else
  1254. GenerateArg(Args, OPT_ftime_report, SA);
  1255. }
  1256. if (Opts.PrepareForLTO && !Opts.PrepareForThinLTO)
  1257. GenerateArg(Args, OPT_flto_EQ, "full", SA);
  1258. if (Opts.PrepareForThinLTO)
  1259. GenerateArg(Args, OPT_flto_EQ, "thin", SA);
  1260. if (!Opts.ThinLTOIndexFile.empty())
  1261. GenerateArg(Args, OPT_fthinlto_index_EQ, Opts.ThinLTOIndexFile, SA);
  1262. if (Opts.SaveTempsFilePrefix == OutputFile)
  1263. GenerateArg(Args, OPT_save_temps_EQ, "obj", SA);
  1264. StringRef MemProfileBasename("memprof.profraw");
  1265. if (!Opts.MemoryProfileOutput.empty()) {
  1266. if (Opts.MemoryProfileOutput == MemProfileBasename) {
  1267. GenerateArg(Args, OPT_fmemory_profile, SA);
  1268. } else {
  1269. size_t ArgLength =
  1270. Opts.MemoryProfileOutput.size() - MemProfileBasename.size();
  1271. GenerateArg(Args, OPT_fmemory_profile_EQ,
  1272. Opts.MemoryProfileOutput.substr(0, ArgLength), SA);
  1273. }
  1274. }
  1275. if (memcmp(Opts.CoverageVersion, "408*", 4) != 0)
  1276. GenerateArg(Args, OPT_coverage_version_EQ,
  1277. StringRef(Opts.CoverageVersion, 4), SA);
  1278. // TODO: Check if we need to generate arguments stored in CmdArgs. (Namely
  1279. // '-fembed_bitcode', which does not map to any CompilerInvocation field and
  1280. // won't be generated.)
  1281. if (Opts.XRayInstrumentationBundle.Mask != XRayInstrKind::All) {
  1282. std::string InstrBundle =
  1283. serializeXRayInstrumentationBundle(Opts.XRayInstrumentationBundle);
  1284. if (!InstrBundle.empty())
  1285. GenerateArg(Args, OPT_fxray_instrumentation_bundle, InstrBundle, SA);
  1286. }
  1287. if (Opts.CFProtectionReturn && Opts.CFProtectionBranch)
  1288. GenerateArg(Args, OPT_fcf_protection_EQ, "full", SA);
  1289. else if (Opts.CFProtectionReturn)
  1290. GenerateArg(Args, OPT_fcf_protection_EQ, "return", SA);
  1291. else if (Opts.CFProtectionBranch)
  1292. GenerateArg(Args, OPT_fcf_protection_EQ, "branch", SA);
  1293. for (const auto &F : Opts.LinkBitcodeFiles) {
  1294. bool Builtint = F.LinkFlags == llvm::Linker::Flags::LinkOnlyNeeded &&
  1295. F.PropagateAttrs && F.Internalize;
  1296. GenerateArg(Args,
  1297. Builtint ? OPT_mlink_builtin_bitcode : OPT_mlink_bitcode_file,
  1298. F.Filename, SA);
  1299. }
  1300. // TODO: Consider removing marshalling annotations from f[no_]emulated_tls.
  1301. // That would make it easy to generate the option only **once** if it was
  1302. // explicitly set to non-default value.
  1303. if (Opts.ExplicitEmulatedTLS) {
  1304. GenerateArg(
  1305. Args, Opts.EmulatedTLS ? OPT_femulated_tls : OPT_fno_emulated_tls, SA);
  1306. }
  1307. if (Opts.FPDenormalMode != llvm::DenormalMode::getIEEE())
  1308. GenerateArg(Args, OPT_fdenormal_fp_math_EQ, Opts.FPDenormalMode.str(), SA);
  1309. if (Opts.FP32DenormalMode != llvm::DenormalMode::getIEEE())
  1310. GenerateArg(Args, OPT_fdenormal_fp_math_f32_EQ, Opts.FP32DenormalMode.str(),
  1311. SA);
  1312. if (Opts.StructReturnConvention == CodeGenOptions::SRCK_OnStack) {
  1313. OptSpecifier Opt =
  1314. T.isPPC32() ? OPT_maix_struct_return : OPT_fpcc_struct_return;
  1315. GenerateArg(Args, Opt, SA);
  1316. } else if (Opts.StructReturnConvention == CodeGenOptions::SRCK_InRegs) {
  1317. OptSpecifier Opt =
  1318. T.isPPC32() ? OPT_msvr4_struct_return : OPT_freg_struct_return;
  1319. GenerateArg(Args, Opt, SA);
  1320. }
  1321. if (Opts.EnableAIXExtendedAltivecABI)
  1322. GenerateArg(Args, OPT_mabi_EQ_vec_extabi, SA);
  1323. if (!Opts.OptRecordPasses.empty())
  1324. GenerateArg(Args, OPT_opt_record_passes, Opts.OptRecordPasses, SA);
  1325. if (!Opts.OptRecordFormat.empty())
  1326. GenerateArg(Args, OPT_opt_record_format, Opts.OptRecordFormat, SA);
  1327. GenerateOptimizationRemark(Args, SA, OPT_Rpass_EQ, "pass",
  1328. Opts.OptimizationRemark);
  1329. GenerateOptimizationRemark(Args, SA, OPT_Rpass_missed_EQ, "pass-missed",
  1330. Opts.OptimizationRemarkMissed);
  1331. GenerateOptimizationRemark(Args, SA, OPT_Rpass_analysis_EQ, "pass-analysis",
  1332. Opts.OptimizationRemarkAnalysis);
  1333. GenerateArg(Args, OPT_fdiagnostics_hotness_threshold_EQ,
  1334. Opts.DiagnosticsHotnessThreshold
  1335. ? Twine(*Opts.DiagnosticsHotnessThreshold)
  1336. : "auto",
  1337. SA);
  1338. for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeRecover))
  1339. GenerateArg(Args, OPT_fsanitize_recover_EQ, Sanitizer, SA);
  1340. for (StringRef Sanitizer : serializeSanitizerKinds(Opts.SanitizeTrap))
  1341. GenerateArg(Args, OPT_fsanitize_trap_EQ, Sanitizer, SA);
  1342. if (!Opts.EmitVersionIdentMetadata)
  1343. GenerateArg(Args, OPT_Qn, SA);
  1344. switch (Opts.FiniteLoops) {
  1345. case CodeGenOptions::FiniteLoopsKind::Language:
  1346. break;
  1347. case CodeGenOptions::FiniteLoopsKind::Always:
  1348. GenerateArg(Args, OPT_ffinite_loops, SA);
  1349. break;
  1350. case CodeGenOptions::FiniteLoopsKind::Never:
  1351. GenerateArg(Args, OPT_fno_finite_loops, SA);
  1352. break;
  1353. }
  1354. }
  1355. bool CompilerInvocation::ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args,
  1356. InputKind IK,
  1357. DiagnosticsEngine &Diags,
  1358. const llvm::Triple &T,
  1359. const std::string &OutputFile,
  1360. const LangOptions &LangOptsRef) {
  1361. unsigned NumErrorsBefore = Diags.getNumErrors();
  1362. unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
  1363. // TODO: This could be done in Driver
  1364. unsigned MaxOptLevel = 3;
  1365. if (OptimizationLevel > MaxOptLevel) {
  1366. // If the optimization level is not supported, fall back on the default
  1367. // optimization
  1368. Diags.Report(diag::warn_drv_optimization_value)
  1369. << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
  1370. OptimizationLevel = MaxOptLevel;
  1371. }
  1372. Opts.OptimizationLevel = OptimizationLevel;
  1373. // The key paths of codegen options defined in Options.td start with
  1374. // "CodeGenOpts.". Let's provide the expected variable name and type.
  1375. CodeGenOptions &CodeGenOpts = Opts;
  1376. // Some codegen options depend on language options. Let's provide the expected
  1377. // variable name and type.
  1378. const LangOptions *LangOpts = &LangOptsRef;
  1379. #define CODEGEN_OPTION_WITH_MARSHALLING( \
  1380. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1381. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1382. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1383. MERGER, EXTRACTOR, TABLE_INDEX) \
  1384. PARSE_OPTION_WITH_MARSHALLING( \
  1385. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  1386. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  1387. #include "clang/Driver/Options.inc"
  1388. #undef CODEGEN_OPTION_WITH_MARSHALLING
  1389. // At O0 we want to fully disable inlining outside of cases marked with
  1390. // 'alwaysinline' that are required for correctness.
  1391. Opts.setInlining((Opts.OptimizationLevel == 0)
  1392. ? CodeGenOptions::OnlyAlwaysInlining
  1393. : CodeGenOptions::NormalInlining);
  1394. // Explicit inlining flags can disable some or all inlining even at
  1395. // optimization levels above zero.
  1396. if (Arg *InlineArg = Args.getLastArg(
  1397. options::OPT_finline_functions, options::OPT_finline_hint_functions,
  1398. options::OPT_fno_inline_functions, options::OPT_fno_inline)) {
  1399. if (Opts.OptimizationLevel > 0) {
  1400. const Option &InlineOpt = InlineArg->getOption();
  1401. if (InlineOpt.matches(options::OPT_finline_functions))
  1402. Opts.setInlining(CodeGenOptions::NormalInlining);
  1403. else if (InlineOpt.matches(options::OPT_finline_hint_functions))
  1404. Opts.setInlining(CodeGenOptions::OnlyHintInlining);
  1405. else
  1406. Opts.setInlining(CodeGenOptions::OnlyAlwaysInlining);
  1407. }
  1408. }
  1409. // PIC defaults to -fno-direct-access-external-data while non-PIC defaults to
  1410. // -fdirect-access-external-data.
  1411. Opts.DirectAccessExternalData =
  1412. Args.hasArg(OPT_fdirect_access_external_data) ||
  1413. (!Args.hasArg(OPT_fno_direct_access_external_data) &&
  1414. LangOpts->PICLevel == 0);
  1415. if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) {
  1416. unsigned Val =
  1417. llvm::StringSwitch<unsigned>(A->getValue())
  1418. .Case("line-tables-only", codegenoptions::DebugLineTablesOnly)
  1419. .Case("line-directives-only", codegenoptions::DebugDirectivesOnly)
  1420. .Case("constructor", codegenoptions::DebugInfoConstructor)
  1421. .Case("limited", codegenoptions::LimitedDebugInfo)
  1422. .Case("standalone", codegenoptions::FullDebugInfo)
  1423. .Case("unused-types", codegenoptions::UnusedTypeInfo)
  1424. .Default(~0U);
  1425. if (Val == ~0U)
  1426. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
  1427. << A->getValue();
  1428. else
  1429. Opts.setDebugInfo(static_cast<codegenoptions::DebugInfoKind>(Val));
  1430. }
  1431. // If -fuse-ctor-homing is set and limited debug info is already on, then use
  1432. // constructor homing, and vice versa for -fno-use-ctor-homing.
  1433. if (const Arg *A =
  1434. Args.getLastArg(OPT_fuse_ctor_homing, OPT_fno_use_ctor_homing)) {
  1435. if (A->getOption().matches(OPT_fuse_ctor_homing) &&
  1436. Opts.getDebugInfo() == codegenoptions::LimitedDebugInfo)
  1437. Opts.setDebugInfo(codegenoptions::DebugInfoConstructor);
  1438. if (A->getOption().matches(OPT_fno_use_ctor_homing) &&
  1439. Opts.getDebugInfo() == codegenoptions::DebugInfoConstructor)
  1440. Opts.setDebugInfo(codegenoptions::LimitedDebugInfo);
  1441. }
  1442. for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) {
  1443. auto Split = StringRef(Arg).split('=');
  1444. Opts.DebugPrefixMap.insert(
  1445. {std::string(Split.first), std::string(Split.second)});
  1446. }
  1447. for (const auto &Arg : Args.getAllArgValues(OPT_fcoverage_prefix_map_EQ)) {
  1448. auto Split = StringRef(Arg).split('=');
  1449. Opts.CoveragePrefixMap.insert(
  1450. {std::string(Split.first), std::string(Split.second)});
  1451. }
  1452. const llvm::Triple::ArchType DebugEntryValueArchs[] = {
  1453. llvm::Triple::x86, llvm::Triple::x86_64, llvm::Triple::aarch64,
  1454. llvm::Triple::arm, llvm::Triple::armeb, llvm::Triple::mips,
  1455. llvm::Triple::mipsel, llvm::Triple::mips64, llvm::Triple::mips64el};
  1456. if (Opts.OptimizationLevel > 0 && Opts.hasReducedDebugInfo() &&
  1457. llvm::is_contained(DebugEntryValueArchs, T.getArch()))
  1458. Opts.EmitCallSiteInfo = true;
  1459. if (!Opts.EnableDIPreservationVerify && Opts.DIBugsReportFilePath.size()) {
  1460. Diags.Report(diag::warn_ignoring_verify_debuginfo_preserve_export)
  1461. << Opts.DIBugsReportFilePath;
  1462. Opts.DIBugsReportFilePath = "";
  1463. }
  1464. Opts.NewStructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa) &&
  1465. Args.hasArg(OPT_new_struct_path_tbaa);
  1466. Opts.OptimizeSize = getOptimizationLevelSize(Args);
  1467. Opts.SimplifyLibCalls = !LangOpts->NoBuiltin;
  1468. if (Opts.SimplifyLibCalls)
  1469. Opts.NoBuiltinFuncs = LangOpts->NoBuiltinFuncs;
  1470. Opts.UnrollLoops =
  1471. Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
  1472. (Opts.OptimizationLevel > 1));
  1473. Opts.BinutilsVersion =
  1474. std::string(Args.getLastArgValue(OPT_fbinutils_version_EQ));
  1475. Opts.DebugNameTable = static_cast<unsigned>(
  1476. Args.hasArg(OPT_ggnu_pubnames)
  1477. ? llvm::DICompileUnit::DebugNameTableKind::GNU
  1478. : Args.hasArg(OPT_gpubnames)
  1479. ? llvm::DICompileUnit::DebugNameTableKind::Default
  1480. : llvm::DICompileUnit::DebugNameTableKind::None);
  1481. if (const Arg *A = Args.getLastArg(OPT_gsimple_template_names_EQ)) {
  1482. StringRef Value = A->getValue();
  1483. if (Value != "simple" && Value != "mangled")
  1484. Diags.Report(diag::err_drv_unsupported_option_argument)
  1485. << A->getOption().getName() << A->getValue();
  1486. Opts.setDebugSimpleTemplateNames(
  1487. StringRef(A->getValue()) == "simple"
  1488. ? codegenoptions::DebugTemplateNamesKind::Simple
  1489. : codegenoptions::DebugTemplateNamesKind::Mangled);
  1490. }
  1491. if (!Opts.ProfileInstrumentUsePath.empty())
  1492. setPGOUseInstrumentor(Opts, Opts.ProfileInstrumentUsePath);
  1493. if (const Arg *A = Args.getLastArg(OPT_ftime_report, OPT_ftime_report_EQ)) {
  1494. Opts.TimePasses = true;
  1495. // -ftime-report= is only for new pass manager.
  1496. if (A->getOption().getID() == OPT_ftime_report_EQ) {
  1497. if (Opts.LegacyPassManager)
  1498. Diags.Report(diag::err_drv_argument_only_allowed_with)
  1499. << A->getAsString(Args) << "-fno-legacy-pass-manager";
  1500. StringRef Val = A->getValue();
  1501. if (Val == "per-pass")
  1502. Opts.TimePassesPerRun = false;
  1503. else if (Val == "per-pass-run")
  1504. Opts.TimePassesPerRun = true;
  1505. else
  1506. Diags.Report(diag::err_drv_invalid_value)
  1507. << A->getAsString(Args) << A->getValue();
  1508. }
  1509. }
  1510. Opts.PrepareForLTO = false;
  1511. Opts.PrepareForThinLTO = false;
  1512. if (Arg *A = Args.getLastArg(OPT_flto_EQ)) {
  1513. Opts.PrepareForLTO = true;
  1514. StringRef S = A->getValue();
  1515. if (S == "thin")
  1516. Opts.PrepareForThinLTO = true;
  1517. else if (S != "full")
  1518. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << S;
  1519. }
  1520. if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) {
  1521. if (IK.getLanguage() != Language::LLVM_IR)
  1522. Diags.Report(diag::err_drv_argument_only_allowed_with)
  1523. << A->getAsString(Args) << "-x ir";
  1524. Opts.ThinLTOIndexFile =
  1525. std::string(Args.getLastArgValue(OPT_fthinlto_index_EQ));
  1526. }
  1527. if (Arg *A = Args.getLastArg(OPT_save_temps_EQ))
  1528. Opts.SaveTempsFilePrefix =
  1529. llvm::StringSwitch<std::string>(A->getValue())
  1530. .Case("obj", OutputFile)
  1531. .Default(llvm::sys::path::filename(OutputFile).str());
  1532. // The memory profile runtime appends the pid to make this name more unique.
  1533. const char *MemProfileBasename = "memprof.profraw";
  1534. if (Args.hasArg(OPT_fmemory_profile_EQ)) {
  1535. SmallString<128> Path(
  1536. std::string(Args.getLastArgValue(OPT_fmemory_profile_EQ)));
  1537. llvm::sys::path::append(Path, MemProfileBasename);
  1538. Opts.MemoryProfileOutput = std::string(Path);
  1539. } else if (Args.hasArg(OPT_fmemory_profile))
  1540. Opts.MemoryProfileOutput = MemProfileBasename;
  1541. memcpy(Opts.CoverageVersion, "408*", 4);
  1542. if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
  1543. if (Args.hasArg(OPT_coverage_version_EQ)) {
  1544. StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
  1545. if (CoverageVersion.size() != 4) {
  1546. Diags.Report(diag::err_drv_invalid_value)
  1547. << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
  1548. << CoverageVersion;
  1549. } else {
  1550. memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
  1551. }
  1552. }
  1553. }
  1554. // FIXME: For backend options that are not yet recorded as function
  1555. // attributes in the IR, keep track of them so we can embed them in a
  1556. // separate data section and use them when building the bitcode.
  1557. for (const auto &A : Args) {
  1558. // Do not encode output and input.
  1559. if (A->getOption().getID() == options::OPT_o ||
  1560. A->getOption().getID() == options::OPT_INPUT ||
  1561. A->getOption().getID() == options::OPT_x ||
  1562. A->getOption().getID() == options::OPT_fembed_bitcode ||
  1563. A->getOption().matches(options::OPT_W_Group))
  1564. continue;
  1565. ArgStringList ASL;
  1566. A->render(Args, ASL);
  1567. for (const auto &arg : ASL) {
  1568. StringRef ArgStr(arg);
  1569. Opts.CmdArgs.insert(Opts.CmdArgs.end(), ArgStr.begin(), ArgStr.end());
  1570. // using \00 to separate each commandline options.
  1571. Opts.CmdArgs.push_back('\0');
  1572. }
  1573. }
  1574. auto XRayInstrBundles =
  1575. Args.getAllArgValues(OPT_fxray_instrumentation_bundle);
  1576. if (XRayInstrBundles.empty())
  1577. Opts.XRayInstrumentationBundle.Mask = XRayInstrKind::All;
  1578. else
  1579. for (const auto &A : XRayInstrBundles)
  1580. parseXRayInstrumentationBundle("-fxray-instrumentation-bundle=", A, Args,
  1581. Diags, Opts.XRayInstrumentationBundle);
  1582. if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
  1583. StringRef Name = A->getValue();
  1584. if (Name == "full") {
  1585. Opts.CFProtectionReturn = 1;
  1586. Opts.CFProtectionBranch = 1;
  1587. } else if (Name == "return")
  1588. Opts.CFProtectionReturn = 1;
  1589. else if (Name == "branch")
  1590. Opts.CFProtectionBranch = 1;
  1591. else if (Name != "none")
  1592. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
  1593. }
  1594. if (Opts.PrepareForLTO && Args.hasArg(OPT_mibt_seal))
  1595. Opts.IBTSeal = 1;
  1596. for (auto *A :
  1597. Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_builtin_bitcode)) {
  1598. CodeGenOptions::BitcodeFileToLink F;
  1599. F.Filename = A->getValue();
  1600. if (A->getOption().matches(OPT_mlink_builtin_bitcode)) {
  1601. F.LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded;
  1602. // When linking CUDA bitcode, propagate function attributes so that
  1603. // e.g. libdevice gets fast-math attrs if we're building with fast-math.
  1604. F.PropagateAttrs = true;
  1605. F.Internalize = true;
  1606. }
  1607. Opts.LinkBitcodeFiles.push_back(F);
  1608. }
  1609. if (Args.getLastArg(OPT_femulated_tls) ||
  1610. Args.getLastArg(OPT_fno_emulated_tls)) {
  1611. Opts.ExplicitEmulatedTLS = true;
  1612. }
  1613. if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
  1614. if (T.isOSAIX()) {
  1615. StringRef Name = A->getValue();
  1616. if (Name != "global-dynamic")
  1617. Diags.Report(diag::err_aix_unsupported_tls_model) << Name;
  1618. }
  1619. }
  1620. if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_EQ)) {
  1621. StringRef Val = A->getValue();
  1622. Opts.FPDenormalMode = llvm::parseDenormalFPAttribute(Val);
  1623. if (!Opts.FPDenormalMode.isValid())
  1624. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
  1625. }
  1626. if (Arg *A = Args.getLastArg(OPT_fdenormal_fp_math_f32_EQ)) {
  1627. StringRef Val = A->getValue();
  1628. Opts.FP32DenormalMode = llvm::parseDenormalFPAttribute(Val);
  1629. if (!Opts.FP32DenormalMode.isValid())
  1630. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
  1631. }
  1632. // X86_32 has -fppc-struct-return and -freg-struct-return.
  1633. // PPC32 has -maix-struct-return and -msvr4-struct-return.
  1634. if (Arg *A =
  1635. Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return,
  1636. OPT_maix_struct_return, OPT_msvr4_struct_return)) {
  1637. // TODO: We might want to consider enabling these options on AIX in the
  1638. // future.
  1639. if (T.isOSAIX())
  1640. Diags.Report(diag::err_drv_unsupported_opt_for_target)
  1641. << A->getSpelling() << T.str();
  1642. const Option &O = A->getOption();
  1643. if (O.matches(OPT_fpcc_struct_return) ||
  1644. O.matches(OPT_maix_struct_return)) {
  1645. Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
  1646. } else {
  1647. assert(O.matches(OPT_freg_struct_return) ||
  1648. O.matches(OPT_msvr4_struct_return));
  1649. Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
  1650. }
  1651. }
  1652. if (Arg *A =
  1653. Args.getLastArg(OPT_mabi_EQ_vec_default, OPT_mabi_EQ_vec_extabi)) {
  1654. if (!T.isOSAIX())
  1655. Diags.Report(diag::err_drv_unsupported_opt_for_target)
  1656. << A->getSpelling() << T.str();
  1657. const Option &O = A->getOption();
  1658. Opts.EnableAIXExtendedAltivecABI = O.matches(OPT_mabi_EQ_vec_extabi);
  1659. }
  1660. bool NeedLocTracking = false;
  1661. if (!Opts.OptRecordFile.empty())
  1662. NeedLocTracking = true;
  1663. if (Arg *A = Args.getLastArg(OPT_opt_record_passes)) {
  1664. Opts.OptRecordPasses = A->getValue();
  1665. NeedLocTracking = true;
  1666. }
  1667. if (Arg *A = Args.getLastArg(OPT_opt_record_format)) {
  1668. Opts.OptRecordFormat = A->getValue();
  1669. NeedLocTracking = true;
  1670. }
  1671. Opts.OptimizationRemark =
  1672. ParseOptimizationRemark(Diags, Args, OPT_Rpass_EQ, "pass");
  1673. Opts.OptimizationRemarkMissed =
  1674. ParseOptimizationRemark(Diags, Args, OPT_Rpass_missed_EQ, "pass-missed");
  1675. Opts.OptimizationRemarkAnalysis = ParseOptimizationRemark(
  1676. Diags, Args, OPT_Rpass_analysis_EQ, "pass-analysis");
  1677. NeedLocTracking |= Opts.OptimizationRemark.hasValidPattern() ||
  1678. Opts.OptimizationRemarkMissed.hasValidPattern() ||
  1679. Opts.OptimizationRemarkAnalysis.hasValidPattern();
  1680. bool UsingSampleProfile = !Opts.SampleProfileFile.empty();
  1681. bool UsingProfile = UsingSampleProfile ||
  1682. (Opts.getProfileUse() != CodeGenOptions::ProfileNone);
  1683. if (Opts.DiagnosticsWithHotness && !UsingProfile &&
  1684. // An IR file will contain PGO as metadata
  1685. IK.getLanguage() != Language::LLVM_IR)
  1686. Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
  1687. << "-fdiagnostics-show-hotness";
  1688. // Parse remarks hotness threshold. Valid value is either integer or 'auto'.
  1689. if (auto *arg =
  1690. Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
  1691. auto ResultOrErr =
  1692. llvm::remarks::parseHotnessThresholdOption(arg->getValue());
  1693. if (!ResultOrErr) {
  1694. Diags.Report(diag::err_drv_invalid_diagnotics_hotness_threshold)
  1695. << "-fdiagnostics-hotness-threshold=";
  1696. } else {
  1697. Opts.DiagnosticsHotnessThreshold = *ResultOrErr;
  1698. if ((!Opts.DiagnosticsHotnessThreshold.hasValue() ||
  1699. Opts.DiagnosticsHotnessThreshold.getValue() > 0) &&
  1700. !UsingProfile)
  1701. Diags.Report(diag::warn_drv_diagnostics_hotness_requires_pgo)
  1702. << "-fdiagnostics-hotness-threshold=";
  1703. }
  1704. }
  1705. // If the user requested to use a sample profile for PGO, then the
  1706. // backend will need to track source location information so the profile
  1707. // can be incorporated into the IR.
  1708. if (UsingSampleProfile)
  1709. NeedLocTracking = true;
  1710. if (!Opts.StackUsageOutput.empty())
  1711. NeedLocTracking = true;
  1712. // If the user requested a flag that requires source locations available in
  1713. // the backend, make sure that the backend tracks source location information.
  1714. if (NeedLocTracking && Opts.getDebugInfo() == codegenoptions::NoDebugInfo)
  1715. Opts.setDebugInfo(codegenoptions::LocTrackingOnly);
  1716. // Parse -fsanitize-recover= arguments.
  1717. // FIXME: Report unrecoverable sanitizers incorrectly specified here.
  1718. parseSanitizerKinds("-fsanitize-recover=",
  1719. Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags,
  1720. Opts.SanitizeRecover);
  1721. parseSanitizerKinds("-fsanitize-trap=",
  1722. Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags,
  1723. Opts.SanitizeTrap);
  1724. Opts.EmitVersionIdentMetadata = Args.hasFlag(OPT_Qy, OPT_Qn, true);
  1725. if (Args.hasArg(options::OPT_ffinite_loops))
  1726. Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Always;
  1727. else if (Args.hasArg(options::OPT_fno_finite_loops))
  1728. Opts.FiniteLoops = CodeGenOptions::FiniteLoopsKind::Never;
  1729. Opts.EmitIEEENaNCompliantInsts =
  1730. Args.hasFlag(options::OPT_mamdgpu_ieee, options::OPT_mno_amdgpu_ieee);
  1731. if (!Opts.EmitIEEENaNCompliantInsts && !LangOptsRef.NoHonorNaNs)
  1732. Diags.Report(diag::err_drv_amdgpu_ieee_without_no_honor_nans);
  1733. return Diags.getNumErrors() == NumErrorsBefore;
  1734. }
  1735. static void
  1736. GenerateDependencyOutputArgs(const DependencyOutputOptions &Opts,
  1737. SmallVectorImpl<const char *> &Args,
  1738. CompilerInvocation::StringAllocator SA) {
  1739. const DependencyOutputOptions &DependencyOutputOpts = Opts;
  1740. #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
  1741. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1742. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1743. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1744. MERGER, EXTRACTOR, TABLE_INDEX) \
  1745. GENERATE_OPTION_WITH_MARSHALLING( \
  1746. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  1747. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  1748. #include "clang/Driver/Options.inc"
  1749. #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
  1750. if (Opts.ShowIncludesDest != ShowIncludesDestination::None)
  1751. GenerateArg(Args, OPT_show_includes, SA);
  1752. for (const auto &Dep : Opts.ExtraDeps) {
  1753. switch (Dep.second) {
  1754. case EDK_SanitizeIgnorelist:
  1755. // Sanitizer ignorelist arguments are generated from LanguageOptions.
  1756. continue;
  1757. case EDK_ModuleFile:
  1758. // Module file arguments are generated from FrontendOptions and
  1759. // HeaderSearchOptions.
  1760. continue;
  1761. case EDK_ProfileList:
  1762. // Profile list arguments are generated from LanguageOptions via the
  1763. // marshalling infrastructure.
  1764. continue;
  1765. case EDK_DepFileEntry:
  1766. GenerateArg(Args, OPT_fdepfile_entry, Dep.first, SA);
  1767. break;
  1768. }
  1769. }
  1770. }
  1771. static bool ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
  1772. ArgList &Args, DiagnosticsEngine &Diags,
  1773. frontend::ActionKind Action,
  1774. bool ShowLineMarkers) {
  1775. unsigned NumErrorsBefore = Diags.getNumErrors();
  1776. DependencyOutputOptions &DependencyOutputOpts = Opts;
  1777. #define DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING( \
  1778. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1779. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1780. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1781. MERGER, EXTRACTOR, TABLE_INDEX) \
  1782. PARSE_OPTION_WITH_MARSHALLING( \
  1783. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  1784. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  1785. #include "clang/Driver/Options.inc"
  1786. #undef DEPENDENCY_OUTPUT_OPTION_WITH_MARSHALLING
  1787. if (Args.hasArg(OPT_show_includes)) {
  1788. // Writing both /showIncludes and preprocessor output to stdout
  1789. // would produce interleaved output, so use stderr for /showIncludes.
  1790. // This behaves the same as cl.exe, when /E, /EP or /P are passed.
  1791. if (Action == frontend::PrintPreprocessedInput || !ShowLineMarkers)
  1792. Opts.ShowIncludesDest = ShowIncludesDestination::Stderr;
  1793. else
  1794. Opts.ShowIncludesDest = ShowIncludesDestination::Stdout;
  1795. } else {
  1796. Opts.ShowIncludesDest = ShowIncludesDestination::None;
  1797. }
  1798. // Add sanitizer ignorelists as extra dependencies.
  1799. // They won't be discovered by the regular preprocessor, so
  1800. // we let make / ninja to know about this implicit dependency.
  1801. if (!Args.hasArg(OPT_fno_sanitize_ignorelist)) {
  1802. for (const auto *A : Args.filtered(OPT_fsanitize_ignorelist_EQ)) {
  1803. StringRef Val = A->getValue();
  1804. if (!Val.contains('='))
  1805. Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
  1806. }
  1807. if (Opts.IncludeSystemHeaders) {
  1808. for (const auto *A : Args.filtered(OPT_fsanitize_system_ignorelist_EQ)) {
  1809. StringRef Val = A->getValue();
  1810. if (!Val.contains('='))
  1811. Opts.ExtraDeps.emplace_back(std::string(Val), EDK_SanitizeIgnorelist);
  1812. }
  1813. }
  1814. }
  1815. // -fprofile-list= dependencies.
  1816. for (const auto &Filename : Args.getAllArgValues(OPT_fprofile_list_EQ))
  1817. Opts.ExtraDeps.emplace_back(Filename, EDK_ProfileList);
  1818. // Propagate the extra dependencies.
  1819. for (const auto *A : Args.filtered(OPT_fdepfile_entry))
  1820. Opts.ExtraDeps.emplace_back(A->getValue(), EDK_DepFileEntry);
  1821. // Only the -fmodule-file=<file> form.
  1822. for (const auto *A : Args.filtered(OPT_fmodule_file)) {
  1823. StringRef Val = A->getValue();
  1824. if (!Val.contains('='))
  1825. Opts.ExtraDeps.emplace_back(std::string(Val), EDK_ModuleFile);
  1826. }
  1827. return Diags.getNumErrors() == NumErrorsBefore;
  1828. }
  1829. static bool parseShowColorsArgs(const ArgList &Args, bool DefaultColor) {
  1830. // Color diagnostics default to auto ("on" if terminal supports) in the driver
  1831. // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
  1832. // Support both clang's -f[no-]color-diagnostics and gcc's
  1833. // -f[no-]diagnostics-colors[=never|always|auto].
  1834. enum {
  1835. Colors_On,
  1836. Colors_Off,
  1837. Colors_Auto
  1838. } ShowColors = DefaultColor ? Colors_Auto : Colors_Off;
  1839. for (auto *A : Args) {
  1840. const Option &O = A->getOption();
  1841. if (O.matches(options::OPT_fcolor_diagnostics) ||
  1842. O.matches(options::OPT_fdiagnostics_color)) {
  1843. ShowColors = Colors_On;
  1844. } else if (O.matches(options::OPT_fno_color_diagnostics) ||
  1845. O.matches(options::OPT_fno_diagnostics_color)) {
  1846. ShowColors = Colors_Off;
  1847. } else if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
  1848. StringRef Value(A->getValue());
  1849. if (Value == "always")
  1850. ShowColors = Colors_On;
  1851. else if (Value == "never")
  1852. ShowColors = Colors_Off;
  1853. else if (Value == "auto")
  1854. ShowColors = Colors_Auto;
  1855. }
  1856. }
  1857. return ShowColors == Colors_On ||
  1858. (ShowColors == Colors_Auto &&
  1859. llvm::sys::Process::StandardErrHasColors());
  1860. }
  1861. static bool checkVerifyPrefixes(const std::vector<std::string> &VerifyPrefixes,
  1862. DiagnosticsEngine &Diags) {
  1863. bool Success = true;
  1864. for (const auto &Prefix : VerifyPrefixes) {
  1865. // Every prefix must start with a letter and contain only alphanumeric
  1866. // characters, hyphens, and underscores.
  1867. auto BadChar = llvm::find_if(Prefix, [](char C) {
  1868. return !isAlphanumeric(C) && C != '-' && C != '_';
  1869. });
  1870. if (BadChar != Prefix.end() || !isLetter(Prefix[0])) {
  1871. Success = false;
  1872. Diags.Report(diag::err_drv_invalid_value) << "-verify=" << Prefix;
  1873. Diags.Report(diag::note_drv_verify_prefix_spelling);
  1874. }
  1875. }
  1876. return Success;
  1877. }
  1878. static void GenerateFileSystemArgs(const FileSystemOptions &Opts,
  1879. SmallVectorImpl<const char *> &Args,
  1880. CompilerInvocation::StringAllocator SA) {
  1881. const FileSystemOptions &FileSystemOpts = Opts;
  1882. #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
  1883. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1884. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1885. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1886. MERGER, EXTRACTOR, TABLE_INDEX) \
  1887. GENERATE_OPTION_WITH_MARSHALLING( \
  1888. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  1889. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  1890. #include "clang/Driver/Options.inc"
  1891. #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
  1892. }
  1893. static bool ParseFileSystemArgs(FileSystemOptions &Opts, const ArgList &Args,
  1894. DiagnosticsEngine &Diags) {
  1895. unsigned NumErrorsBefore = Diags.getNumErrors();
  1896. FileSystemOptions &FileSystemOpts = Opts;
  1897. #define FILE_SYSTEM_OPTION_WITH_MARSHALLING( \
  1898. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1899. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1900. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1901. MERGER, EXTRACTOR, TABLE_INDEX) \
  1902. PARSE_OPTION_WITH_MARSHALLING( \
  1903. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  1904. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  1905. #include "clang/Driver/Options.inc"
  1906. #undef FILE_SYSTEM_OPTION_WITH_MARSHALLING
  1907. return Diags.getNumErrors() == NumErrorsBefore;
  1908. }
  1909. static void GenerateMigratorArgs(const MigratorOptions &Opts,
  1910. SmallVectorImpl<const char *> &Args,
  1911. CompilerInvocation::StringAllocator SA) {
  1912. const MigratorOptions &MigratorOpts = Opts;
  1913. #define MIGRATOR_OPTION_WITH_MARSHALLING( \
  1914. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1915. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1916. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1917. MERGER, EXTRACTOR, TABLE_INDEX) \
  1918. GENERATE_OPTION_WITH_MARSHALLING( \
  1919. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  1920. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  1921. #include "clang/Driver/Options.inc"
  1922. #undef MIGRATOR_OPTION_WITH_MARSHALLING
  1923. }
  1924. static bool ParseMigratorArgs(MigratorOptions &Opts, const ArgList &Args,
  1925. DiagnosticsEngine &Diags) {
  1926. unsigned NumErrorsBefore = Diags.getNumErrors();
  1927. MigratorOptions &MigratorOpts = Opts;
  1928. #define MIGRATOR_OPTION_WITH_MARSHALLING( \
  1929. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1930. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1931. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1932. MERGER, EXTRACTOR, TABLE_INDEX) \
  1933. PARSE_OPTION_WITH_MARSHALLING( \
  1934. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  1935. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  1936. #include "clang/Driver/Options.inc"
  1937. #undef MIGRATOR_OPTION_WITH_MARSHALLING
  1938. return Diags.getNumErrors() == NumErrorsBefore;
  1939. }
  1940. void CompilerInvocation::GenerateDiagnosticArgs(
  1941. const DiagnosticOptions &Opts, SmallVectorImpl<const char *> &Args,
  1942. StringAllocator SA, bool DefaultDiagColor) {
  1943. const DiagnosticOptions *DiagnosticOpts = &Opts;
  1944. #define DIAG_OPTION_WITH_MARSHALLING( \
  1945. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  1946. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  1947. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  1948. MERGER, EXTRACTOR, TABLE_INDEX) \
  1949. GENERATE_OPTION_WITH_MARSHALLING( \
  1950. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  1951. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  1952. #include "clang/Driver/Options.inc"
  1953. #undef DIAG_OPTION_WITH_MARSHALLING
  1954. if (!Opts.DiagnosticSerializationFile.empty())
  1955. GenerateArg(Args, OPT_diagnostic_serialized_file,
  1956. Opts.DiagnosticSerializationFile, SA);
  1957. if (Opts.ShowColors)
  1958. GenerateArg(Args, OPT_fcolor_diagnostics, SA);
  1959. if (Opts.VerifyDiagnostics &&
  1960. llvm::is_contained(Opts.VerifyPrefixes, "expected"))
  1961. GenerateArg(Args, OPT_verify, SA);
  1962. for (const auto &Prefix : Opts.VerifyPrefixes)
  1963. if (Prefix != "expected")
  1964. GenerateArg(Args, OPT_verify_EQ, Prefix, SA);
  1965. DiagnosticLevelMask VIU = Opts.getVerifyIgnoreUnexpected();
  1966. if (VIU == DiagnosticLevelMask::None) {
  1967. // This is the default, don't generate anything.
  1968. } else if (VIU == DiagnosticLevelMask::All) {
  1969. GenerateArg(Args, OPT_verify_ignore_unexpected, SA);
  1970. } else {
  1971. if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Note) != 0)
  1972. GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "note", SA);
  1973. if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Remark) != 0)
  1974. GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "remark", SA);
  1975. if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Warning) != 0)
  1976. GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "warning", SA);
  1977. if (static_cast<unsigned>(VIU & DiagnosticLevelMask::Error) != 0)
  1978. GenerateArg(Args, OPT_verify_ignore_unexpected_EQ, "error", SA);
  1979. }
  1980. for (const auto &Warning : Opts.Warnings) {
  1981. // This option is automatically generated from UndefPrefixes.
  1982. if (Warning == "undef-prefix")
  1983. continue;
  1984. Args.push_back(SA(StringRef("-W") + Warning));
  1985. }
  1986. for (const auto &Remark : Opts.Remarks) {
  1987. // These arguments are generated from OptimizationRemark fields of
  1988. // CodeGenOptions.
  1989. StringRef IgnoredRemarks[] = {"pass", "no-pass",
  1990. "pass-analysis", "no-pass-analysis",
  1991. "pass-missed", "no-pass-missed"};
  1992. if (llvm::is_contained(IgnoredRemarks, Remark))
  1993. continue;
  1994. Args.push_back(SA(StringRef("-R") + Remark));
  1995. }
  1996. }
  1997. std::unique_ptr<DiagnosticOptions>
  1998. clang::CreateAndPopulateDiagOpts(ArrayRef<const char *> Argv) {
  1999. auto DiagOpts = std::make_unique<DiagnosticOptions>();
  2000. unsigned MissingArgIndex, MissingArgCount;
  2001. InputArgList Args = getDriverOptTable().ParseArgs(
  2002. Argv.slice(1), MissingArgIndex, MissingArgCount);
  2003. // We ignore MissingArgCount and the return value of ParseDiagnosticArgs.
  2004. // Any errors that would be diagnosed here will also be diagnosed later,
  2005. // when the DiagnosticsEngine actually exists.
  2006. (void)ParseDiagnosticArgs(*DiagOpts, Args);
  2007. return DiagOpts;
  2008. }
  2009. bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
  2010. DiagnosticsEngine *Diags,
  2011. bool DefaultDiagColor) {
  2012. Optional<DiagnosticsEngine> IgnoringDiags;
  2013. if (!Diags) {
  2014. IgnoringDiags.emplace(new DiagnosticIDs(), new DiagnosticOptions(),
  2015. new IgnoringDiagConsumer());
  2016. Diags = &*IgnoringDiags;
  2017. }
  2018. unsigned NumErrorsBefore = Diags->getNumErrors();
  2019. // The key paths of diagnostic options defined in Options.td start with
  2020. // "DiagnosticOpts->". Let's provide the expected variable name and type.
  2021. DiagnosticOptions *DiagnosticOpts = &Opts;
  2022. #define DIAG_OPTION_WITH_MARSHALLING( \
  2023. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  2024. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  2025. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  2026. MERGER, EXTRACTOR, TABLE_INDEX) \
  2027. PARSE_OPTION_WITH_MARSHALLING( \
  2028. Args, *Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  2029. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  2030. #include "clang/Driver/Options.inc"
  2031. #undef DIAG_OPTION_WITH_MARSHALLING
  2032. llvm::sys::Process::UseANSIEscapeCodes(Opts.UseANSIEscapeCodes);
  2033. if (Arg *A =
  2034. Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
  2035. Opts.DiagnosticSerializationFile = A->getValue();
  2036. Opts.ShowColors = parseShowColorsArgs(Args, DefaultDiagColor);
  2037. Opts.VerifyDiagnostics = Args.hasArg(OPT_verify) || Args.hasArg(OPT_verify_EQ);
  2038. Opts.VerifyPrefixes = Args.getAllArgValues(OPT_verify_EQ);
  2039. if (Args.hasArg(OPT_verify))
  2040. Opts.VerifyPrefixes.push_back("expected");
  2041. // Keep VerifyPrefixes in its original order for the sake of diagnostics, and
  2042. // then sort it to prepare for fast lookup using std::binary_search.
  2043. if (!checkVerifyPrefixes(Opts.VerifyPrefixes, *Diags))
  2044. Opts.VerifyDiagnostics = false;
  2045. else
  2046. llvm::sort(Opts.VerifyPrefixes);
  2047. DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None;
  2048. parseDiagnosticLevelMask(
  2049. "-verify-ignore-unexpected=",
  2050. Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), *Diags, DiagMask);
  2051. if (Args.hasArg(OPT_verify_ignore_unexpected))
  2052. DiagMask = DiagnosticLevelMask::All;
  2053. Opts.setVerifyIgnoreUnexpected(DiagMask);
  2054. if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
  2055. Opts.TabStop = DiagnosticOptions::DefaultTabStop;
  2056. Diags->Report(diag::warn_ignoring_ftabstop_value)
  2057. << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
  2058. }
  2059. addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
  2060. addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
  2061. return Diags->getNumErrors() == NumErrorsBefore;
  2062. }
  2063. /// Parse the argument to the -ftest-module-file-extension
  2064. /// command-line argument.
  2065. ///
  2066. /// \returns true on error, false on success.
  2067. static bool parseTestModuleFileExtensionArg(StringRef Arg,
  2068. std::string &BlockName,
  2069. unsigned &MajorVersion,
  2070. unsigned &MinorVersion,
  2071. bool &Hashed,
  2072. std::string &UserInfo) {
  2073. SmallVector<StringRef, 5> Args;
  2074. Arg.split(Args, ':', 5);
  2075. if (Args.size() < 5)
  2076. return true;
  2077. BlockName = std::string(Args[0]);
  2078. if (Args[1].getAsInteger(10, MajorVersion)) return true;
  2079. if (Args[2].getAsInteger(10, MinorVersion)) return true;
  2080. if (Args[3].getAsInteger(2, Hashed)) return true;
  2081. if (Args.size() > 4)
  2082. UserInfo = std::string(Args[4]);
  2083. return false;
  2084. }
  2085. /// Return a table that associates command line option specifiers with the
  2086. /// frontend action. Note: The pair {frontend::PluginAction, OPT_plugin} is
  2087. /// intentionally missing, as this case is handled separately from other
  2088. /// frontend options.
  2089. static const auto &getFrontendActionTable() {
  2090. static const std::pair<frontend::ActionKind, unsigned> Table[] = {
  2091. {frontend::ASTDeclList, OPT_ast_list},
  2092. {frontend::ASTDump, OPT_ast_dump_all_EQ},
  2093. {frontend::ASTDump, OPT_ast_dump_all},
  2094. {frontend::ASTDump, OPT_ast_dump_EQ},
  2095. {frontend::ASTDump, OPT_ast_dump},
  2096. {frontend::ASTDump, OPT_ast_dump_lookups},
  2097. {frontend::ASTDump, OPT_ast_dump_decl_types},
  2098. {frontend::ASTPrint, OPT_ast_print},
  2099. {frontend::ASTView, OPT_ast_view},
  2100. {frontend::DumpCompilerOptions, OPT_compiler_options_dump},
  2101. {frontend::DumpRawTokens, OPT_dump_raw_tokens},
  2102. {frontend::DumpTokens, OPT_dump_tokens},
  2103. {frontend::EmitAssembly, OPT_S},
  2104. {frontend::EmitBC, OPT_emit_llvm_bc},
  2105. {frontend::EmitHTML, OPT_emit_html},
  2106. {frontend::EmitLLVM, OPT_emit_llvm},
  2107. {frontend::EmitLLVMOnly, OPT_emit_llvm_only},
  2108. {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
  2109. {frontend::EmitCodeGenOnly, OPT_emit_codegen_only},
  2110. {frontend::EmitObj, OPT_emit_obj},
  2111. {frontend::ExtractAPI, OPT_extract_api},
  2112. {frontend::FixIt, OPT_fixit_EQ},
  2113. {frontend::FixIt, OPT_fixit},
  2114. {frontend::GenerateModule, OPT_emit_module},
  2115. {frontend::GenerateModuleInterface, OPT_emit_module_interface},
  2116. {frontend::GenerateHeaderModule, OPT_emit_header_module},
  2117. {frontend::GeneratePCH, OPT_emit_pch},
  2118. {frontend::GenerateInterfaceStubs, OPT_emit_interface_stubs},
  2119. {frontend::InitOnly, OPT_init_only},
  2120. {frontend::ParseSyntaxOnly, OPT_fsyntax_only},
  2121. {frontend::ModuleFileInfo, OPT_module_file_info},
  2122. {frontend::VerifyPCH, OPT_verify_pch},
  2123. {frontend::PrintPreamble, OPT_print_preamble},
  2124. {frontend::PrintPreprocessedInput, OPT_E},
  2125. {frontend::TemplightDump, OPT_templight_dump},
  2126. {frontend::RewriteMacros, OPT_rewrite_macros},
  2127. {frontend::RewriteObjC, OPT_rewrite_objc},
  2128. {frontend::RewriteTest, OPT_rewrite_test},
  2129. {frontend::RunAnalysis, OPT_analyze},
  2130. {frontend::MigrateSource, OPT_migrate},
  2131. {frontend::RunPreprocessorOnly, OPT_Eonly},
  2132. {frontend::PrintDependencyDirectivesSourceMinimizerOutput,
  2133. OPT_print_dependency_directives_minimized_source},
  2134. };
  2135. return Table;
  2136. }
  2137. /// Maps command line option to frontend action.
  2138. static Optional<frontend::ActionKind> getFrontendAction(OptSpecifier &Opt) {
  2139. for (const auto &ActionOpt : getFrontendActionTable())
  2140. if (ActionOpt.second == Opt.getID())
  2141. return ActionOpt.first;
  2142. return None;
  2143. }
  2144. /// Maps frontend action to command line option.
  2145. static Optional<OptSpecifier>
  2146. getProgramActionOpt(frontend::ActionKind ProgramAction) {
  2147. for (const auto &ActionOpt : getFrontendActionTable())
  2148. if (ActionOpt.first == ProgramAction)
  2149. return OptSpecifier(ActionOpt.second);
  2150. return None;
  2151. }
  2152. static void GenerateFrontendArgs(const FrontendOptions &Opts,
  2153. SmallVectorImpl<const char *> &Args,
  2154. CompilerInvocation::StringAllocator SA,
  2155. bool IsHeader) {
  2156. const FrontendOptions &FrontendOpts = Opts;
  2157. #define FRONTEND_OPTION_WITH_MARSHALLING( \
  2158. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  2159. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  2160. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  2161. MERGER, EXTRACTOR, TABLE_INDEX) \
  2162. GENERATE_OPTION_WITH_MARSHALLING( \
  2163. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  2164. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  2165. #include "clang/Driver/Options.inc"
  2166. #undef FRONTEND_OPTION_WITH_MARSHALLING
  2167. Optional<OptSpecifier> ProgramActionOpt =
  2168. getProgramActionOpt(Opts.ProgramAction);
  2169. // Generating a simple flag covers most frontend actions.
  2170. std::function<void()> GenerateProgramAction = [&]() {
  2171. GenerateArg(Args, *ProgramActionOpt, SA);
  2172. };
  2173. if (!ProgramActionOpt) {
  2174. // PluginAction is the only program action handled separately.
  2175. assert(Opts.ProgramAction == frontend::PluginAction &&
  2176. "Frontend action without option.");
  2177. GenerateProgramAction = [&]() {
  2178. GenerateArg(Args, OPT_plugin, Opts.ActionName, SA);
  2179. };
  2180. }
  2181. // FIXME: Simplify the complex 'AST dump' command line.
  2182. if (Opts.ProgramAction == frontend::ASTDump) {
  2183. GenerateProgramAction = [&]() {
  2184. // ASTDumpLookups, ASTDumpDeclTypes and ASTDumpFilter are generated via
  2185. // marshalling infrastructure.
  2186. if (Opts.ASTDumpFormat != ADOF_Default) {
  2187. StringRef Format;
  2188. switch (Opts.ASTDumpFormat) {
  2189. case ADOF_Default:
  2190. llvm_unreachable("Default AST dump format.");
  2191. case ADOF_JSON:
  2192. Format = "json";
  2193. break;
  2194. }
  2195. if (Opts.ASTDumpAll)
  2196. GenerateArg(Args, OPT_ast_dump_all_EQ, Format, SA);
  2197. if (Opts.ASTDumpDecls)
  2198. GenerateArg(Args, OPT_ast_dump_EQ, Format, SA);
  2199. } else {
  2200. if (Opts.ASTDumpAll)
  2201. GenerateArg(Args, OPT_ast_dump_all, SA);
  2202. if (Opts.ASTDumpDecls)
  2203. GenerateArg(Args, OPT_ast_dump, SA);
  2204. }
  2205. };
  2206. }
  2207. if (Opts.ProgramAction == frontend::FixIt && !Opts.FixItSuffix.empty()) {
  2208. GenerateProgramAction = [&]() {
  2209. GenerateArg(Args, OPT_fixit_EQ, Opts.FixItSuffix, SA);
  2210. };
  2211. }
  2212. GenerateProgramAction();
  2213. for (const auto &PluginArgs : Opts.PluginArgs) {
  2214. Option Opt = getDriverOptTable().getOption(OPT_plugin_arg);
  2215. const char *Spelling =
  2216. SA(Opt.getPrefix() + Opt.getName() + PluginArgs.first);
  2217. for (const auto &PluginArg : PluginArgs.second)
  2218. denormalizeString(Args, Spelling, SA, Opt.getKind(), 0, PluginArg);
  2219. }
  2220. for (const auto &Ext : Opts.ModuleFileExtensions)
  2221. if (auto *TestExt = dyn_cast_or_null<TestModuleFileExtension>(Ext.get()))
  2222. GenerateArg(Args, OPT_ftest_module_file_extension_EQ, TestExt->str(), SA);
  2223. if (!Opts.CodeCompletionAt.FileName.empty())
  2224. GenerateArg(Args, OPT_code_completion_at, Opts.CodeCompletionAt.ToString(),
  2225. SA);
  2226. for (const auto &Plugin : Opts.Plugins)
  2227. GenerateArg(Args, OPT_load, Plugin, SA);
  2228. // ASTDumpDecls and ASTDumpAll already handled with ProgramAction.
  2229. for (const auto &ModuleFile : Opts.ModuleFiles)
  2230. GenerateArg(Args, OPT_fmodule_file, ModuleFile, SA);
  2231. if (Opts.AuxTargetCPU.hasValue())
  2232. GenerateArg(Args, OPT_aux_target_cpu, *Opts.AuxTargetCPU, SA);
  2233. if (Opts.AuxTargetFeatures.hasValue())
  2234. for (const auto &Feature : *Opts.AuxTargetFeatures)
  2235. GenerateArg(Args, OPT_aux_target_feature, Feature, SA);
  2236. {
  2237. StringRef Preprocessed = Opts.DashX.isPreprocessed() ? "-cpp-output" : "";
  2238. StringRef ModuleMap =
  2239. Opts.DashX.getFormat() == InputKind::ModuleMap ? "-module-map" : "";
  2240. StringRef Header = IsHeader ? "-header" : "";
  2241. StringRef Lang;
  2242. switch (Opts.DashX.getLanguage()) {
  2243. case Language::C:
  2244. Lang = "c";
  2245. break;
  2246. case Language::OpenCL:
  2247. Lang = "cl";
  2248. break;
  2249. case Language::OpenCLCXX:
  2250. Lang = "clcpp";
  2251. break;
  2252. case Language::CUDA:
  2253. Lang = "cuda";
  2254. break;
  2255. case Language::HIP:
  2256. Lang = "hip";
  2257. break;
  2258. case Language::CXX:
  2259. Lang = "c++";
  2260. break;
  2261. case Language::ObjC:
  2262. Lang = "objective-c";
  2263. break;
  2264. case Language::ObjCXX:
  2265. Lang = "objective-c++";
  2266. break;
  2267. case Language::RenderScript:
  2268. Lang = "renderscript";
  2269. break;
  2270. case Language::Asm:
  2271. Lang = "assembler-with-cpp";
  2272. break;
  2273. case Language::Unknown:
  2274. assert(Opts.DashX.getFormat() == InputKind::Precompiled &&
  2275. "Generating -x argument for unknown language (not precompiled).");
  2276. Lang = "ast";
  2277. break;
  2278. case Language::LLVM_IR:
  2279. Lang = "ir";
  2280. break;
  2281. }
  2282. GenerateArg(Args, OPT_x, Lang + Header + ModuleMap + Preprocessed, SA);
  2283. }
  2284. // OPT_INPUT has a unique class, generate it directly.
  2285. for (const auto &Input : Opts.Inputs)
  2286. Args.push_back(SA(Input.getFile()));
  2287. }
  2288. static bool ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
  2289. DiagnosticsEngine &Diags, bool &IsHeaderFile) {
  2290. unsigned NumErrorsBefore = Diags.getNumErrors();
  2291. FrontendOptions &FrontendOpts = Opts;
  2292. #define FRONTEND_OPTION_WITH_MARSHALLING( \
  2293. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  2294. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  2295. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  2296. MERGER, EXTRACTOR, TABLE_INDEX) \
  2297. PARSE_OPTION_WITH_MARSHALLING( \
  2298. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  2299. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  2300. #include "clang/Driver/Options.inc"
  2301. #undef FRONTEND_OPTION_WITH_MARSHALLING
  2302. Opts.ProgramAction = frontend::ParseSyntaxOnly;
  2303. if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
  2304. OptSpecifier Opt = OptSpecifier(A->getOption().getID());
  2305. Optional<frontend::ActionKind> ProgramAction = getFrontendAction(Opt);
  2306. assert(ProgramAction && "Option specifier not in Action_Group.");
  2307. if (ProgramAction == frontend::ASTDump &&
  2308. (Opt == OPT_ast_dump_all_EQ || Opt == OPT_ast_dump_EQ)) {
  2309. unsigned Val = llvm::StringSwitch<unsigned>(A->getValue())
  2310. .CaseLower("default", ADOF_Default)
  2311. .CaseLower("json", ADOF_JSON)
  2312. .Default(std::numeric_limits<unsigned>::max());
  2313. if (Val != std::numeric_limits<unsigned>::max())
  2314. Opts.ASTDumpFormat = static_cast<ASTDumpOutputFormat>(Val);
  2315. else {
  2316. Diags.Report(diag::err_drv_invalid_value)
  2317. << A->getAsString(Args) << A->getValue();
  2318. Opts.ASTDumpFormat = ADOF_Default;
  2319. }
  2320. }
  2321. if (ProgramAction == frontend::FixIt && Opt == OPT_fixit_EQ)
  2322. Opts.FixItSuffix = A->getValue();
  2323. if (ProgramAction == frontend::GenerateInterfaceStubs) {
  2324. StringRef ArgStr =
  2325. Args.hasArg(OPT_interface_stub_version_EQ)
  2326. ? Args.getLastArgValue(OPT_interface_stub_version_EQ)
  2327. : "ifs-v1";
  2328. if (ArgStr == "experimental-yaml-elf-v1" ||
  2329. ArgStr == "experimental-ifs-v1" || ArgStr == "experimental-ifs-v2" ||
  2330. ArgStr == "experimental-tapi-elf-v1") {
  2331. std::string ErrorMessage =
  2332. "Invalid interface stub format: " + ArgStr.str() +
  2333. " is deprecated.";
  2334. Diags.Report(diag::err_drv_invalid_value)
  2335. << "Must specify a valid interface stub format type, ie: "
  2336. "-interface-stub-version=ifs-v1"
  2337. << ErrorMessage;
  2338. ProgramAction = frontend::ParseSyntaxOnly;
  2339. } else if (!ArgStr.startswith("ifs-")) {
  2340. std::string ErrorMessage =
  2341. "Invalid interface stub format: " + ArgStr.str() + ".";
  2342. Diags.Report(diag::err_drv_invalid_value)
  2343. << "Must specify a valid interface stub format type, ie: "
  2344. "-interface-stub-version=ifs-v1"
  2345. << ErrorMessage;
  2346. ProgramAction = frontend::ParseSyntaxOnly;
  2347. }
  2348. }
  2349. Opts.ProgramAction = *ProgramAction;
  2350. }
  2351. if (const Arg* A = Args.getLastArg(OPT_plugin)) {
  2352. Opts.Plugins.emplace_back(A->getValue(0));
  2353. Opts.ProgramAction = frontend::PluginAction;
  2354. Opts.ActionName = A->getValue();
  2355. }
  2356. for (const auto *AA : Args.filtered(OPT_plugin_arg))
  2357. Opts.PluginArgs[AA->getValue(0)].emplace_back(AA->getValue(1));
  2358. for (const std::string &Arg :
  2359. Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) {
  2360. std::string BlockName;
  2361. unsigned MajorVersion;
  2362. unsigned MinorVersion;
  2363. bool Hashed;
  2364. std::string UserInfo;
  2365. if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion,
  2366. MinorVersion, Hashed, UserInfo)) {
  2367. Diags.Report(diag::err_test_module_file_extension_format) << Arg;
  2368. continue;
  2369. }
  2370. // Add the testing module file extension.
  2371. Opts.ModuleFileExtensions.push_back(
  2372. std::make_shared<TestModuleFileExtension>(
  2373. BlockName, MajorVersion, MinorVersion, Hashed, UserInfo));
  2374. }
  2375. if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
  2376. Opts.CodeCompletionAt =
  2377. ParsedSourceLocation::FromString(A->getValue());
  2378. if (Opts.CodeCompletionAt.FileName.empty())
  2379. Diags.Report(diag::err_drv_invalid_value)
  2380. << A->getAsString(Args) << A->getValue();
  2381. }
  2382. Opts.Plugins = Args.getAllArgValues(OPT_load);
  2383. Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump, OPT_ast_dump_EQ);
  2384. Opts.ASTDumpAll = Args.hasArg(OPT_ast_dump_all, OPT_ast_dump_all_EQ);
  2385. // Only the -fmodule-file=<file> form.
  2386. for (const auto *A : Args.filtered(OPT_fmodule_file)) {
  2387. StringRef Val = A->getValue();
  2388. if (!Val.contains('='))
  2389. Opts.ModuleFiles.push_back(std::string(Val));
  2390. }
  2391. if (Opts.ProgramAction != frontend::GenerateModule && Opts.IsSystemModule)
  2392. Diags.Report(diag::err_drv_argument_only_allowed_with) << "-fsystem-module"
  2393. << "-emit-module";
  2394. if (Args.hasArg(OPT_aux_target_cpu))
  2395. Opts.AuxTargetCPU = std::string(Args.getLastArgValue(OPT_aux_target_cpu));
  2396. if (Args.hasArg(OPT_aux_target_feature))
  2397. Opts.AuxTargetFeatures = Args.getAllArgValues(OPT_aux_target_feature);
  2398. if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
  2399. Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
  2400. Diags.Report(diag::err_drv_argument_not_allowed_with)
  2401. << "ARC migration" << "ObjC migration";
  2402. }
  2403. InputKind DashX(Language::Unknown);
  2404. if (const Arg *A = Args.getLastArg(OPT_x)) {
  2405. StringRef XValue = A->getValue();
  2406. // Parse suffixes: '<lang>(-header|[-module-map][-cpp-output])'.
  2407. // FIXME: Supporting '<lang>-header-cpp-output' would be useful.
  2408. bool Preprocessed = XValue.consume_back("-cpp-output");
  2409. bool ModuleMap = XValue.consume_back("-module-map");
  2410. IsHeaderFile = !Preprocessed && !ModuleMap &&
  2411. XValue != "precompiled-header" &&
  2412. XValue.consume_back("-header");
  2413. // Principal languages.
  2414. DashX = llvm::StringSwitch<InputKind>(XValue)
  2415. .Case("c", Language::C)
  2416. .Case("cl", Language::OpenCL)
  2417. .Case("clcpp", Language::OpenCLCXX)
  2418. .Case("cuda", Language::CUDA)
  2419. .Case("hip", Language::HIP)
  2420. .Case("c++", Language::CXX)
  2421. .Case("objective-c", Language::ObjC)
  2422. .Case("objective-c++", Language::ObjCXX)
  2423. .Case("renderscript", Language::RenderScript)
  2424. .Default(Language::Unknown);
  2425. // "objc[++]-cpp-output" is an acceptable synonym for
  2426. // "objective-c[++]-cpp-output".
  2427. if (DashX.isUnknown() && Preprocessed && !IsHeaderFile && !ModuleMap)
  2428. DashX = llvm::StringSwitch<InputKind>(XValue)
  2429. .Case("objc", Language::ObjC)
  2430. .Case("objc++", Language::ObjCXX)
  2431. .Default(Language::Unknown);
  2432. // Some special cases cannot be combined with suffixes.
  2433. if (DashX.isUnknown() && !Preprocessed && !ModuleMap && !IsHeaderFile)
  2434. DashX = llvm::StringSwitch<InputKind>(XValue)
  2435. .Case("cpp-output", InputKind(Language::C).getPreprocessed())
  2436. .Case("assembler-with-cpp", Language::Asm)
  2437. .Cases("ast", "pcm", "precompiled-header",
  2438. InputKind(Language::Unknown, InputKind::Precompiled))
  2439. .Case("ir", Language::LLVM_IR)
  2440. .Default(Language::Unknown);
  2441. if (DashX.isUnknown())
  2442. Diags.Report(diag::err_drv_invalid_value)
  2443. << A->getAsString(Args) << A->getValue();
  2444. if (Preprocessed)
  2445. DashX = DashX.getPreprocessed();
  2446. if (ModuleMap)
  2447. DashX = DashX.withFormat(InputKind::ModuleMap);
  2448. }
  2449. // '-' is the default input if none is given.
  2450. std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
  2451. Opts.Inputs.clear();
  2452. if (Inputs.empty())
  2453. Inputs.push_back("-");
  2454. for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
  2455. InputKind IK = DashX;
  2456. if (IK.isUnknown()) {
  2457. IK = FrontendOptions::getInputKindForExtension(
  2458. StringRef(Inputs[i]).rsplit('.').second);
  2459. // FIXME: Warn on this?
  2460. if (IK.isUnknown())
  2461. IK = Language::C;
  2462. // FIXME: Remove this hack.
  2463. if (i == 0)
  2464. DashX = IK;
  2465. }
  2466. bool IsSystem = false;
  2467. // The -emit-module action implicitly takes a module map.
  2468. if (Opts.ProgramAction == frontend::GenerateModule &&
  2469. IK.getFormat() == InputKind::Source) {
  2470. IK = IK.withFormat(InputKind::ModuleMap);
  2471. IsSystem = Opts.IsSystemModule;
  2472. }
  2473. Opts.Inputs.emplace_back(std::move(Inputs[i]), IK, IsSystem);
  2474. }
  2475. Opts.DashX = DashX;
  2476. return Diags.getNumErrors() == NumErrorsBefore;
  2477. }
  2478. std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
  2479. void *MainAddr) {
  2480. std::string ClangExecutable =
  2481. llvm::sys::fs::getMainExecutable(Argv0, MainAddr);
  2482. return Driver::GetResourcesPath(ClangExecutable, CLANG_RESOURCE_DIR);
  2483. }
  2484. static void GenerateHeaderSearchArgs(HeaderSearchOptions &Opts,
  2485. SmallVectorImpl<const char *> &Args,
  2486. CompilerInvocation::StringAllocator SA) {
  2487. const HeaderSearchOptions *HeaderSearchOpts = &Opts;
  2488. #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
  2489. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  2490. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  2491. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  2492. MERGER, EXTRACTOR, TABLE_INDEX) \
  2493. GENERATE_OPTION_WITH_MARSHALLING( \
  2494. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  2495. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  2496. #include "clang/Driver/Options.inc"
  2497. #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
  2498. if (Opts.UseLibcxx)
  2499. GenerateArg(Args, OPT_stdlib_EQ, "libc++", SA);
  2500. if (!Opts.ModuleCachePath.empty())
  2501. GenerateArg(Args, OPT_fmodules_cache_path, Opts.ModuleCachePath, SA);
  2502. for (const auto &File : Opts.PrebuiltModuleFiles)
  2503. GenerateArg(Args, OPT_fmodule_file, File.first + "=" + File.second, SA);
  2504. for (const auto &Path : Opts.PrebuiltModulePaths)
  2505. GenerateArg(Args, OPT_fprebuilt_module_path, Path, SA);
  2506. for (const auto &Macro : Opts.ModulesIgnoreMacros)
  2507. GenerateArg(Args, OPT_fmodules_ignore_macro, Macro.val(), SA);
  2508. auto Matches = [](const HeaderSearchOptions::Entry &Entry,
  2509. llvm::ArrayRef<frontend::IncludeDirGroup> Groups,
  2510. llvm::Optional<bool> IsFramework,
  2511. llvm::Optional<bool> IgnoreSysRoot) {
  2512. return llvm::is_contained(Groups, Entry.Group) &&
  2513. (!IsFramework || (Entry.IsFramework == *IsFramework)) &&
  2514. (!IgnoreSysRoot || (Entry.IgnoreSysRoot == *IgnoreSysRoot));
  2515. };
  2516. auto It = Opts.UserEntries.begin();
  2517. auto End = Opts.UserEntries.end();
  2518. // Add -I..., -F..., and -index-header-map options in order.
  2519. for (; It < End &&
  2520. Matches(*It, {frontend::IndexHeaderMap, frontend::Angled}, None, true);
  2521. ++It) {
  2522. OptSpecifier Opt = [It, Matches]() {
  2523. if (Matches(*It, frontend::IndexHeaderMap, true, true))
  2524. return OPT_F;
  2525. if (Matches(*It, frontend::IndexHeaderMap, false, true))
  2526. return OPT_I;
  2527. if (Matches(*It, frontend::Angled, true, true))
  2528. return OPT_F;
  2529. if (Matches(*It, frontend::Angled, false, true))
  2530. return OPT_I;
  2531. llvm_unreachable("Unexpected HeaderSearchOptions::Entry.");
  2532. }();
  2533. if (It->Group == frontend::IndexHeaderMap)
  2534. GenerateArg(Args, OPT_index_header_map, SA);
  2535. GenerateArg(Args, Opt, It->Path, SA);
  2536. };
  2537. // Note: some paths that came from "[-iprefix=xx] -iwithprefixbefore=yy" may
  2538. // have already been generated as "-I[xx]yy". If that's the case, their
  2539. // position on command line was such that this has no semantic impact on
  2540. // include paths.
  2541. for (; It < End &&
  2542. Matches(*It, {frontend::After, frontend::Angled}, false, true);
  2543. ++It) {
  2544. OptSpecifier Opt =
  2545. It->Group == frontend::After ? OPT_iwithprefix : OPT_iwithprefixbefore;
  2546. GenerateArg(Args, Opt, It->Path, SA);
  2547. }
  2548. // Note: Some paths that came from "-idirafter=xxyy" may have already been
  2549. // generated as "-iwithprefix=xxyy". If that's the case, their position on
  2550. // command line was such that this has no semantic impact on include paths.
  2551. for (; It < End && Matches(*It, {frontend::After}, false, true); ++It)
  2552. GenerateArg(Args, OPT_idirafter, It->Path, SA);
  2553. for (; It < End && Matches(*It, {frontend::Quoted}, false, true); ++It)
  2554. GenerateArg(Args, OPT_iquote, It->Path, SA);
  2555. for (; It < End && Matches(*It, {frontend::System}, false, None); ++It)
  2556. GenerateArg(Args, It->IgnoreSysRoot ? OPT_isystem : OPT_iwithsysroot,
  2557. It->Path, SA);
  2558. for (; It < End && Matches(*It, {frontend::System}, true, true); ++It)
  2559. GenerateArg(Args, OPT_iframework, It->Path, SA);
  2560. for (; It < End && Matches(*It, {frontend::System}, true, false); ++It)
  2561. GenerateArg(Args, OPT_iframeworkwithsysroot, It->Path, SA);
  2562. // Add the paths for the various language specific isystem flags.
  2563. for (; It < End && Matches(*It, {frontend::CSystem}, false, true); ++It)
  2564. GenerateArg(Args, OPT_c_isystem, It->Path, SA);
  2565. for (; It < End && Matches(*It, {frontend::CXXSystem}, false, true); ++It)
  2566. GenerateArg(Args, OPT_cxx_isystem, It->Path, SA);
  2567. for (; It < End && Matches(*It, {frontend::ObjCSystem}, false, true); ++It)
  2568. GenerateArg(Args, OPT_objc_isystem, It->Path, SA);
  2569. for (; It < End && Matches(*It, {frontend::ObjCXXSystem}, false, true); ++It)
  2570. GenerateArg(Args, OPT_objcxx_isystem, It->Path, SA);
  2571. // Add the internal paths from a driver that detects standard include paths.
  2572. // Note: Some paths that came from "-internal-isystem" arguments may have
  2573. // already been generated as "-isystem". If that's the case, their position on
  2574. // command line was such that this has no semantic impact on include paths.
  2575. for (; It < End &&
  2576. Matches(*It, {frontend::System, frontend::ExternCSystem}, false, true);
  2577. ++It) {
  2578. OptSpecifier Opt = It->Group == frontend::System
  2579. ? OPT_internal_isystem
  2580. : OPT_internal_externc_isystem;
  2581. GenerateArg(Args, Opt, It->Path, SA);
  2582. }
  2583. assert(It == End && "Unhandled HeaderSearchOption::Entry.");
  2584. // Add the path prefixes which are implicitly treated as being system headers.
  2585. for (const auto &P : Opts.SystemHeaderPrefixes) {
  2586. OptSpecifier Opt = P.IsSystemHeader ? OPT_system_header_prefix
  2587. : OPT_no_system_header_prefix;
  2588. GenerateArg(Args, Opt, P.Prefix, SA);
  2589. }
  2590. for (const std::string &F : Opts.VFSOverlayFiles)
  2591. GenerateArg(Args, OPT_ivfsoverlay, F, SA);
  2592. }
  2593. static bool ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args,
  2594. DiagnosticsEngine &Diags,
  2595. const std::string &WorkingDir) {
  2596. unsigned NumErrorsBefore = Diags.getNumErrors();
  2597. HeaderSearchOptions *HeaderSearchOpts = &Opts;
  2598. #define HEADER_SEARCH_OPTION_WITH_MARSHALLING( \
  2599. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  2600. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  2601. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  2602. MERGER, EXTRACTOR, TABLE_INDEX) \
  2603. PARSE_OPTION_WITH_MARSHALLING( \
  2604. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  2605. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  2606. #include "clang/Driver/Options.inc"
  2607. #undef HEADER_SEARCH_OPTION_WITH_MARSHALLING
  2608. if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
  2609. Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
  2610. // Canonicalize -fmodules-cache-path before storing it.
  2611. SmallString<128> P(Args.getLastArgValue(OPT_fmodules_cache_path));
  2612. if (!(P.empty() || llvm::sys::path::is_absolute(P))) {
  2613. if (WorkingDir.empty())
  2614. llvm::sys::fs::make_absolute(P);
  2615. else
  2616. llvm::sys::fs::make_absolute(WorkingDir, P);
  2617. }
  2618. llvm::sys::path::remove_dots(P);
  2619. Opts.ModuleCachePath = std::string(P.str());
  2620. // Only the -fmodule-file=<name>=<file> form.
  2621. for (const auto *A : Args.filtered(OPT_fmodule_file)) {
  2622. StringRef Val = A->getValue();
  2623. if (Val.contains('=')) {
  2624. auto Split = Val.split('=');
  2625. Opts.PrebuiltModuleFiles.insert(
  2626. {std::string(Split.first), std::string(Split.second)});
  2627. }
  2628. }
  2629. for (const auto *A : Args.filtered(OPT_fprebuilt_module_path))
  2630. Opts.AddPrebuiltModulePath(A->getValue());
  2631. for (const auto *A : Args.filtered(OPT_fmodules_ignore_macro)) {
  2632. StringRef MacroDef = A->getValue();
  2633. Opts.ModulesIgnoreMacros.insert(
  2634. llvm::CachedHashString(MacroDef.split('=').first));
  2635. }
  2636. // Add -I..., -F..., and -index-header-map options in order.
  2637. bool IsIndexHeaderMap = false;
  2638. bool IsSysrootSpecified =
  2639. Args.hasArg(OPT__sysroot_EQ) || Args.hasArg(OPT_isysroot);
  2640. for (const auto *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) {
  2641. if (A->getOption().matches(OPT_index_header_map)) {
  2642. // -index-header-map applies to the next -I or -F.
  2643. IsIndexHeaderMap = true;
  2644. continue;
  2645. }
  2646. frontend::IncludeDirGroup Group =
  2647. IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled;
  2648. bool IsFramework = A->getOption().matches(OPT_F);
  2649. std::string Path = A->getValue();
  2650. if (IsSysrootSpecified && !IsFramework && A->getValue()[0] == '=') {
  2651. SmallString<32> Buffer;
  2652. llvm::sys::path::append(Buffer, Opts.Sysroot,
  2653. llvm::StringRef(A->getValue()).substr(1));
  2654. Path = std::string(Buffer.str());
  2655. }
  2656. Opts.AddPath(Path, Group, IsFramework,
  2657. /*IgnoreSysroot*/ true);
  2658. IsIndexHeaderMap = false;
  2659. }
  2660. // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
  2661. StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
  2662. for (const auto *A :
  2663. Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) {
  2664. if (A->getOption().matches(OPT_iprefix))
  2665. Prefix = A->getValue();
  2666. else if (A->getOption().matches(OPT_iwithprefix))
  2667. Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true);
  2668. else
  2669. Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true);
  2670. }
  2671. for (const auto *A : Args.filtered(OPT_idirafter))
  2672. Opts.AddPath(A->getValue(), frontend::After, false, true);
  2673. for (const auto *A : Args.filtered(OPT_iquote))
  2674. Opts.AddPath(A->getValue(), frontend::Quoted, false, true);
  2675. for (const auto *A : Args.filtered(OPT_isystem, OPT_iwithsysroot))
  2676. Opts.AddPath(A->getValue(), frontend::System, false,
  2677. !A->getOption().matches(OPT_iwithsysroot));
  2678. for (const auto *A : Args.filtered(OPT_iframework))
  2679. Opts.AddPath(A->getValue(), frontend::System, true, true);
  2680. for (const auto *A : Args.filtered(OPT_iframeworkwithsysroot))
  2681. Opts.AddPath(A->getValue(), frontend::System, /*IsFramework=*/true,
  2682. /*IgnoreSysRoot=*/false);
  2683. // Add the paths for the various language specific isystem flags.
  2684. for (const auto *A : Args.filtered(OPT_c_isystem))
  2685. Opts.AddPath(A->getValue(), frontend::CSystem, false, true);
  2686. for (const auto *A : Args.filtered(OPT_cxx_isystem))
  2687. Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true);
  2688. for (const auto *A : Args.filtered(OPT_objc_isystem))
  2689. Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true);
  2690. for (const auto *A : Args.filtered(OPT_objcxx_isystem))
  2691. Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true);
  2692. // Add the internal paths from a driver that detects standard include paths.
  2693. for (const auto *A :
  2694. Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) {
  2695. frontend::IncludeDirGroup Group = frontend::System;
  2696. if (A->getOption().matches(OPT_internal_externc_isystem))
  2697. Group = frontend::ExternCSystem;
  2698. Opts.AddPath(A->getValue(), Group, false, true);
  2699. }
  2700. // Add the path prefixes which are implicitly treated as being system headers.
  2701. for (const auto *A :
  2702. Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix))
  2703. Opts.AddSystemHeaderPrefix(
  2704. A->getValue(), A->getOption().matches(OPT_system_header_prefix));
  2705. for (const auto *A : Args.filtered(OPT_ivfsoverlay))
  2706. Opts.AddVFSOverlayFile(A->getValue());
  2707. Opts.CaseInsensitive = Args.hasArg(OPT_fcase_insensitive_paths);
  2708. return Diags.getNumErrors() == NumErrorsBefore;
  2709. }
  2710. void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
  2711. const llvm::Triple &T,
  2712. std::vector<std::string> &Includes,
  2713. LangStandard::Kind LangStd) {
  2714. // Set some properties which depend solely on the input kind; it would be nice
  2715. // to move these to the language standard, and have the driver resolve the
  2716. // input kind + language standard.
  2717. //
  2718. // FIXME: Perhaps a better model would be for a single source file to have
  2719. // multiple language standards (C / C++ std, ObjC std, OpenCL std, OpenMP std)
  2720. // simultaneously active?
  2721. if (IK.getLanguage() == Language::Asm) {
  2722. Opts.AsmPreprocessor = 1;
  2723. } else if (IK.isObjectiveC()) {
  2724. Opts.ObjC = 1;
  2725. }
  2726. if (LangStd == LangStandard::lang_unspecified) {
  2727. // Based on the base language, pick one.
  2728. switch (IK.getLanguage()) {
  2729. case Language::Unknown:
  2730. case Language::LLVM_IR:
  2731. llvm_unreachable("Invalid input kind!");
  2732. case Language::OpenCL:
  2733. LangStd = LangStandard::lang_opencl12;
  2734. break;
  2735. case Language::OpenCLCXX:
  2736. LangStd = LangStandard::lang_openclcpp10;
  2737. break;
  2738. case Language::CUDA:
  2739. LangStd = LangStandard::lang_cuda;
  2740. break;
  2741. case Language::Asm:
  2742. case Language::C:
  2743. #if defined(CLANG_DEFAULT_STD_C)
  2744. LangStd = CLANG_DEFAULT_STD_C;
  2745. #else
  2746. // The PS4 uses C99 as the default C standard.
  2747. if (T.isPS4())
  2748. LangStd = LangStandard::lang_gnu99;
  2749. else
  2750. LangStd = LangStandard::lang_gnu17;
  2751. #endif
  2752. break;
  2753. case Language::ObjC:
  2754. #if defined(CLANG_DEFAULT_STD_C)
  2755. LangStd = CLANG_DEFAULT_STD_C;
  2756. #else
  2757. LangStd = LangStandard::lang_gnu11;
  2758. #endif
  2759. break;
  2760. case Language::CXX:
  2761. case Language::ObjCXX:
  2762. #if defined(CLANG_DEFAULT_STD_CXX)
  2763. LangStd = CLANG_DEFAULT_STD_CXX;
  2764. #else
  2765. LangStd = LangStandard::lang_gnucxx14;
  2766. #endif
  2767. break;
  2768. case Language::RenderScript:
  2769. LangStd = LangStandard::lang_c99;
  2770. break;
  2771. case Language::HIP:
  2772. LangStd = LangStandard::lang_hip;
  2773. break;
  2774. }
  2775. }
  2776. const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
  2777. Opts.LangStd = LangStd;
  2778. Opts.LineComment = Std.hasLineComments();
  2779. Opts.C99 = Std.isC99();
  2780. Opts.C11 = Std.isC11();
  2781. Opts.C17 = Std.isC17();
  2782. Opts.C2x = Std.isC2x();
  2783. Opts.CPlusPlus = Std.isCPlusPlus();
  2784. Opts.CPlusPlus11 = Std.isCPlusPlus11();
  2785. Opts.CPlusPlus14 = Std.isCPlusPlus14();
  2786. Opts.CPlusPlus17 = Std.isCPlusPlus17();
  2787. Opts.CPlusPlus20 = Std.isCPlusPlus20();
  2788. Opts.CPlusPlus2b = Std.isCPlusPlus2b();
  2789. Opts.GNUMode = Std.isGNUMode();
  2790. Opts.GNUCVersion = 0;
  2791. Opts.HexFloats = Std.hasHexFloats();
  2792. Opts.ImplicitInt = Std.hasImplicitInt();
  2793. // Set OpenCL Version.
  2794. Opts.OpenCL = Std.isOpenCL();
  2795. if (LangStd == LangStandard::lang_opencl10)
  2796. Opts.OpenCLVersion = 100;
  2797. else if (LangStd == LangStandard::lang_opencl11)
  2798. Opts.OpenCLVersion = 110;
  2799. else if (LangStd == LangStandard::lang_opencl12)
  2800. Opts.OpenCLVersion = 120;
  2801. else if (LangStd == LangStandard::lang_opencl20)
  2802. Opts.OpenCLVersion = 200;
  2803. else if (LangStd == LangStandard::lang_opencl30)
  2804. Opts.OpenCLVersion = 300;
  2805. else if (LangStd == LangStandard::lang_openclcpp10)
  2806. Opts.OpenCLCPlusPlusVersion = 100;
  2807. else if (LangStd == LangStandard::lang_openclcpp2021)
  2808. Opts.OpenCLCPlusPlusVersion = 202100;
  2809. // OpenCL has some additional defaults.
  2810. if (Opts.OpenCL) {
  2811. Opts.AltiVec = 0;
  2812. Opts.ZVector = 0;
  2813. Opts.setDefaultFPContractMode(LangOptions::FPM_On);
  2814. Opts.OpenCLCPlusPlus = Opts.CPlusPlus;
  2815. Opts.OpenCLPipes = Opts.getOpenCLCompatibleVersion() == 200;
  2816. Opts.OpenCLGenericAddressSpace = Opts.getOpenCLCompatibleVersion() == 200;
  2817. // Include default header file for OpenCL.
  2818. if (Opts.IncludeDefaultHeader) {
  2819. if (Opts.DeclareOpenCLBuiltins) {
  2820. // Only include base header file for builtin types and constants.
  2821. Includes.push_back("opencl-c-base.h");
  2822. } else {
  2823. Includes.push_back("opencl-c.h");
  2824. }
  2825. }
  2826. }
  2827. Opts.HIP = IK.getLanguage() == Language::HIP;
  2828. Opts.CUDA = IK.getLanguage() == Language::CUDA || Opts.HIP;
  2829. if (Opts.HIP) {
  2830. // HIP toolchain does not support 'Fast' FPOpFusion in backends since it
  2831. // fuses multiplication/addition instructions without contract flag from
  2832. // device library functions in LLVM bitcode, which causes accuracy loss in
  2833. // certain math functions, e.g. tan(-1e20) becomes -0.933 instead of 0.8446.
  2834. // For device library functions in bitcode to work, 'Strict' or 'Standard'
  2835. // FPOpFusion options in backends is needed. Therefore 'fast-honor-pragmas'
  2836. // FP contract option is used to allow fuse across statements in frontend
  2837. // whereas respecting contract flag in backend.
  2838. Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
  2839. } else if (Opts.CUDA) {
  2840. // Allow fuse across statements disregarding pragmas.
  2841. Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
  2842. }
  2843. Opts.RenderScript = IK.getLanguage() == Language::RenderScript;
  2844. // OpenCL and C++ both have bool, true, false keywords.
  2845. Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
  2846. // OpenCL has half keyword
  2847. Opts.Half = Opts.OpenCL;
  2848. }
  2849. /// Check if input file kind and language standard are compatible.
  2850. static bool IsInputCompatibleWithStandard(InputKind IK,
  2851. const LangStandard &S) {
  2852. switch (IK.getLanguage()) {
  2853. case Language::Unknown:
  2854. case Language::LLVM_IR:
  2855. llvm_unreachable("should not parse language flags for this input");
  2856. case Language::C:
  2857. case Language::ObjC:
  2858. case Language::RenderScript:
  2859. return S.getLanguage() == Language::C;
  2860. case Language::OpenCL:
  2861. return S.getLanguage() == Language::OpenCL ||
  2862. S.getLanguage() == Language::OpenCLCXX;
  2863. case Language::OpenCLCXX:
  2864. return S.getLanguage() == Language::OpenCLCXX;
  2865. case Language::CXX:
  2866. case Language::ObjCXX:
  2867. return S.getLanguage() == Language::CXX;
  2868. case Language::CUDA:
  2869. // FIXME: What -std= values should be permitted for CUDA compilations?
  2870. return S.getLanguage() == Language::CUDA ||
  2871. S.getLanguage() == Language::CXX;
  2872. case Language::HIP:
  2873. return S.getLanguage() == Language::CXX || S.getLanguage() == Language::HIP;
  2874. case Language::Asm:
  2875. // Accept (and ignore) all -std= values.
  2876. // FIXME: The -std= value is not ignored; it affects the tokenization
  2877. // and preprocessing rules if we're preprocessing this asm input.
  2878. return true;
  2879. }
  2880. llvm_unreachable("unexpected input language");
  2881. }
  2882. /// Get language name for given input kind.
  2883. static StringRef GetInputKindName(InputKind IK) {
  2884. switch (IK.getLanguage()) {
  2885. case Language::C:
  2886. return "C";
  2887. case Language::ObjC:
  2888. return "Objective-C";
  2889. case Language::CXX:
  2890. return "C++";
  2891. case Language::ObjCXX:
  2892. return "Objective-C++";
  2893. case Language::OpenCL:
  2894. return "OpenCL";
  2895. case Language::OpenCLCXX:
  2896. return "C++ for OpenCL";
  2897. case Language::CUDA:
  2898. return "CUDA";
  2899. case Language::RenderScript:
  2900. return "RenderScript";
  2901. case Language::HIP:
  2902. return "HIP";
  2903. case Language::Asm:
  2904. return "Asm";
  2905. case Language::LLVM_IR:
  2906. return "LLVM IR";
  2907. case Language::Unknown:
  2908. break;
  2909. }
  2910. llvm_unreachable("unknown input language");
  2911. }
  2912. void CompilerInvocation::GenerateLangArgs(const LangOptions &Opts,
  2913. SmallVectorImpl<const char *> &Args,
  2914. StringAllocator SA,
  2915. const llvm::Triple &T, InputKind IK) {
  2916. if (IK.getFormat() == InputKind::Precompiled ||
  2917. IK.getLanguage() == Language::LLVM_IR) {
  2918. if (Opts.ObjCAutoRefCount)
  2919. GenerateArg(Args, OPT_fobjc_arc, SA);
  2920. if (Opts.PICLevel != 0)
  2921. GenerateArg(Args, OPT_pic_level, Twine(Opts.PICLevel), SA);
  2922. if (Opts.PIE)
  2923. GenerateArg(Args, OPT_pic_is_pie, SA);
  2924. for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
  2925. GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
  2926. return;
  2927. }
  2928. OptSpecifier StdOpt;
  2929. switch (Opts.LangStd) {
  2930. case LangStandard::lang_opencl10:
  2931. case LangStandard::lang_opencl11:
  2932. case LangStandard::lang_opencl12:
  2933. case LangStandard::lang_opencl20:
  2934. case LangStandard::lang_opencl30:
  2935. case LangStandard::lang_openclcpp10:
  2936. case LangStandard::lang_openclcpp2021:
  2937. StdOpt = OPT_cl_std_EQ;
  2938. break;
  2939. default:
  2940. StdOpt = OPT_std_EQ;
  2941. break;
  2942. }
  2943. auto LangStandard = LangStandard::getLangStandardForKind(Opts.LangStd);
  2944. GenerateArg(Args, StdOpt, LangStandard.getName(), SA);
  2945. if (Opts.IncludeDefaultHeader)
  2946. GenerateArg(Args, OPT_finclude_default_header, SA);
  2947. if (Opts.DeclareOpenCLBuiltins)
  2948. GenerateArg(Args, OPT_fdeclare_opencl_builtins, SA);
  2949. const LangOptions *LangOpts = &Opts;
  2950. #define LANG_OPTION_WITH_MARSHALLING( \
  2951. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  2952. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  2953. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  2954. MERGER, EXTRACTOR, TABLE_INDEX) \
  2955. GENERATE_OPTION_WITH_MARSHALLING( \
  2956. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  2957. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  2958. #include "clang/Driver/Options.inc"
  2959. #undef LANG_OPTION_WITH_MARSHALLING
  2960. // The '-fcf-protection=' option is generated by CodeGenOpts generator.
  2961. if (Opts.ObjC) {
  2962. GenerateArg(Args, OPT_fobjc_runtime_EQ, Opts.ObjCRuntime.getAsString(), SA);
  2963. if (Opts.GC == LangOptions::GCOnly)
  2964. GenerateArg(Args, OPT_fobjc_gc_only, SA);
  2965. else if (Opts.GC == LangOptions::HybridGC)
  2966. GenerateArg(Args, OPT_fobjc_gc, SA);
  2967. else if (Opts.ObjCAutoRefCount == 1)
  2968. GenerateArg(Args, OPT_fobjc_arc, SA);
  2969. if (Opts.ObjCWeakRuntime)
  2970. GenerateArg(Args, OPT_fobjc_runtime_has_weak, SA);
  2971. if (Opts.ObjCWeak)
  2972. GenerateArg(Args, OPT_fobjc_weak, SA);
  2973. if (Opts.ObjCSubscriptingLegacyRuntime)
  2974. GenerateArg(Args, OPT_fobjc_subscripting_legacy_runtime, SA);
  2975. }
  2976. if (Opts.GNUCVersion != 0) {
  2977. unsigned Major = Opts.GNUCVersion / 100 / 100;
  2978. unsigned Minor = (Opts.GNUCVersion / 100) % 100;
  2979. unsigned Patch = Opts.GNUCVersion % 100;
  2980. GenerateArg(Args, OPT_fgnuc_version_EQ,
  2981. Twine(Major) + "." + Twine(Minor) + "." + Twine(Patch), SA);
  2982. }
  2983. if (Opts.IgnoreXCOFFVisibility)
  2984. GenerateArg(Args, OPT_mignore_xcoff_visibility, SA);
  2985. if (Opts.SignedOverflowBehavior == LangOptions::SOB_Trapping) {
  2986. GenerateArg(Args, OPT_ftrapv, SA);
  2987. GenerateArg(Args, OPT_ftrapv_handler, Opts.OverflowHandler, SA);
  2988. } else if (Opts.SignedOverflowBehavior == LangOptions::SOB_Defined) {
  2989. GenerateArg(Args, OPT_fwrapv, SA);
  2990. }
  2991. if (Opts.MSCompatibilityVersion != 0) {
  2992. unsigned Major = Opts.MSCompatibilityVersion / 10000000;
  2993. unsigned Minor = (Opts.MSCompatibilityVersion / 100000) % 100;
  2994. unsigned Subminor = Opts.MSCompatibilityVersion % 100000;
  2995. GenerateArg(Args, OPT_fms_compatibility_version,
  2996. Twine(Major) + "." + Twine(Minor) + "." + Twine(Subminor), SA);
  2997. }
  2998. if ((!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS()) {
  2999. if (!Opts.Trigraphs)
  3000. GenerateArg(Args, OPT_fno_trigraphs, SA);
  3001. } else {
  3002. if (Opts.Trigraphs)
  3003. GenerateArg(Args, OPT_ftrigraphs, SA);
  3004. }
  3005. if (Opts.Blocks && !(Opts.OpenCL && Opts.OpenCLVersion == 200))
  3006. GenerateArg(Args, OPT_fblocks, SA);
  3007. if (Opts.ConvergentFunctions &&
  3008. !(Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) || Opts.SYCLIsDevice))
  3009. GenerateArg(Args, OPT_fconvergent_functions, SA);
  3010. if (Opts.NoBuiltin && !Opts.Freestanding)
  3011. GenerateArg(Args, OPT_fno_builtin, SA);
  3012. if (!Opts.NoBuiltin)
  3013. for (const auto &Func : Opts.NoBuiltinFuncs)
  3014. GenerateArg(Args, OPT_fno_builtin_, Func, SA);
  3015. if (Opts.LongDoubleSize == 128)
  3016. GenerateArg(Args, OPT_mlong_double_128, SA);
  3017. else if (Opts.LongDoubleSize == 64)
  3018. GenerateArg(Args, OPT_mlong_double_64, SA);
  3019. // Not generating '-mrtd', it's just an alias for '-fdefault-calling-conv='.
  3020. // OpenMP was requested via '-fopenmp', not implied by '-fopenmp-simd' or
  3021. // '-fopenmp-targets='.
  3022. if (Opts.OpenMP && !Opts.OpenMPSimd) {
  3023. GenerateArg(Args, OPT_fopenmp, SA);
  3024. if (Opts.OpenMP != 50)
  3025. GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
  3026. if (!Opts.OpenMPUseTLS)
  3027. GenerateArg(Args, OPT_fnoopenmp_use_tls, SA);
  3028. if (Opts.OpenMPIsDevice)
  3029. GenerateArg(Args, OPT_fopenmp_is_device, SA);
  3030. if (Opts.OpenMPIRBuilder)
  3031. GenerateArg(Args, OPT_fopenmp_enable_irbuilder, SA);
  3032. }
  3033. if (Opts.OpenMPSimd) {
  3034. GenerateArg(Args, OPT_fopenmp_simd, SA);
  3035. if (Opts.OpenMP != 50)
  3036. GenerateArg(Args, OPT_fopenmp_version_EQ, Twine(Opts.OpenMP), SA);
  3037. }
  3038. if (Opts.OpenMPTargetNewRuntime)
  3039. GenerateArg(Args, OPT_fopenmp_target_new_runtime, SA);
  3040. if (Opts.OpenMPThreadSubscription)
  3041. GenerateArg(Args, OPT_fopenmp_assume_threads_oversubscription, SA);
  3042. if (Opts.OpenMPTeamSubscription)
  3043. GenerateArg(Args, OPT_fopenmp_assume_teams_oversubscription, SA);
  3044. if (Opts.OpenMPTargetDebug != 0)
  3045. GenerateArg(Args, OPT_fopenmp_target_debug_EQ,
  3046. Twine(Opts.OpenMPTargetDebug), SA);
  3047. if (Opts.OpenMPCUDANumSMs != 0)
  3048. GenerateArg(Args, OPT_fopenmp_cuda_number_of_sm_EQ,
  3049. Twine(Opts.OpenMPCUDANumSMs), SA);
  3050. if (Opts.OpenMPCUDABlocksPerSM != 0)
  3051. GenerateArg(Args, OPT_fopenmp_cuda_blocks_per_sm_EQ,
  3052. Twine(Opts.OpenMPCUDABlocksPerSM), SA);
  3053. if (Opts.OpenMPCUDAReductionBufNum != 1024)
  3054. GenerateArg(Args, OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
  3055. Twine(Opts.OpenMPCUDAReductionBufNum), SA);
  3056. if (!Opts.OMPTargetTriples.empty()) {
  3057. std::string Targets;
  3058. llvm::raw_string_ostream OS(Targets);
  3059. llvm::interleave(
  3060. Opts.OMPTargetTriples, OS,
  3061. [&OS](const llvm::Triple &T) { OS << T.str(); }, ",");
  3062. GenerateArg(Args, OPT_fopenmp_targets_EQ, OS.str(), SA);
  3063. }
  3064. if (!Opts.OMPHostIRFile.empty())
  3065. GenerateArg(Args, OPT_fopenmp_host_ir_file_path, Opts.OMPHostIRFile, SA);
  3066. if (Opts.OpenMPCUDAMode)
  3067. GenerateArg(Args, OPT_fopenmp_cuda_mode, SA);
  3068. if (Opts.OpenMPCUDAForceFullRuntime)
  3069. GenerateArg(Args, OPT_fopenmp_cuda_force_full_runtime, SA);
  3070. // The arguments used to set Optimize, OptimizeSize and NoInlineDefine are
  3071. // generated from CodeGenOptions.
  3072. if (Opts.DefaultFPContractMode == LangOptions::FPM_Fast)
  3073. GenerateArg(Args, OPT_ffp_contract, "fast", SA);
  3074. else if (Opts.DefaultFPContractMode == LangOptions::FPM_On)
  3075. GenerateArg(Args, OPT_ffp_contract, "on", SA);
  3076. else if (Opts.DefaultFPContractMode == LangOptions::FPM_Off)
  3077. GenerateArg(Args, OPT_ffp_contract, "off", SA);
  3078. else if (Opts.DefaultFPContractMode == LangOptions::FPM_FastHonorPragmas)
  3079. GenerateArg(Args, OPT_ffp_contract, "fast-honor-pragmas", SA);
  3080. for (StringRef Sanitizer : serializeSanitizerKinds(Opts.Sanitize))
  3081. GenerateArg(Args, OPT_fsanitize_EQ, Sanitizer, SA);
  3082. // Conflating '-fsanitize-system-ignorelist' and '-fsanitize-ignorelist'.
  3083. for (const std::string &F : Opts.NoSanitizeFiles)
  3084. GenerateArg(Args, OPT_fsanitize_ignorelist_EQ, F, SA);
  3085. if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver3_8)
  3086. GenerateArg(Args, OPT_fclang_abi_compat_EQ, "3.8", SA);
  3087. else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver4)
  3088. GenerateArg(Args, OPT_fclang_abi_compat_EQ, "4.0", SA);
  3089. else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver6)
  3090. GenerateArg(Args, OPT_fclang_abi_compat_EQ, "6.0", SA);
  3091. else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver7)
  3092. GenerateArg(Args, OPT_fclang_abi_compat_EQ, "7.0", SA);
  3093. else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver9)
  3094. GenerateArg(Args, OPT_fclang_abi_compat_EQ, "9.0", SA);
  3095. else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver11)
  3096. GenerateArg(Args, OPT_fclang_abi_compat_EQ, "11.0", SA);
  3097. else if (Opts.getClangABICompat() == LangOptions::ClangABI::Ver12)
  3098. GenerateArg(Args, OPT_fclang_abi_compat_EQ, "12.0", SA);
  3099. if (Opts.getSignReturnAddressScope() ==
  3100. LangOptions::SignReturnAddressScopeKind::All)
  3101. GenerateArg(Args, OPT_msign_return_address_EQ, "all", SA);
  3102. else if (Opts.getSignReturnAddressScope() ==
  3103. LangOptions::SignReturnAddressScopeKind::NonLeaf)
  3104. GenerateArg(Args, OPT_msign_return_address_EQ, "non-leaf", SA);
  3105. if (Opts.getSignReturnAddressKey() ==
  3106. LangOptions::SignReturnAddressKeyKind::BKey)
  3107. GenerateArg(Args, OPT_msign_return_address_key_EQ, "b_key", SA);
  3108. if (Opts.CXXABI)
  3109. GenerateArg(Args, OPT_fcxx_abi_EQ, TargetCXXABI::getSpelling(*Opts.CXXABI),
  3110. SA);
  3111. if (Opts.RelativeCXXABIVTables)
  3112. GenerateArg(Args, OPT_fexperimental_relative_cxx_abi_vtables, SA);
  3113. else
  3114. GenerateArg(Args, OPT_fno_experimental_relative_cxx_abi_vtables, SA);
  3115. for (const auto &MP : Opts.MacroPrefixMap)
  3116. GenerateArg(Args, OPT_fmacro_prefix_map_EQ, MP.first + "=" + MP.second, SA);
  3117. }
  3118. bool CompilerInvocation::ParseLangArgs(LangOptions &Opts, ArgList &Args,
  3119. InputKind IK, const llvm::Triple &T,
  3120. std::vector<std::string> &Includes,
  3121. DiagnosticsEngine &Diags) {
  3122. unsigned NumErrorsBefore = Diags.getNumErrors();
  3123. if (IK.getFormat() == InputKind::Precompiled ||
  3124. IK.getLanguage() == Language::LLVM_IR) {
  3125. // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the
  3126. // PassManager in BackendUtil.cpp. They need to be initialized no matter
  3127. // what the input type is.
  3128. if (Args.hasArg(OPT_fobjc_arc))
  3129. Opts.ObjCAutoRefCount = 1;
  3130. // PICLevel and PIELevel are needed during code generation and this should
  3131. // be set regardless of the input type.
  3132. Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
  3133. Opts.PIE = Args.hasArg(OPT_pic_is_pie);
  3134. parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
  3135. Diags, Opts.Sanitize);
  3136. return Diags.getNumErrors() == NumErrorsBefore;
  3137. }
  3138. // Other LangOpts are only initialized when the input is not AST or LLVM IR.
  3139. // FIXME: Should we really be parsing this for an Language::Asm input?
  3140. // FIXME: Cleanup per-file based stuff.
  3141. LangStandard::Kind LangStd = LangStandard::lang_unspecified;
  3142. if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
  3143. LangStd = LangStandard::getLangKind(A->getValue());
  3144. if (LangStd == LangStandard::lang_unspecified) {
  3145. Diags.Report(diag::err_drv_invalid_value)
  3146. << A->getAsString(Args) << A->getValue();
  3147. // Report supported standards with short description.
  3148. for (unsigned KindValue = 0;
  3149. KindValue != LangStandard::lang_unspecified;
  3150. ++KindValue) {
  3151. const LangStandard &Std = LangStandard::getLangStandardForKind(
  3152. static_cast<LangStandard::Kind>(KindValue));
  3153. if (IsInputCompatibleWithStandard(IK, Std)) {
  3154. auto Diag = Diags.Report(diag::note_drv_use_standard);
  3155. Diag << Std.getName() << Std.getDescription();
  3156. unsigned NumAliases = 0;
  3157. #define LANGSTANDARD(id, name, lang, desc, features)
  3158. #define LANGSTANDARD_ALIAS(id, alias) \
  3159. if (KindValue == LangStandard::lang_##id) ++NumAliases;
  3160. #define LANGSTANDARD_ALIAS_DEPR(id, alias)
  3161. #include "clang/Basic/LangStandards.def"
  3162. Diag << NumAliases;
  3163. #define LANGSTANDARD(id, name, lang, desc, features)
  3164. #define LANGSTANDARD_ALIAS(id, alias) \
  3165. if (KindValue == LangStandard::lang_##id) Diag << alias;
  3166. #define LANGSTANDARD_ALIAS_DEPR(id, alias)
  3167. #include "clang/Basic/LangStandards.def"
  3168. }
  3169. }
  3170. } else {
  3171. // Valid standard, check to make sure language and standard are
  3172. // compatible.
  3173. const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
  3174. if (!IsInputCompatibleWithStandard(IK, Std)) {
  3175. Diags.Report(diag::err_drv_argument_not_allowed_with)
  3176. << A->getAsString(Args) << GetInputKindName(IK);
  3177. }
  3178. }
  3179. }
  3180. // -cl-std only applies for OpenCL language standards.
  3181. // Override the -std option in this case.
  3182. if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
  3183. LangStandard::Kind OpenCLLangStd
  3184. = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
  3185. .Cases("cl", "CL", LangStandard::lang_opencl10)
  3186. .Cases("cl1.0", "CL1.0", LangStandard::lang_opencl10)
  3187. .Cases("cl1.1", "CL1.1", LangStandard::lang_opencl11)
  3188. .Cases("cl1.2", "CL1.2", LangStandard::lang_opencl12)
  3189. .Cases("cl2.0", "CL2.0", LangStandard::lang_opencl20)
  3190. .Cases("cl3.0", "CL3.0", LangStandard::lang_opencl30)
  3191. .Cases("clc++", "CLC++", LangStandard::lang_openclcpp10)
  3192. .Cases("clc++1.0", "CLC++1.0", LangStandard::lang_openclcpp10)
  3193. .Cases("clc++2021", "CLC++2021", LangStandard::lang_openclcpp2021)
  3194. .Default(LangStandard::lang_unspecified);
  3195. if (OpenCLLangStd == LangStandard::lang_unspecified) {
  3196. Diags.Report(diag::err_drv_invalid_value)
  3197. << A->getAsString(Args) << A->getValue();
  3198. }
  3199. else
  3200. LangStd = OpenCLLangStd;
  3201. }
  3202. // These need to be parsed now. They are used to set OpenCL defaults.
  3203. Opts.IncludeDefaultHeader = Args.hasArg(OPT_finclude_default_header);
  3204. Opts.DeclareOpenCLBuiltins = Args.hasArg(OPT_fdeclare_opencl_builtins);
  3205. CompilerInvocation::setLangDefaults(Opts, IK, T, Includes, LangStd);
  3206. // The key paths of codegen options defined in Options.td start with
  3207. // "LangOpts->". Let's provide the expected variable name and type.
  3208. LangOptions *LangOpts = &Opts;
  3209. #define LANG_OPTION_WITH_MARSHALLING( \
  3210. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  3211. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  3212. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  3213. MERGER, EXTRACTOR, TABLE_INDEX) \
  3214. PARSE_OPTION_WITH_MARSHALLING( \
  3215. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  3216. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  3217. #include "clang/Driver/Options.inc"
  3218. #undef LANG_OPTION_WITH_MARSHALLING
  3219. if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
  3220. StringRef Name = A->getValue();
  3221. if (Name == "full" || Name == "branch") {
  3222. Opts.CFProtectionBranch = 1;
  3223. }
  3224. }
  3225. if ((Args.hasArg(OPT_fsycl_is_device) || Args.hasArg(OPT_fsycl_is_host)) &&
  3226. !Args.hasArg(OPT_sycl_std_EQ)) {
  3227. // If the user supplied -fsycl-is-device or -fsycl-is-host, but failed to
  3228. // provide -sycl-std=, we want to default it to whatever the default SYCL
  3229. // version is. I could not find a way to express this with the options
  3230. // tablegen because we still want this value to be SYCL_None when the user
  3231. // is not in device or host mode.
  3232. Opts.setSYCLVersion(LangOptions::SYCL_Default);
  3233. }
  3234. if (Opts.ObjC) {
  3235. if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
  3236. StringRef value = arg->getValue();
  3237. if (Opts.ObjCRuntime.tryParse(value))
  3238. Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
  3239. }
  3240. if (Args.hasArg(OPT_fobjc_gc_only))
  3241. Opts.setGC(LangOptions::GCOnly);
  3242. else if (Args.hasArg(OPT_fobjc_gc))
  3243. Opts.setGC(LangOptions::HybridGC);
  3244. else if (Args.hasArg(OPT_fobjc_arc)) {
  3245. Opts.ObjCAutoRefCount = 1;
  3246. if (!Opts.ObjCRuntime.allowsARC())
  3247. Diags.Report(diag::err_arc_unsupported_on_runtime);
  3248. }
  3249. // ObjCWeakRuntime tracks whether the runtime supports __weak, not
  3250. // whether the feature is actually enabled. This is predominantly
  3251. // determined by -fobjc-runtime, but we allow it to be overridden
  3252. // from the command line for testing purposes.
  3253. if (Args.hasArg(OPT_fobjc_runtime_has_weak))
  3254. Opts.ObjCWeakRuntime = 1;
  3255. else
  3256. Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak();
  3257. // ObjCWeak determines whether __weak is actually enabled.
  3258. // Note that we allow -fno-objc-weak to disable this even in ARC mode.
  3259. if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) {
  3260. if (!weakArg->getOption().matches(OPT_fobjc_weak)) {
  3261. assert(!Opts.ObjCWeak);
  3262. } else if (Opts.getGC() != LangOptions::NonGC) {
  3263. Diags.Report(diag::err_objc_weak_with_gc);
  3264. } else if (!Opts.ObjCWeakRuntime) {
  3265. Diags.Report(diag::err_objc_weak_unsupported);
  3266. } else {
  3267. Opts.ObjCWeak = 1;
  3268. }
  3269. } else if (Opts.ObjCAutoRefCount) {
  3270. Opts.ObjCWeak = Opts.ObjCWeakRuntime;
  3271. }
  3272. if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
  3273. Opts.ObjCSubscriptingLegacyRuntime =
  3274. (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
  3275. }
  3276. if (Arg *A = Args.getLastArg(options::OPT_fgnuc_version_EQ)) {
  3277. // Check that the version has 1 to 3 components and the minor and patch
  3278. // versions fit in two decimal digits.
  3279. VersionTuple GNUCVer;
  3280. bool Invalid = GNUCVer.tryParse(A->getValue());
  3281. unsigned Major = GNUCVer.getMajor();
  3282. unsigned Minor = GNUCVer.getMinor().getValueOr(0);
  3283. unsigned Patch = GNUCVer.getSubminor().getValueOr(0);
  3284. if (Invalid || GNUCVer.getBuild() || Minor >= 100 || Patch >= 100) {
  3285. Diags.Report(diag::err_drv_invalid_value)
  3286. << A->getAsString(Args) << A->getValue();
  3287. }
  3288. Opts.GNUCVersion = Major * 100 * 100 + Minor * 100 + Patch;
  3289. }
  3290. // In AIX OS, the -mignore-xcoff-visibility is enable by default if there is
  3291. // no -fvisibility=* option.
  3292. // This is the reason why '-fvisibility' needs to be always generated:
  3293. // its absence implies '-mignore-xcoff-visibility'.
  3294. //
  3295. // Suppose the original cc1 command line does contain '-fvisibility default':
  3296. // '-mignore-xcoff-visibility' should not be implied.
  3297. // * If '-fvisibility' is not generated (as most options with default values
  3298. // don't), its absence would imply '-mignore-xcoff-visibility'. This changes
  3299. // the command line semantics.
  3300. // * If '-fvisibility' is generated regardless of its presence and value,
  3301. // '-mignore-xcoff-visibility' won't be implied and the command line
  3302. // semantics are kept intact.
  3303. //
  3304. // When the original cc1 command line does **not** contain '-fvisibility',
  3305. // '-mignore-xcoff-visibility' is implied. The generated command line will
  3306. // contain both '-fvisibility default' and '-mignore-xcoff-visibility' and
  3307. // subsequent calls to `CreateFromArgs`/`generateCC1CommandLine` will always
  3308. // produce the same arguments.
  3309. if (T.isOSAIX() && (Args.hasArg(OPT_mignore_xcoff_visibility) ||
  3310. !Args.hasArg(OPT_fvisibility)))
  3311. Opts.IgnoreXCOFFVisibility = 1;
  3312. if (Args.hasArg(OPT_ftrapv)) {
  3313. Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
  3314. // Set the handler, if one is specified.
  3315. Opts.OverflowHandler =
  3316. std::string(Args.getLastArgValue(OPT_ftrapv_handler));
  3317. }
  3318. else if (Args.hasArg(OPT_fwrapv))
  3319. Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
  3320. Opts.CaseInsensitive = Args.hasArg(OPT_fcase_insensitive_paths);
  3321. Opts.MSCompatibilityVersion = 0;
  3322. if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) {
  3323. VersionTuple VT;
  3324. if (VT.tryParse(A->getValue()))
  3325. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
  3326. << A->getValue();
  3327. Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 +
  3328. VT.getMinor().getValueOr(0) * 100000 +
  3329. VT.getSubminor().getValueOr(0);
  3330. }
  3331. // Mimicking gcc's behavior, trigraphs are only enabled if -trigraphs
  3332. // is specified, or -std is set to a conforming mode.
  3333. // Trigraphs are disabled by default in c++1z onwards.
  3334. // For z/OS, trigraphs are enabled by default (without regard to the above).
  3335. Opts.Trigraphs =
  3336. (!Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus17) || T.isOSzOS();
  3337. Opts.Trigraphs =
  3338. Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs);
  3339. Opts.Blocks = Args.hasArg(OPT_fblocks) || (Opts.OpenCL
  3340. && Opts.OpenCLVersion == 200);
  3341. Opts.ConvergentFunctions = Opts.OpenCL || (Opts.CUDA && Opts.CUDAIsDevice) ||
  3342. Opts.SYCLIsDevice ||
  3343. Args.hasArg(OPT_fconvergent_functions);
  3344. Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
  3345. if (!Opts.NoBuiltin)
  3346. getAllNoBuiltinFuncValues(Args, Opts.NoBuiltinFuncs);
  3347. Opts.LongDoubleSize = Args.hasArg(OPT_mlong_double_128)
  3348. ? 128
  3349. : Args.hasArg(OPT_mlong_double_64) ? 64 : 0;
  3350. if (Opts.FastRelaxedMath)
  3351. Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
  3352. llvm::sort(Opts.ModuleFeatures);
  3353. // -mrtd option
  3354. if (Arg *A = Args.getLastArg(OPT_mrtd)) {
  3355. if (Opts.getDefaultCallingConv() != LangOptions::DCC_None)
  3356. Diags.Report(diag::err_drv_argument_not_allowed_with)
  3357. << A->getSpelling() << "-fdefault-calling-conv";
  3358. else {
  3359. if (T.getArch() != llvm::Triple::x86)
  3360. Diags.Report(diag::err_drv_argument_not_allowed_with)
  3361. << A->getSpelling() << T.getTriple();
  3362. else
  3363. Opts.setDefaultCallingConv(LangOptions::DCC_StdCall);
  3364. }
  3365. }
  3366. // Check if -fopenmp is specified and set default version to 5.0.
  3367. Opts.OpenMP = Args.hasArg(OPT_fopenmp) ? 50 : 0;
  3368. // Check if -fopenmp-simd is specified.
  3369. bool IsSimdSpecified =
  3370. Args.hasFlag(options::OPT_fopenmp_simd, options::OPT_fno_openmp_simd,
  3371. /*Default=*/false);
  3372. Opts.OpenMPSimd = !Opts.OpenMP && IsSimdSpecified;
  3373. Opts.OpenMPUseTLS =
  3374. Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls);
  3375. Opts.OpenMPIsDevice =
  3376. Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_is_device);
  3377. Opts.OpenMPIRBuilder =
  3378. Opts.OpenMP && Args.hasArg(options::OPT_fopenmp_enable_irbuilder);
  3379. bool IsTargetSpecified =
  3380. Opts.OpenMPIsDevice || Args.hasArg(options::OPT_fopenmp_targets_EQ);
  3381. Opts.OpenMPTargetNewRuntime =
  3382. Opts.OpenMPIsDevice &&
  3383. Args.hasArg(options::OPT_fopenmp_target_new_runtime);
  3384. Opts.ConvergentFunctions = Opts.ConvergentFunctions || Opts.OpenMPIsDevice;
  3385. if (Opts.OpenMP || Opts.OpenMPSimd) {
  3386. if (int Version = getLastArgIntValue(
  3387. Args, OPT_fopenmp_version_EQ,
  3388. (IsSimdSpecified || IsTargetSpecified) ? 50 : Opts.OpenMP, Diags))
  3389. Opts.OpenMP = Version;
  3390. // Provide diagnostic when a given target is not expected to be an OpenMP
  3391. // device or host.
  3392. if (!Opts.OpenMPIsDevice) {
  3393. switch (T.getArch()) {
  3394. default:
  3395. break;
  3396. // Add unsupported host targets here:
  3397. case llvm::Triple::nvptx:
  3398. case llvm::Triple::nvptx64:
  3399. Diags.Report(diag::err_drv_omp_host_target_not_supported) << T.str();
  3400. break;
  3401. }
  3402. }
  3403. }
  3404. // Set the flag to prevent the implementation from emitting device exception
  3405. // handling code for those requiring so.
  3406. if ((Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN())) ||
  3407. Opts.OpenCLCPlusPlus) {
  3408. Opts.Exceptions = 0;
  3409. Opts.CXXExceptions = 0;
  3410. }
  3411. if (Opts.OpenMPIsDevice && T.isNVPTX()) {
  3412. Opts.OpenMPCUDANumSMs =
  3413. getLastArgIntValue(Args, options::OPT_fopenmp_cuda_number_of_sm_EQ,
  3414. Opts.OpenMPCUDANumSMs, Diags);
  3415. Opts.OpenMPCUDABlocksPerSM =
  3416. getLastArgIntValue(Args, options::OPT_fopenmp_cuda_blocks_per_sm_EQ,
  3417. Opts.OpenMPCUDABlocksPerSM, Diags);
  3418. Opts.OpenMPCUDAReductionBufNum = getLastArgIntValue(
  3419. Args, options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ,
  3420. Opts.OpenMPCUDAReductionBufNum, Diags);
  3421. }
  3422. // Set the value of the debugging flag used in the new offloading device RTL.
  3423. // Set either by a specific value or to a default if not specified.
  3424. if (Opts.OpenMPIsDevice && (Args.hasArg(OPT_fopenmp_target_debug) ||
  3425. Args.hasArg(OPT_fopenmp_target_debug_EQ))) {
  3426. if (Opts.OpenMPTargetNewRuntime) {
  3427. Opts.OpenMPTargetDebug = getLastArgIntValue(
  3428. Args, OPT_fopenmp_target_debug_EQ, Opts.OpenMPTargetDebug, Diags);
  3429. if (!Opts.OpenMPTargetDebug && Args.hasArg(OPT_fopenmp_target_debug))
  3430. Opts.OpenMPTargetDebug = 1;
  3431. } else {
  3432. Diags.Report(diag::err_drv_debug_no_new_runtime);
  3433. }
  3434. }
  3435. if (Opts.OpenMPIsDevice && Opts.OpenMPTargetNewRuntime) {
  3436. if (Args.hasArg(OPT_fopenmp_assume_teams_oversubscription))
  3437. Opts.OpenMPTeamSubscription = true;
  3438. if (Args.hasArg(OPT_fopenmp_assume_threads_oversubscription))
  3439. Opts.OpenMPThreadSubscription = true;
  3440. }
  3441. // Get the OpenMP target triples if any.
  3442. if (Arg *A = Args.getLastArg(options::OPT_fopenmp_targets_EQ)) {
  3443. enum ArchPtrSize { Arch16Bit, Arch32Bit, Arch64Bit };
  3444. auto getArchPtrSize = [](const llvm::Triple &T) {
  3445. if (T.isArch16Bit())
  3446. return Arch16Bit;
  3447. if (T.isArch32Bit())
  3448. return Arch32Bit;
  3449. assert(T.isArch64Bit() && "Expected 64-bit architecture");
  3450. return Arch64Bit;
  3451. };
  3452. for (unsigned i = 0; i < A->getNumValues(); ++i) {
  3453. llvm::Triple TT(A->getValue(i));
  3454. if (TT.getArch() == llvm::Triple::UnknownArch ||
  3455. !(TT.getArch() == llvm::Triple::aarch64 || TT.isPPC() ||
  3456. TT.getArch() == llvm::Triple::nvptx ||
  3457. TT.getArch() == llvm::Triple::nvptx64 ||
  3458. TT.getArch() == llvm::Triple::amdgcn ||
  3459. TT.getArch() == llvm::Triple::x86 ||
  3460. TT.getArch() == llvm::Triple::x86_64))
  3461. Diags.Report(diag::err_drv_invalid_omp_target) << A->getValue(i);
  3462. else if (getArchPtrSize(T) != getArchPtrSize(TT))
  3463. Diags.Report(diag::err_drv_incompatible_omp_arch)
  3464. << A->getValue(i) << T.str();
  3465. else
  3466. Opts.OMPTargetTriples.push_back(TT);
  3467. }
  3468. }
  3469. // Get OpenMP host file path if any and report if a non existent file is
  3470. // found
  3471. if (Arg *A = Args.getLastArg(options::OPT_fopenmp_host_ir_file_path)) {
  3472. Opts.OMPHostIRFile = A->getValue();
  3473. if (!llvm::sys::fs::exists(Opts.OMPHostIRFile))
  3474. Diags.Report(diag::err_drv_omp_host_ir_file_not_found)
  3475. << Opts.OMPHostIRFile;
  3476. }
  3477. // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
  3478. Opts.OpenMPCUDAMode = Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
  3479. Args.hasArg(options::OPT_fopenmp_cuda_mode);
  3480. // Set CUDA mode for OpenMP target NVPTX/AMDGCN if specified in options
  3481. Opts.OpenMPCUDAForceFullRuntime =
  3482. Opts.OpenMPIsDevice && (T.isNVPTX() || T.isAMDGCN()) &&
  3483. Args.hasArg(options::OPT_fopenmp_cuda_force_full_runtime);
  3484. // FIXME: Eliminate this dependency.
  3485. unsigned Opt = getOptimizationLevel(Args, IK, Diags),
  3486. OptSize = getOptimizationLevelSize(Args);
  3487. Opts.Optimize = Opt != 0;
  3488. Opts.OptimizeSize = OptSize != 0;
  3489. // This is the __NO_INLINE__ define, which just depends on things like the
  3490. // optimization level and -fno-inline, not actually whether the backend has
  3491. // inlining enabled.
  3492. Opts.NoInlineDefine = !Opts.Optimize;
  3493. if (Arg *InlineArg = Args.getLastArg(
  3494. options::OPT_finline_functions, options::OPT_finline_hint_functions,
  3495. options::OPT_fno_inline_functions, options::OPT_fno_inline))
  3496. if (InlineArg->getOption().matches(options::OPT_fno_inline))
  3497. Opts.NoInlineDefine = true;
  3498. if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
  3499. StringRef Val = A->getValue();
  3500. if (Val == "fast")
  3501. Opts.setDefaultFPContractMode(LangOptions::FPM_Fast);
  3502. else if (Val == "on")
  3503. Opts.setDefaultFPContractMode(LangOptions::FPM_On);
  3504. else if (Val == "off")
  3505. Opts.setDefaultFPContractMode(LangOptions::FPM_Off);
  3506. else if (Val == "fast-honor-pragmas")
  3507. Opts.setDefaultFPContractMode(LangOptions::FPM_FastHonorPragmas);
  3508. else
  3509. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
  3510. }
  3511. // Parse -fsanitize= arguments.
  3512. parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ),
  3513. Diags, Opts.Sanitize);
  3514. Opts.NoSanitizeFiles = Args.getAllArgValues(OPT_fsanitize_ignorelist_EQ);
  3515. std::vector<std::string> systemIgnorelists =
  3516. Args.getAllArgValues(OPT_fsanitize_system_ignorelist_EQ);
  3517. Opts.NoSanitizeFiles.insert(Opts.NoSanitizeFiles.end(),
  3518. systemIgnorelists.begin(),
  3519. systemIgnorelists.end());
  3520. if (Arg *A = Args.getLastArg(OPT_fclang_abi_compat_EQ)) {
  3521. Opts.setClangABICompat(LangOptions::ClangABI::Latest);
  3522. StringRef Ver = A->getValue();
  3523. std::pair<StringRef, StringRef> VerParts = Ver.split('.');
  3524. unsigned Major, Minor = 0;
  3525. // Check the version number is valid: either 3.x (0 <= x <= 9) or
  3526. // y or y.0 (4 <= y <= current version).
  3527. if (!VerParts.first.startswith("0") &&
  3528. !VerParts.first.getAsInteger(10, Major) &&
  3529. 3 <= Major && Major <= CLANG_VERSION_MAJOR &&
  3530. (Major == 3 ? VerParts.second.size() == 1 &&
  3531. !VerParts.second.getAsInteger(10, Minor)
  3532. : VerParts.first.size() == Ver.size() ||
  3533. VerParts.second == "0")) {
  3534. // Got a valid version number.
  3535. if (Major == 3 && Minor <= 8)
  3536. Opts.setClangABICompat(LangOptions::ClangABI::Ver3_8);
  3537. else if (Major <= 4)
  3538. Opts.setClangABICompat(LangOptions::ClangABI::Ver4);
  3539. else if (Major <= 6)
  3540. Opts.setClangABICompat(LangOptions::ClangABI::Ver6);
  3541. else if (Major <= 7)
  3542. Opts.setClangABICompat(LangOptions::ClangABI::Ver7);
  3543. else if (Major <= 9)
  3544. Opts.setClangABICompat(LangOptions::ClangABI::Ver9);
  3545. else if (Major <= 11)
  3546. Opts.setClangABICompat(LangOptions::ClangABI::Ver11);
  3547. else if (Major <= 12)
  3548. Opts.setClangABICompat(LangOptions::ClangABI::Ver12);
  3549. } else if (Ver != "latest") {
  3550. Diags.Report(diag::err_drv_invalid_value)
  3551. << A->getAsString(Args) << A->getValue();
  3552. }
  3553. }
  3554. if (Arg *A = Args.getLastArg(OPT_msign_return_address_EQ)) {
  3555. StringRef SignScope = A->getValue();
  3556. if (SignScope.equals_insensitive("none"))
  3557. Opts.setSignReturnAddressScope(
  3558. LangOptions::SignReturnAddressScopeKind::None);
  3559. else if (SignScope.equals_insensitive("all"))
  3560. Opts.setSignReturnAddressScope(
  3561. LangOptions::SignReturnAddressScopeKind::All);
  3562. else if (SignScope.equals_insensitive("non-leaf"))
  3563. Opts.setSignReturnAddressScope(
  3564. LangOptions::SignReturnAddressScopeKind::NonLeaf);
  3565. else
  3566. Diags.Report(diag::err_drv_invalid_value)
  3567. << A->getAsString(Args) << SignScope;
  3568. if (Arg *A = Args.getLastArg(OPT_msign_return_address_key_EQ)) {
  3569. StringRef SignKey = A->getValue();
  3570. if (!SignScope.empty() && !SignKey.empty()) {
  3571. if (SignKey.equals_insensitive("a_key"))
  3572. Opts.setSignReturnAddressKey(
  3573. LangOptions::SignReturnAddressKeyKind::AKey);
  3574. else if (SignKey.equals_insensitive("b_key"))
  3575. Opts.setSignReturnAddressKey(
  3576. LangOptions::SignReturnAddressKeyKind::BKey);
  3577. else
  3578. Diags.Report(diag::err_drv_invalid_value)
  3579. << A->getAsString(Args) << SignKey;
  3580. }
  3581. }
  3582. }
  3583. // The value can be empty, which indicates the system default should be used.
  3584. StringRef CXXABI = Args.getLastArgValue(OPT_fcxx_abi_EQ);
  3585. if (!CXXABI.empty()) {
  3586. if (!TargetCXXABI::isABI(CXXABI)) {
  3587. Diags.Report(diag::err_invalid_cxx_abi) << CXXABI;
  3588. } else {
  3589. auto Kind = TargetCXXABI::getKind(CXXABI);
  3590. if (!TargetCXXABI::isSupportedCXXABI(T, Kind))
  3591. Diags.Report(diag::err_unsupported_cxx_abi) << CXXABI << T.str();
  3592. else
  3593. Opts.CXXABI = Kind;
  3594. }
  3595. }
  3596. Opts.RelativeCXXABIVTables =
  3597. Args.hasFlag(options::OPT_fexperimental_relative_cxx_abi_vtables,
  3598. options::OPT_fno_experimental_relative_cxx_abi_vtables,
  3599. TargetCXXABI::usesRelativeVTables(T));
  3600. for (const auto &A : Args.getAllArgValues(OPT_fmacro_prefix_map_EQ)) {
  3601. auto Split = StringRef(A).split('=');
  3602. Opts.MacroPrefixMap.insert(
  3603. {std::string(Split.first), std::string(Split.second)});
  3604. }
  3605. // Error if -mvscale-min is unbounded.
  3606. if (Arg *A = Args.getLastArg(options::OPT_mvscale_min_EQ)) {
  3607. unsigned VScaleMin;
  3608. if (StringRef(A->getValue()).getAsInteger(10, VScaleMin) || VScaleMin == 0)
  3609. Diags.Report(diag::err_cc1_unbounded_vscale_min);
  3610. }
  3611. return Diags.getNumErrors() == NumErrorsBefore;
  3612. }
  3613. static bool isStrictlyPreprocessorAction(frontend::ActionKind Action) {
  3614. switch (Action) {
  3615. case frontend::ASTDeclList:
  3616. case frontend::ASTDump:
  3617. case frontend::ASTPrint:
  3618. case frontend::ASTView:
  3619. case frontend::EmitAssembly:
  3620. case frontend::EmitBC:
  3621. case frontend::EmitHTML:
  3622. case frontend::EmitLLVM:
  3623. case frontend::EmitLLVMOnly:
  3624. case frontend::EmitCodeGenOnly:
  3625. case frontend::EmitObj:
  3626. case frontend::ExtractAPI:
  3627. case frontend::FixIt:
  3628. case frontend::GenerateModule:
  3629. case frontend::GenerateModuleInterface:
  3630. case frontend::GenerateHeaderModule:
  3631. case frontend::GeneratePCH:
  3632. case frontend::GenerateInterfaceStubs:
  3633. case frontend::ParseSyntaxOnly:
  3634. case frontend::ModuleFileInfo:
  3635. case frontend::VerifyPCH:
  3636. case frontend::PluginAction:
  3637. case frontend::RewriteObjC:
  3638. case frontend::RewriteTest:
  3639. case frontend::RunAnalysis:
  3640. case frontend::TemplightDump:
  3641. case frontend::MigrateSource:
  3642. return false;
  3643. case frontend::DumpCompilerOptions:
  3644. case frontend::DumpRawTokens:
  3645. case frontend::DumpTokens:
  3646. case frontend::InitOnly:
  3647. case frontend::PrintPreamble:
  3648. case frontend::PrintPreprocessedInput:
  3649. case frontend::RewriteMacros:
  3650. case frontend::RunPreprocessorOnly:
  3651. case frontend::PrintDependencyDirectivesSourceMinimizerOutput:
  3652. return true;
  3653. }
  3654. llvm_unreachable("invalid frontend action");
  3655. }
  3656. static void GeneratePreprocessorArgs(PreprocessorOptions &Opts,
  3657. SmallVectorImpl<const char *> &Args,
  3658. CompilerInvocation::StringAllocator SA,
  3659. const LangOptions &LangOpts,
  3660. const FrontendOptions &FrontendOpts,
  3661. const CodeGenOptions &CodeGenOpts) {
  3662. PreprocessorOptions *PreprocessorOpts = &Opts;
  3663. #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
  3664. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  3665. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  3666. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  3667. MERGER, EXTRACTOR, TABLE_INDEX) \
  3668. GENERATE_OPTION_WITH_MARSHALLING( \
  3669. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  3670. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  3671. #include "clang/Driver/Options.inc"
  3672. #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
  3673. if (Opts.PCHWithHdrStop && !Opts.PCHWithHdrStopCreate)
  3674. GenerateArg(Args, OPT_pch_through_hdrstop_use, SA);
  3675. for (const auto &D : Opts.DeserializedPCHDeclsToErrorOn)
  3676. GenerateArg(Args, OPT_error_on_deserialized_pch_decl, D, SA);
  3677. if (Opts.PrecompiledPreambleBytes != std::make_pair(0u, false))
  3678. GenerateArg(Args, OPT_preamble_bytes_EQ,
  3679. Twine(Opts.PrecompiledPreambleBytes.first) + "," +
  3680. (Opts.PrecompiledPreambleBytes.second ? "1" : "0"),
  3681. SA);
  3682. for (const auto &M : Opts.Macros) {
  3683. // Don't generate __CET__ macro definitions. They are implied by the
  3684. // -fcf-protection option that is generated elsewhere.
  3685. if (M.first == "__CET__=1" && !M.second &&
  3686. !CodeGenOpts.CFProtectionReturn && CodeGenOpts.CFProtectionBranch)
  3687. continue;
  3688. if (M.first == "__CET__=2" && !M.second && CodeGenOpts.CFProtectionReturn &&
  3689. !CodeGenOpts.CFProtectionBranch)
  3690. continue;
  3691. if (M.first == "__CET__=3" && !M.second && CodeGenOpts.CFProtectionReturn &&
  3692. CodeGenOpts.CFProtectionBranch)
  3693. continue;
  3694. GenerateArg(Args, M.second ? OPT_U : OPT_D, M.first, SA);
  3695. }
  3696. for (const auto &I : Opts.Includes) {
  3697. // Don't generate OpenCL includes. They are implied by other flags that are
  3698. // generated elsewhere.
  3699. if (LangOpts.OpenCL && LangOpts.IncludeDefaultHeader &&
  3700. ((LangOpts.DeclareOpenCLBuiltins && I == "opencl-c-base.h") ||
  3701. I == "opencl-c.h"))
  3702. continue;
  3703. GenerateArg(Args, OPT_include, I, SA);
  3704. }
  3705. for (const auto &CI : Opts.ChainedIncludes)
  3706. GenerateArg(Args, OPT_chain_include, CI, SA);
  3707. for (const auto &RF : Opts.RemappedFiles)
  3708. GenerateArg(Args, OPT_remap_file, RF.first + ";" + RF.second, SA);
  3709. // Don't handle LexEditorPlaceholders. It is implied by the action that is
  3710. // generated elsewhere.
  3711. }
  3712. static bool ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
  3713. DiagnosticsEngine &Diags,
  3714. frontend::ActionKind Action,
  3715. const FrontendOptions &FrontendOpts) {
  3716. unsigned NumErrorsBefore = Diags.getNumErrors();
  3717. PreprocessorOptions *PreprocessorOpts = &Opts;
  3718. #define PREPROCESSOR_OPTION_WITH_MARSHALLING( \
  3719. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  3720. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  3721. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  3722. MERGER, EXTRACTOR, TABLE_INDEX) \
  3723. PARSE_OPTION_WITH_MARSHALLING( \
  3724. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  3725. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  3726. #include "clang/Driver/Options.inc"
  3727. #undef PREPROCESSOR_OPTION_WITH_MARSHALLING
  3728. Opts.PCHWithHdrStop = Args.hasArg(OPT_pch_through_hdrstop_create) ||
  3729. Args.hasArg(OPT_pch_through_hdrstop_use);
  3730. for (const auto *A : Args.filtered(OPT_error_on_deserialized_pch_decl))
  3731. Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
  3732. if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
  3733. StringRef Value(A->getValue());
  3734. size_t Comma = Value.find(',');
  3735. unsigned Bytes = 0;
  3736. unsigned EndOfLine = 0;
  3737. if (Comma == StringRef::npos ||
  3738. Value.substr(0, Comma).getAsInteger(10, Bytes) ||
  3739. Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
  3740. Diags.Report(diag::err_drv_preamble_format);
  3741. else {
  3742. Opts.PrecompiledPreambleBytes.first = Bytes;
  3743. Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
  3744. }
  3745. }
  3746. // Add the __CET__ macro if a CFProtection option is set.
  3747. if (const Arg *A = Args.getLastArg(OPT_fcf_protection_EQ)) {
  3748. StringRef Name = A->getValue();
  3749. if (Name == "branch")
  3750. Opts.addMacroDef("__CET__=1");
  3751. else if (Name == "return")
  3752. Opts.addMacroDef("__CET__=2");
  3753. else if (Name == "full")
  3754. Opts.addMacroDef("__CET__=3");
  3755. }
  3756. // Add macros from the command line.
  3757. for (const auto *A : Args.filtered(OPT_D, OPT_U)) {
  3758. if (A->getOption().matches(OPT_D))
  3759. Opts.addMacroDef(A->getValue());
  3760. else
  3761. Opts.addMacroUndef(A->getValue());
  3762. }
  3763. // Add the ordered list of -includes.
  3764. for (const auto *A : Args.filtered(OPT_include))
  3765. Opts.Includes.emplace_back(A->getValue());
  3766. for (const auto *A : Args.filtered(OPT_chain_include))
  3767. Opts.ChainedIncludes.emplace_back(A->getValue());
  3768. for (const auto *A : Args.filtered(OPT_remap_file)) {
  3769. std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';');
  3770. if (Split.second.empty()) {
  3771. Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
  3772. continue;
  3773. }
  3774. Opts.addRemappedFile(Split.first, Split.second);
  3775. }
  3776. // Always avoid lexing editor placeholders when we're just running the
  3777. // preprocessor as we never want to emit the
  3778. // "editor placeholder in source file" error in PP only mode.
  3779. if (isStrictlyPreprocessorAction(Action))
  3780. Opts.LexEditorPlaceholders = false;
  3781. return Diags.getNumErrors() == NumErrorsBefore;
  3782. }
  3783. static void GeneratePreprocessorOutputArgs(
  3784. const PreprocessorOutputOptions &Opts, SmallVectorImpl<const char *> &Args,
  3785. CompilerInvocation::StringAllocator SA, frontend::ActionKind Action) {
  3786. const PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
  3787. #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
  3788. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  3789. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  3790. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  3791. MERGER, EXTRACTOR, TABLE_INDEX) \
  3792. GENERATE_OPTION_WITH_MARSHALLING( \
  3793. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  3794. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  3795. #include "clang/Driver/Options.inc"
  3796. #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
  3797. bool Generate_dM = isStrictlyPreprocessorAction(Action) && !Opts.ShowCPP;
  3798. if (Generate_dM)
  3799. GenerateArg(Args, OPT_dM, SA);
  3800. if (!Generate_dM && Opts.ShowMacros)
  3801. GenerateArg(Args, OPT_dD, SA);
  3802. }
  3803. static bool ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
  3804. ArgList &Args, DiagnosticsEngine &Diags,
  3805. frontend::ActionKind Action) {
  3806. unsigned NumErrorsBefore = Diags.getNumErrors();
  3807. PreprocessorOutputOptions &PreprocessorOutputOpts = Opts;
  3808. #define PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING( \
  3809. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  3810. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  3811. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  3812. MERGER, EXTRACTOR, TABLE_INDEX) \
  3813. PARSE_OPTION_WITH_MARSHALLING( \
  3814. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  3815. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  3816. #include "clang/Driver/Options.inc"
  3817. #undef PREPROCESSOR_OUTPUT_OPTION_WITH_MARSHALLING
  3818. Opts.ShowCPP = isStrictlyPreprocessorAction(Action) && !Args.hasArg(OPT_dM);
  3819. Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
  3820. return Diags.getNumErrors() == NumErrorsBefore;
  3821. }
  3822. static void GenerateTargetArgs(const TargetOptions &Opts,
  3823. SmallVectorImpl<const char *> &Args,
  3824. CompilerInvocation::StringAllocator SA) {
  3825. const TargetOptions *TargetOpts = &Opts;
  3826. #define TARGET_OPTION_WITH_MARSHALLING( \
  3827. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  3828. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  3829. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  3830. MERGER, EXTRACTOR, TABLE_INDEX) \
  3831. GENERATE_OPTION_WITH_MARSHALLING( \
  3832. Args, SA, KIND, FLAGS, SPELLING, ALWAYS_EMIT, KEYPATH, DEFAULT_VALUE, \
  3833. IMPLIED_CHECK, IMPLIED_VALUE, DENORMALIZER, EXTRACTOR, TABLE_INDEX)
  3834. #include "clang/Driver/Options.inc"
  3835. #undef TARGET_OPTION_WITH_MARSHALLING
  3836. if (!Opts.SDKVersion.empty())
  3837. GenerateArg(Args, OPT_target_sdk_version_EQ, Opts.SDKVersion.getAsString(),
  3838. SA);
  3839. }
  3840. static bool ParseTargetArgs(TargetOptions &Opts, ArgList &Args,
  3841. DiagnosticsEngine &Diags) {
  3842. unsigned NumErrorsBefore = Diags.getNumErrors();
  3843. TargetOptions *TargetOpts = &Opts;
  3844. #define TARGET_OPTION_WITH_MARSHALLING( \
  3845. PREFIX_TYPE, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
  3846. HELPTEXT, METAVAR, VALUES, SPELLING, SHOULD_PARSE, ALWAYS_EMIT, KEYPATH, \
  3847. DEFAULT_VALUE, IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, DENORMALIZER, \
  3848. MERGER, EXTRACTOR, TABLE_INDEX) \
  3849. PARSE_OPTION_WITH_MARSHALLING( \
  3850. Args, Diags, ID, FLAGS, PARAM, SHOULD_PARSE, KEYPATH, DEFAULT_VALUE, \
  3851. IMPLIED_CHECK, IMPLIED_VALUE, NORMALIZER, MERGER, TABLE_INDEX)
  3852. #include "clang/Driver/Options.inc"
  3853. #undef TARGET_OPTION_WITH_MARSHALLING
  3854. if (Arg *A = Args.getLastArg(options::OPT_target_sdk_version_EQ)) {
  3855. llvm::VersionTuple Version;
  3856. if (Version.tryParse(A->getValue()))
  3857. Diags.Report(diag::err_drv_invalid_value)
  3858. << A->getAsString(Args) << A->getValue();
  3859. else
  3860. Opts.SDKVersion = Version;
  3861. }
  3862. return Diags.getNumErrors() == NumErrorsBefore;
  3863. }
  3864. bool CompilerInvocation::CreateFromArgsImpl(
  3865. CompilerInvocation &Res, ArrayRef<const char *> CommandLineArgs,
  3866. DiagnosticsEngine &Diags, const char *Argv0) {
  3867. unsigned NumErrorsBefore = Diags.getNumErrors();
  3868. // Parse the arguments.
  3869. const OptTable &Opts = getDriverOptTable();
  3870. const unsigned IncludedFlagsBitmask = options::CC1Option;
  3871. unsigned MissingArgIndex, MissingArgCount;
  3872. InputArgList Args = Opts.ParseArgs(CommandLineArgs, MissingArgIndex,
  3873. MissingArgCount, IncludedFlagsBitmask);
  3874. LangOptions &LangOpts = *Res.getLangOpts();
  3875. // Check for missing argument error.
  3876. if (MissingArgCount)
  3877. Diags.Report(diag::err_drv_missing_argument)
  3878. << Args.getArgString(MissingArgIndex) << MissingArgCount;
  3879. // Issue errors on unknown arguments.
  3880. for (const auto *A : Args.filtered(OPT_UNKNOWN)) {
  3881. auto ArgString = A->getAsString(Args);
  3882. std::string Nearest;
  3883. if (Opts.findNearest(ArgString, Nearest, IncludedFlagsBitmask) > 1)
  3884. Diags.Report(diag::err_drv_unknown_argument) << ArgString;
  3885. else
  3886. Diags.Report(diag::err_drv_unknown_argument_with_suggestion)
  3887. << ArgString << Nearest;
  3888. }
  3889. ParseFileSystemArgs(Res.getFileSystemOpts(), Args, Diags);
  3890. ParseMigratorArgs(Res.getMigratorOpts(), Args, Diags);
  3891. ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags);
  3892. ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags,
  3893. /*DefaultDiagColor=*/false);
  3894. ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags, LangOpts.IsHeaderFile);
  3895. // FIXME: We shouldn't have to pass the DashX option around here
  3896. InputKind DashX = Res.getFrontendOpts().DashX;
  3897. ParseTargetArgs(Res.getTargetOpts(), Args, Diags);
  3898. llvm::Triple T(Res.getTargetOpts().Triple);
  3899. ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args, Diags,
  3900. Res.getFileSystemOpts().WorkingDir);
  3901. ParseLangArgs(LangOpts, Args, DashX, T, Res.getPreprocessorOpts().Includes,
  3902. Diags);
  3903. if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
  3904. LangOpts.ObjCExceptions = 1;
  3905. if (LangOpts.CUDA) {
  3906. // During CUDA device-side compilation, the aux triple is the
  3907. // triple used for host compilation.
  3908. if (LangOpts.CUDAIsDevice)
  3909. Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
  3910. }
  3911. // Set the triple of the host for OpenMP device compile.
  3912. if (LangOpts.OpenMPIsDevice)
  3913. Res.getTargetOpts().HostTriple = Res.getFrontendOpts().AuxTriple;
  3914. ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, T,
  3915. Res.getFrontendOpts().OutputFile, LangOpts);
  3916. // FIXME: Override value name discarding when asan or msan is used because the
  3917. // backend passes depend on the name of the alloca in order to print out
  3918. // names.
  3919. Res.getCodeGenOpts().DiscardValueNames &=
  3920. !LangOpts.Sanitize.has(SanitizerKind::Address) &&
  3921. !LangOpts.Sanitize.has(SanitizerKind::KernelAddress) &&
  3922. !LangOpts.Sanitize.has(SanitizerKind::Memory) &&
  3923. !LangOpts.Sanitize.has(SanitizerKind::KernelMemory);
  3924. ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, Diags,
  3925. Res.getFrontendOpts().ProgramAction,
  3926. Res.getFrontendOpts());
  3927. ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, Diags,
  3928. Res.getFrontendOpts().ProgramAction);
  3929. ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args, Diags,
  3930. Res.getFrontendOpts().ProgramAction,
  3931. Res.getPreprocessorOutputOpts().ShowLineMarkers);
  3932. if (!Res.getDependencyOutputOpts().OutputFile.empty() &&
  3933. Res.getDependencyOutputOpts().Targets.empty())
  3934. Diags.Report(diag::err_fe_dependency_file_requires_MT);
  3935. // If sanitizer is enabled, disable OPT_ffine_grained_bitfield_accesses.
  3936. if (Res.getCodeGenOpts().FineGrainedBitfieldAccesses &&
  3937. !Res.getLangOpts()->Sanitize.empty()) {
  3938. Res.getCodeGenOpts().FineGrainedBitfieldAccesses = false;
  3939. Diags.Report(diag::warn_drv_fine_grained_bitfield_accesses_ignored);
  3940. }
  3941. // Store the command-line for using in the CodeView backend.
  3942. Res.getCodeGenOpts().Argv0 = Argv0;
  3943. append_range(Res.getCodeGenOpts().CommandLineArgs, CommandLineArgs);
  3944. FixupInvocation(Res, Diags, Args, DashX);
  3945. return Diags.getNumErrors() == NumErrorsBefore;
  3946. }
  3947. bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Invocation,
  3948. ArrayRef<const char *> CommandLineArgs,
  3949. DiagnosticsEngine &Diags,
  3950. const char *Argv0) {
  3951. CompilerInvocation DummyInvocation;
  3952. return RoundTrip(
  3953. [](CompilerInvocation &Invocation, ArrayRef<const char *> CommandLineArgs,
  3954. DiagnosticsEngine &Diags, const char *Argv0) {
  3955. return CreateFromArgsImpl(Invocation, CommandLineArgs, Diags, Argv0);
  3956. },
  3957. [](CompilerInvocation &Invocation, SmallVectorImpl<const char *> &Args,
  3958. StringAllocator SA) { Invocation.generateCC1CommandLine(Args, SA); },
  3959. Invocation, DummyInvocation, CommandLineArgs, Diags, Argv0);
  3960. }
  3961. std::string CompilerInvocation::getModuleHash() const {
  3962. // FIXME: Consider using SHA1 instead of MD5.
  3963. llvm::HashBuilder<llvm::MD5, llvm::support::endianness::native> HBuilder;
  3964. // Note: For QoI reasons, the things we use as a hash here should all be
  3965. // dumped via the -module-info flag.
  3966. // Start the signature with the compiler version.
  3967. HBuilder.add(getClangFullRepositoryVersion());
  3968. // Also include the serialization version, in case LLVM_APPEND_VC_REV is off
  3969. // and getClangFullRepositoryVersion() doesn't include git revision.
  3970. HBuilder.add(serialization::VERSION_MAJOR, serialization::VERSION_MINOR);
  3971. // Extend the signature with the language options
  3972. #define LANGOPT(Name, Bits, Default, Description) HBuilder.add(LangOpts->Name);
  3973. #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
  3974. HBuilder.add(static_cast<unsigned>(LangOpts->get##Name()));
  3975. #define BENIGN_LANGOPT(Name, Bits, Default, Description)
  3976. #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
  3977. #include "clang/Basic/LangOptions.def"
  3978. HBuilder.addRange(LangOpts->ModuleFeatures);
  3979. HBuilder.add(LangOpts->ObjCRuntime);
  3980. HBuilder.addRange(LangOpts->CommentOpts.BlockCommandNames);
  3981. // Extend the signature with the target options.
  3982. HBuilder.add(TargetOpts->Triple, TargetOpts->CPU, TargetOpts->TuneCPU,
  3983. TargetOpts->ABI);
  3984. HBuilder.addRange(TargetOpts->FeaturesAsWritten);
  3985. // Extend the signature with preprocessor options.
  3986. const PreprocessorOptions &ppOpts = getPreprocessorOpts();
  3987. HBuilder.add(ppOpts.UsePredefines, ppOpts.DetailedRecord);
  3988. const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
  3989. for (const auto &Macro : getPreprocessorOpts().Macros) {
  3990. // If we're supposed to ignore this macro for the purposes of modules,
  3991. // don't put it into the hash.
  3992. if (!hsOpts.ModulesIgnoreMacros.empty()) {
  3993. // Check whether we're ignoring this macro.
  3994. StringRef MacroDef = Macro.first;
  3995. if (hsOpts.ModulesIgnoreMacros.count(
  3996. llvm::CachedHashString(MacroDef.split('=').first)))
  3997. continue;
  3998. }
  3999. HBuilder.add(Macro);
  4000. }
  4001. // Extend the signature with the sysroot and other header search options.
  4002. HBuilder.add(hsOpts.Sysroot, hsOpts.ModuleFormat, hsOpts.UseDebugInfo,
  4003. hsOpts.UseBuiltinIncludes, hsOpts.UseStandardSystemIncludes,
  4004. hsOpts.UseStandardCXXIncludes, hsOpts.UseLibcxx,
  4005. hsOpts.ModulesValidateDiagnosticOptions);
  4006. HBuilder.add(hsOpts.ResourceDir);
  4007. if (hsOpts.ModulesStrictContextHash) {
  4008. HBuilder.addRange(hsOpts.SystemHeaderPrefixes);
  4009. HBuilder.addRange(hsOpts.UserEntries);
  4010. const DiagnosticOptions &diagOpts = getDiagnosticOpts();
  4011. #define DIAGOPT(Name, Bits, Default) HBuilder.add(diagOpts.Name);
  4012. #define ENUM_DIAGOPT(Name, Type, Bits, Default) \
  4013. HBuilder.add(diagOpts.get##Name());
  4014. #include "clang/Basic/DiagnosticOptions.def"
  4015. #undef DIAGOPT
  4016. #undef ENUM_DIAGOPT
  4017. }
  4018. // Extend the signature with the user build path.
  4019. HBuilder.add(hsOpts.ModuleUserBuildPath);
  4020. // Extend the signature with the module file extensions.
  4021. for (const auto &ext : getFrontendOpts().ModuleFileExtensions)
  4022. ext->hashExtension(HBuilder);
  4023. // When compiling with -gmodules, also hash -fdebug-prefix-map as it
  4024. // affects the debug info in the PCM.
  4025. if (getCodeGenOpts().DebugTypeExtRefs)
  4026. HBuilder.addRange(getCodeGenOpts().DebugPrefixMap);
  4027. // Extend the signature with the enabled sanitizers, if at least one is
  4028. // enabled. Sanitizers which cannot affect AST generation aren't hashed.
  4029. SanitizerSet SanHash = LangOpts->Sanitize;
  4030. SanHash.clear(getPPTransparentSanitizers());
  4031. if (!SanHash.empty())
  4032. HBuilder.add(SanHash.Mask);
  4033. llvm::MD5::MD5Result Result;
  4034. HBuilder.getHasher().final(Result);
  4035. uint64_t Hash = Result.high() ^ Result.low();
  4036. return toString(llvm::APInt(64, Hash), 36, /*Signed=*/false);
  4037. }
  4038. void CompilerInvocation::generateCC1CommandLine(
  4039. SmallVectorImpl<const char *> &Args, StringAllocator SA) const {
  4040. llvm::Triple T(TargetOpts->Triple);
  4041. GenerateFileSystemArgs(FileSystemOpts, Args, SA);
  4042. GenerateMigratorArgs(MigratorOpts, Args, SA);
  4043. GenerateAnalyzerArgs(*AnalyzerOpts, Args, SA);
  4044. GenerateDiagnosticArgs(*DiagnosticOpts, Args, SA, false);
  4045. GenerateFrontendArgs(FrontendOpts, Args, SA, LangOpts->IsHeaderFile);
  4046. GenerateTargetArgs(*TargetOpts, Args, SA);
  4047. GenerateHeaderSearchArgs(*HeaderSearchOpts, Args, SA);
  4048. GenerateLangArgs(*LangOpts, Args, SA, T, FrontendOpts.DashX);
  4049. GenerateCodeGenArgs(CodeGenOpts, Args, SA, T, FrontendOpts.OutputFile,
  4050. &*LangOpts);
  4051. GeneratePreprocessorArgs(*PreprocessorOpts, Args, SA, *LangOpts, FrontendOpts,
  4052. CodeGenOpts);
  4053. GeneratePreprocessorOutputArgs(PreprocessorOutputOpts, Args, SA,
  4054. FrontendOpts.ProgramAction);
  4055. GenerateDependencyOutputArgs(DependencyOutputOpts, Args, SA);
  4056. }
  4057. IntrusiveRefCntPtr<llvm::vfs::FileSystem>
  4058. clang::createVFSFromCompilerInvocationOrig(const CompilerInvocation &CI,
  4059. DiagnosticsEngine &Diags) {
  4060. return createVFSFromCompilerInvocation(CI, Diags,
  4061. llvm::vfs::getRealFileSystem());
  4062. }
  4063. IntrusiveRefCntPtr<llvm::vfs::FileSystem>
  4064. clang::createVFSFromCompilerInvocation(
  4065. const CompilerInvocation &CI, DiagnosticsEngine &Diags,
  4066. IntrusiveRefCntPtr<llvm::vfs::FileSystem> BaseFS) {
  4067. if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
  4068. return BaseFS;
  4069. IntrusiveRefCntPtr<llvm::vfs::FileSystem> Result = BaseFS;
  4070. // earlier vfs files are on the bottom
  4071. for (const auto &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
  4072. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
  4073. Result->getBufferForFile(File);
  4074. if (!Buffer) {
  4075. Diags.Report(diag::err_missing_vfs_overlay_file) << File;
  4076. continue;
  4077. }
  4078. IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = llvm::vfs::getVFSFromYAML(
  4079. std::move(Buffer.get()), /*DiagHandler*/ nullptr, File,
  4080. /*DiagContext*/ nullptr, Result);
  4081. if (!FS) {
  4082. Diags.Report(diag::err_invalid_vfs_overlay) << File;
  4083. continue;
  4084. }
  4085. Result = FS;
  4086. }
  4087. return Result;
  4088. }
  4089. IntrusiveRefCntPtr<llvm::vfs::FileSystem>
  4090. clang::createVFSFromCompilerInvocation(const CompilerInvocation &CI,
  4091. DiagnosticsEngine &Diags) {
  4092. IntrusiveRefCntPtr<llvm::vfs::FileSystem> FS = clang::createVFSFromCompilerInvocationOrig(CI, Diags);
  4093. if (!CI.getHeaderSearchOpts().CaseInsensitive) {
  4094. return FS;
  4095. } else {
  4096. return new llvm::vfs::CaseInsensitiveFileSystem(FS);
  4097. }
  4098. }