CompilerInvocation.cpp 192 KB

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