Driver.cpp 152 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047
  1. //===--- Driver.cpp - Clang GCC Compatible Driver -------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "clang/Driver/Driver.h"
  10. #include "InputInfo.h"
  11. #include "ToolChains/AMDGPU.h"
  12. #include "ToolChains/AVR.h"
  13. #include "ToolChains/Ananas.h"
  14. #include "ToolChains/Clang.h"
  15. #include "ToolChains/CloudABI.h"
  16. #include "ToolChains/Contiki.h"
  17. #include "ToolChains/CrossWindows.h"
  18. #include "ToolChains/Cuda.h"
  19. #include "ToolChains/Darwin.h"
  20. #include "ToolChains/DragonFly.h"
  21. #include "ToolChains/FreeBSD.h"
  22. #include "ToolChains/Fuchsia.h"
  23. #include "ToolChains/Gnu.h"
  24. #include "ToolChains/BareMetal.h"
  25. #include "ToolChains/Haiku.h"
  26. #include "ToolChains/Hexagon.h"
  27. #include "ToolChains/Lanai.h"
  28. #include "ToolChains/Linux.h"
  29. #include "ToolChains/MinGW.h"
  30. #include "ToolChains/Minix.h"
  31. #include "ToolChains/MipsLinux.h"
  32. #include "ToolChains/MSVC.h"
  33. #include "ToolChains/Myriad.h"
  34. #include "ToolChains/NaCl.h"
  35. #include "ToolChains/NetBSD.h"
  36. #include "ToolChains/OpenBSD.h"
  37. #include "ToolChains/PS4CPU.h"
  38. #include "ToolChains/Solaris.h"
  39. #include "ToolChains/TCE.h"
  40. #include "ToolChains/WebAssembly.h"
  41. #include "ToolChains/XCore.h"
  42. #include "clang/Basic/Version.h"
  43. #include "clang/Basic/VirtualFileSystem.h"
  44. #include "clang/Config/config.h"
  45. #include "clang/Driver/Action.h"
  46. #include "clang/Driver/Compilation.h"
  47. #include "clang/Driver/DriverDiagnostic.h"
  48. #include "clang/Driver/Job.h"
  49. #include "clang/Driver/Options.h"
  50. #include "clang/Driver/SanitizerArgs.h"
  51. #include "clang/Driver/Tool.h"
  52. #include "clang/Driver/ToolChain.h"
  53. #include "llvm/ADT/ArrayRef.h"
  54. #include "llvm/ADT/STLExtras.h"
  55. #include "llvm/ADT/SmallSet.h"
  56. #include "llvm/ADT/StringExtras.h"
  57. #include "llvm/ADT/StringSet.h"
  58. #include "llvm/ADT/StringSwitch.h"
  59. #include "llvm/Option/Arg.h"
  60. #include "llvm/Option/ArgList.h"
  61. #include "llvm/Option/OptSpecifier.h"
  62. #include "llvm/Option/OptTable.h"
  63. #include "llvm/Option/Option.h"
  64. #include "llvm/Support/ErrorHandling.h"
  65. #include "llvm/Support/FileSystem.h"
  66. #include "llvm/Support/Path.h"
  67. #include "llvm/Support/PrettyStackTrace.h"
  68. #include "llvm/Support/Process.h"
  69. #include "llvm/Support/Program.h"
  70. #include "llvm/Support/TargetRegistry.h"
  71. #include "llvm/Support/raw_ostream.h"
  72. #include <map>
  73. #include <memory>
  74. #include <utility>
  75. #if LLVM_ON_UNIX
  76. #include <unistd.h> // getpid
  77. #endif
  78. using namespace clang::driver;
  79. using namespace clang;
  80. using namespace llvm::opt;
  81. Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
  82. DiagnosticsEngine &Diags,
  83. IntrusiveRefCntPtr<vfs::FileSystem> VFS)
  84. : Opts(createDriverOptTable()), Diags(Diags), VFS(std::move(VFS)),
  85. Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
  86. LTOMode(LTOK_None), ClangExecutable(ClangExecutable),
  87. SysRoot(DEFAULT_SYSROOT),
  88. DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
  89. CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
  90. CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
  91. CCGenDiagnostics(false), DefaultTargetTriple(DefaultTargetTriple),
  92. CCCGenericGCCName(""), CheckInputsExist(true), CCCUsePCH(true),
  93. GenReproducer(false), SuppressMissingInputWarning(false) {
  94. // Provide a sane fallback if no VFS is specified.
  95. if (!this->VFS)
  96. this->VFS = vfs::getRealFileSystem();
  97. Name = llvm::sys::path::filename(ClangExecutable);
  98. Dir = llvm::sys::path::parent_path(ClangExecutable);
  99. InstalledDir = Dir; // Provide a sensible default installed dir.
  100. // Compute the path to the resource directory.
  101. StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
  102. SmallString<128> P(Dir);
  103. if (ClangResourceDir != "") {
  104. llvm::sys::path::append(P, ClangResourceDir);
  105. } else {
  106. StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
  107. P = llvm::sys::path::parent_path(Dir);
  108. llvm::sys::path::append(P, Twine("lib") + ClangLibdirSuffix, "clang",
  109. CLANG_VERSION_STRING);
  110. }
  111. ResourceDir = P.str();
  112. }
  113. void Driver::ParseDriverMode(StringRef ProgramName,
  114. ArrayRef<const char *> Args) {
  115. ClangNameParts = ToolChain::getTargetAndModeFromProgramName(ProgramName);
  116. setDriverModeFromOption(ClangNameParts.DriverMode);
  117. for (const char *ArgPtr : Args) {
  118. // Ingore nullptrs, they are response file's EOL markers
  119. if (ArgPtr == nullptr)
  120. continue;
  121. const StringRef Arg = ArgPtr;
  122. setDriverModeFromOption(Arg);
  123. }
  124. }
  125. void Driver::setDriverModeFromOption(StringRef Opt) {
  126. const std::string OptName =
  127. getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
  128. if (!Opt.startswith(OptName))
  129. return;
  130. StringRef Value = Opt.drop_front(OptName.size());
  131. const unsigned M = llvm::StringSwitch<unsigned>(Value)
  132. .Case("gcc", GCCMode)
  133. .Case("g++", GXXMode)
  134. .Case("cpp", CPPMode)
  135. .Case("cl", CLMode)
  136. .Default(~0U);
  137. if (M != ~0U)
  138. Mode = static_cast<DriverMode>(M);
  139. else
  140. Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
  141. }
  142. InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings,
  143. bool &ContainsError) {
  144. llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
  145. ContainsError = false;
  146. unsigned IncludedFlagsBitmask;
  147. unsigned ExcludedFlagsBitmask;
  148. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  149. getIncludeExcludeOptionFlagMasks();
  150. unsigned MissingArgIndex, MissingArgCount;
  151. InputArgList Args =
  152. getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
  153. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  154. // Check for missing argument error.
  155. if (MissingArgCount) {
  156. Diag(diag::err_drv_missing_argument)
  157. << Args.getArgString(MissingArgIndex) << MissingArgCount;
  158. ContainsError |=
  159. Diags.getDiagnosticLevel(diag::err_drv_missing_argument,
  160. SourceLocation()) > DiagnosticsEngine::Warning;
  161. }
  162. // Check for unsupported options.
  163. for (const Arg *A : Args) {
  164. if (A->getOption().hasFlag(options::Unsupported)) {
  165. Diag(diag::err_drv_unsupported_opt) << A->getAsString(Args);
  166. ContainsError |= Diags.getDiagnosticLevel(diag::err_drv_unsupported_opt,
  167. SourceLocation()) >
  168. DiagnosticsEngine::Warning;
  169. continue;
  170. }
  171. // Warn about -mcpu= without an argument.
  172. if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
  173. Diag(diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
  174. ContainsError |= Diags.getDiagnosticLevel(
  175. diag::warn_drv_empty_joined_argument,
  176. SourceLocation()) > DiagnosticsEngine::Warning;
  177. }
  178. }
  179. for (const Arg *A : Args.filtered(options::OPT_UNKNOWN)) {
  180. auto ID = IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl
  181. : diag::err_drv_unknown_argument;
  182. Diags.Report(ID) << A->getAsString(Args);
  183. ContainsError |= Diags.getDiagnosticLevel(ID, SourceLocation()) >
  184. DiagnosticsEngine::Warning;
  185. }
  186. return Args;
  187. }
  188. // Determine which compilation mode we are in. We look for options which
  189. // affect the phase, starting with the earliest phases, and record which
  190. // option we used to determine the final phase.
  191. phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
  192. Arg **FinalPhaseArg) const {
  193. Arg *PhaseArg = nullptr;
  194. phases::ID FinalPhase;
  195. // -{E,EP,P,M,MM} only run the preprocessor.
  196. if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
  197. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
  198. (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
  199. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
  200. FinalPhase = phases::Preprocess;
  201. // --precompile only runs up to precompilation.
  202. } else if ((PhaseArg = DAL.getLastArg(options::OPT__precompile))) {
  203. FinalPhase = phases::Precompile;
  204. // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
  205. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
  206. (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
  207. (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
  208. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
  209. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
  210. (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
  211. (PhaseArg = DAL.getLastArg(options::OPT__analyze,
  212. options::OPT__analyze_auto)) ||
  213. (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
  214. FinalPhase = phases::Compile;
  215. // -S only runs up to the backend.
  216. } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
  217. FinalPhase = phases::Backend;
  218. // -c compilation only runs up to the assembler.
  219. } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
  220. FinalPhase = phases::Assemble;
  221. // Otherwise do everything.
  222. } else
  223. FinalPhase = phases::Link;
  224. if (FinalPhaseArg)
  225. *FinalPhaseArg = PhaseArg;
  226. return FinalPhase;
  227. }
  228. static Arg *MakeInputArg(DerivedArgList &Args, OptTable &Opts,
  229. StringRef Value) {
  230. Arg *A = new Arg(Opts.getOption(options::OPT_INPUT), Value,
  231. Args.getBaseArgs().MakeIndex(Value), Value.data());
  232. Args.AddSynthesizedArg(A);
  233. A->claim();
  234. return A;
  235. }
  236. DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
  237. DerivedArgList *DAL = new DerivedArgList(Args);
  238. bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
  239. bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
  240. for (Arg *A : Args) {
  241. // Unfortunately, we have to parse some forwarding options (-Xassembler,
  242. // -Xlinker, -Xpreprocessor) because we either integrate their functionality
  243. // (assembler and preprocessor), or bypass a previous driver ('collect2').
  244. // Rewrite linker options, to replace --no-demangle with a custom internal
  245. // option.
  246. if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
  247. A->getOption().matches(options::OPT_Xlinker)) &&
  248. A->containsValue("--no-demangle")) {
  249. // Add the rewritten no-demangle argument.
  250. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
  251. // Add the remaining values as Xlinker arguments.
  252. for (StringRef Val : A->getValues())
  253. if (Val != "--no-demangle")
  254. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
  255. continue;
  256. }
  257. // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
  258. // some build systems. We don't try to be complete here because we don't
  259. // care to encourage this usage model.
  260. if (A->getOption().matches(options::OPT_Wp_COMMA) &&
  261. (A->getValue(0) == StringRef("-MD") ||
  262. A->getValue(0) == StringRef("-MMD"))) {
  263. // Rewrite to -MD/-MMD along with -MF.
  264. if (A->getValue(0) == StringRef("-MD"))
  265. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
  266. else
  267. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
  268. if (A->getNumValues() == 2)
  269. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
  270. A->getValue(1));
  271. continue;
  272. }
  273. // Rewrite reserved library names.
  274. if (A->getOption().matches(options::OPT_l)) {
  275. StringRef Value = A->getValue();
  276. // Rewrite unless -nostdlib is present.
  277. if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
  278. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
  279. continue;
  280. }
  281. // Rewrite unconditionally.
  282. if (Value == "cc_kext") {
  283. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
  284. continue;
  285. }
  286. }
  287. // Pick up inputs via the -- option.
  288. if (A->getOption().matches(options::OPT__DASH_DASH)) {
  289. A->claim();
  290. for (StringRef Val : A->getValues())
  291. DAL->append(MakeInputArg(*DAL, *Opts, Val));
  292. continue;
  293. }
  294. DAL->append(A);
  295. }
  296. // Enforce -static if -miamcu is present.
  297. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false))
  298. DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
  299. // Add a default value of -mlinker-version=, if one was given and the user
  300. // didn't specify one.
  301. #if defined(HOST_LINK_VERSION)
  302. if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
  303. strlen(HOST_LINK_VERSION) > 0) {
  304. DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
  305. HOST_LINK_VERSION);
  306. DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
  307. }
  308. #endif
  309. return DAL;
  310. }
  311. /// \brief Compute target triple from args.
  312. ///
  313. /// This routine provides the logic to compute a target triple from various
  314. /// args passed to the driver and the default triple string.
  315. static llvm::Triple computeTargetTriple(const Driver &D,
  316. StringRef DefaultTargetTriple,
  317. const ArgList &Args,
  318. StringRef DarwinArchName = "") {
  319. // FIXME: Already done in Compilation *Driver::BuildCompilation
  320. if (const Arg *A = Args.getLastArg(options::OPT_target))
  321. DefaultTargetTriple = A->getValue();
  322. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  323. // Handle Apple-specific options available here.
  324. if (Target.isOSBinFormatMachO()) {
  325. // If an explict Darwin arch name is given, that trumps all.
  326. if (!DarwinArchName.empty()) {
  327. tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
  328. return Target;
  329. }
  330. // Handle the Darwin '-arch' flag.
  331. if (Arg *A = Args.getLastArg(options::OPT_arch)) {
  332. StringRef ArchName = A->getValue();
  333. tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
  334. }
  335. }
  336. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  337. // '-mbig-endian'/'-EB'.
  338. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  339. options::OPT_mbig_endian)) {
  340. if (A->getOption().matches(options::OPT_mlittle_endian)) {
  341. llvm::Triple LE = Target.getLittleEndianArchVariant();
  342. if (LE.getArch() != llvm::Triple::UnknownArch)
  343. Target = std::move(LE);
  344. } else {
  345. llvm::Triple BE = Target.getBigEndianArchVariant();
  346. if (BE.getArch() != llvm::Triple::UnknownArch)
  347. Target = std::move(BE);
  348. }
  349. }
  350. // Skip further flag support on OSes which don't support '-m32' or '-m64'.
  351. if (Target.getArch() == llvm::Triple::tce ||
  352. Target.getOS() == llvm::Triple::Minix)
  353. return Target;
  354. // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
  355. Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
  356. options::OPT_m32, options::OPT_m16);
  357. if (A) {
  358. llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
  359. if (A->getOption().matches(options::OPT_m64)) {
  360. AT = Target.get64BitArchVariant().getArch();
  361. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  362. Target.setEnvironment(llvm::Triple::GNU);
  363. } else if (A->getOption().matches(options::OPT_mx32) &&
  364. Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
  365. AT = llvm::Triple::x86_64;
  366. Target.setEnvironment(llvm::Triple::GNUX32);
  367. } else if (A->getOption().matches(options::OPT_m32)) {
  368. AT = Target.get32BitArchVariant().getArch();
  369. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  370. Target.setEnvironment(llvm::Triple::GNU);
  371. } else if (A->getOption().matches(options::OPT_m16) &&
  372. Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
  373. AT = llvm::Triple::x86;
  374. Target.setEnvironment(llvm::Triple::CODE16);
  375. }
  376. if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
  377. Target.setArch(AT);
  378. }
  379. // Handle -miamcu flag.
  380. if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
  381. if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
  382. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
  383. << Target.str();
  384. if (A && !A->getOption().matches(options::OPT_m32))
  385. D.Diag(diag::err_drv_argument_not_allowed_with)
  386. << "-miamcu" << A->getBaseArg().getAsString(Args);
  387. Target.setArch(llvm::Triple::x86);
  388. Target.setArchName("i586");
  389. Target.setEnvironment(llvm::Triple::UnknownEnvironment);
  390. Target.setEnvironmentName("");
  391. Target.setOS(llvm::Triple::ELFIAMCU);
  392. Target.setVendor(llvm::Triple::UnknownVendor);
  393. Target.setVendorName("intel");
  394. }
  395. return Target;
  396. }
  397. // \brief Parse the LTO options and record the type of LTO compilation
  398. // based on which -f(no-)?lto(=.*)? option occurs last.
  399. void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
  400. LTOMode = LTOK_None;
  401. if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
  402. options::OPT_fno_lto, false))
  403. return;
  404. StringRef LTOName("full");
  405. const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
  406. if (A)
  407. LTOName = A->getValue();
  408. LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
  409. .Case("full", LTOK_Full)
  410. .Case("thin", LTOK_Thin)
  411. .Default(LTOK_Unknown);
  412. if (LTOMode == LTOK_Unknown) {
  413. assert(A);
  414. Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
  415. << A->getValue();
  416. }
  417. }
  418. /// Compute the desired OpenMP runtime from the flags provided.
  419. Driver::OpenMPRuntimeKind Driver::getOpenMPRuntime(const ArgList &Args) const {
  420. StringRef RuntimeName(CLANG_DEFAULT_OPENMP_RUNTIME);
  421. const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ);
  422. if (A)
  423. RuntimeName = A->getValue();
  424. auto RT = llvm::StringSwitch<OpenMPRuntimeKind>(RuntimeName)
  425. .Case("libomp", OMPRT_OMP)
  426. .Case("libgomp", OMPRT_GOMP)
  427. .Case("libiomp5", OMPRT_IOMP5)
  428. .Default(OMPRT_Unknown);
  429. if (RT == OMPRT_Unknown) {
  430. if (A)
  431. Diag(diag::err_drv_unsupported_option_argument)
  432. << A->getOption().getName() << A->getValue();
  433. else
  434. // FIXME: We could use a nicer diagnostic here.
  435. Diag(diag::err_drv_unsupported_opt) << "-fopenmp";
  436. }
  437. return RT;
  438. }
  439. void Driver::CreateOffloadingDeviceToolChains(Compilation &C,
  440. InputList &Inputs) {
  441. //
  442. // CUDA
  443. //
  444. // We need to generate a CUDA toolchain if any of the inputs has a CUDA type.
  445. if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &I) {
  446. return types::isCuda(I.first);
  447. })) {
  448. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  449. const llvm::Triple &HostTriple = HostTC->getTriple();
  450. llvm::Triple CudaTriple(HostTriple.isArch64Bit() ? "nvptx64-nvidia-cuda"
  451. : "nvptx-nvidia-cuda");
  452. // Use the CUDA and host triples as the key into the ToolChains map, because
  453. // the device toolchain we create depends on both.
  454. auto &CudaTC = ToolChains[CudaTriple.str() + "/" + HostTriple.str()];
  455. if (!CudaTC) {
  456. CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
  457. *this, CudaTriple, *HostTC, C.getInputArgs(), Action::OFK_Cuda);
  458. }
  459. C.addOffloadDeviceToolChain(CudaTC.get(), Action::OFK_Cuda);
  460. }
  461. //
  462. // OpenMP
  463. //
  464. // We need to generate an OpenMP toolchain if the user specified targets with
  465. // the -fopenmp-targets option.
  466. if (Arg *OpenMPTargets =
  467. C.getInputArgs().getLastArg(options::OPT_fopenmp_targets_EQ)) {
  468. if (OpenMPTargets->getNumValues()) {
  469. // We expect that -fopenmp-targets is always used in conjunction with the
  470. // option -fopenmp specifying a valid runtime with offloading support,
  471. // i.e. libomp or libiomp.
  472. bool HasValidOpenMPRuntime = C.getInputArgs().hasFlag(
  473. options::OPT_fopenmp, options::OPT_fopenmp_EQ,
  474. options::OPT_fno_openmp, false);
  475. if (HasValidOpenMPRuntime) {
  476. OpenMPRuntimeKind OpenMPKind = getOpenMPRuntime(C.getInputArgs());
  477. HasValidOpenMPRuntime =
  478. OpenMPKind == OMPRT_OMP || OpenMPKind == OMPRT_IOMP5;
  479. }
  480. if (HasValidOpenMPRuntime) {
  481. llvm::StringMap<const char *> FoundNormalizedTriples;
  482. for (const char *Val : OpenMPTargets->getValues()) {
  483. llvm::Triple TT(Val);
  484. std::string NormalizedName = TT.normalize();
  485. // Make sure we don't have a duplicate triple.
  486. auto Duplicate = FoundNormalizedTriples.find(NormalizedName);
  487. if (Duplicate != FoundNormalizedTriples.end()) {
  488. Diag(clang::diag::warn_drv_omp_offload_target_duplicate)
  489. << Val << Duplicate->second;
  490. continue;
  491. }
  492. // Store the current triple so that we can check for duplicates in the
  493. // following iterations.
  494. FoundNormalizedTriples[NormalizedName] = Val;
  495. // If the specified target is invalid, emit a diagnostic.
  496. if (TT.getArch() == llvm::Triple::UnknownArch)
  497. Diag(clang::diag::err_drv_invalid_omp_target) << Val;
  498. else {
  499. const ToolChain *TC;
  500. // CUDA toolchains have to be selected differently. They pair host
  501. // and device in their implementation.
  502. if (TT.isNVPTX()) {
  503. const ToolChain *HostTC =
  504. C.getSingleOffloadToolChain<Action::OFK_Host>();
  505. assert(HostTC && "Host toolchain should be always defined.");
  506. auto &CudaTC =
  507. ToolChains[TT.str() + "/" + HostTC->getTriple().normalize()];
  508. if (!CudaTC)
  509. CudaTC = llvm::make_unique<toolchains::CudaToolChain>(
  510. *this, TT, *HostTC, C.getInputArgs(), Action::OFK_OpenMP);
  511. TC = CudaTC.get();
  512. } else
  513. TC = &getToolChain(C.getInputArgs(), TT);
  514. C.addOffloadDeviceToolChain(TC, Action::OFK_OpenMP);
  515. }
  516. }
  517. } else
  518. Diag(clang::diag::err_drv_expecting_fopenmp_with_fopenmp_targets);
  519. } else
  520. Diag(clang::diag::warn_drv_empty_joined_argument)
  521. << OpenMPTargets->getAsString(C.getInputArgs());
  522. }
  523. //
  524. // TODO: Add support for other offloading programming models here.
  525. //
  526. return;
  527. }
  528. Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
  529. llvm::PrettyStackTraceString CrashInfo("Compilation construction");
  530. // FIXME: Handle environment options which affect driver behavior, somewhere
  531. // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
  532. if (Optional<std::string> CompilerPathValue =
  533. llvm::sys::Process::GetEnv("COMPILER_PATH")) {
  534. StringRef CompilerPath = *CompilerPathValue;
  535. while (!CompilerPath.empty()) {
  536. std::pair<StringRef, StringRef> Split =
  537. CompilerPath.split(llvm::sys::EnvPathSeparator);
  538. PrefixDirs.push_back(Split.first);
  539. CompilerPath = Split.second;
  540. }
  541. }
  542. // We look for the driver mode option early, because the mode can affect
  543. // how other options are parsed.
  544. ParseDriverMode(ClangExecutable, ArgList.slice(1));
  545. // FIXME: What are we going to do with -V and -b?
  546. // FIXME: This stuff needs to go into the Compilation, not the driver.
  547. bool CCCPrintPhases;
  548. bool ContainsError;
  549. InputArgList Args = ParseArgStrings(ArgList.slice(1), ContainsError);
  550. // Silence driver warnings if requested
  551. Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
  552. // -no-canonical-prefixes is used very early in main.
  553. Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
  554. // Ignore -pipe.
  555. Args.ClaimAllArgs(options::OPT_pipe);
  556. // Extract -ccc args.
  557. //
  558. // FIXME: We need to figure out where this behavior should live. Most of it
  559. // should be outside in the client; the parts that aren't should have proper
  560. // options, either by introducing new ones or by overloading gcc ones like -V
  561. // or -b.
  562. CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
  563. CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
  564. if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
  565. CCCGenericGCCName = A->getValue();
  566. CCCUsePCH =
  567. Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
  568. GenReproducer = Args.hasFlag(options::OPT_gen_reproducer,
  569. options::OPT_fno_crash_diagnostics,
  570. !!::getenv("FORCE_CLANG_DIAGNOSTICS_CRASH"));
  571. // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
  572. // and getToolChain is const.
  573. if (IsCLMode()) {
  574. // clang-cl targets MSVC-style Win32.
  575. llvm::Triple T(DefaultTargetTriple);
  576. T.setOS(llvm::Triple::Win32);
  577. T.setVendor(llvm::Triple::PC);
  578. T.setEnvironment(llvm::Triple::MSVC);
  579. T.setObjectFormat(llvm::Triple::COFF);
  580. DefaultTargetTriple = T.str();
  581. }
  582. if (const Arg *A = Args.getLastArg(options::OPT_target))
  583. DefaultTargetTriple = A->getValue();
  584. if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
  585. Dir = InstalledDir = A->getValue();
  586. for (const Arg *A : Args.filtered(options::OPT_B)) {
  587. A->claim();
  588. PrefixDirs.push_back(A->getValue(0));
  589. }
  590. if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
  591. SysRoot = A->getValue();
  592. if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
  593. DyldPrefix = A->getValue();
  594. if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
  595. ResourceDir = A->getValue();
  596. if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
  597. SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
  598. .Case("cwd", SaveTempsCwd)
  599. .Case("obj", SaveTempsObj)
  600. .Default(SaveTempsCwd);
  601. }
  602. setLTOMode(Args);
  603. // Process -fembed-bitcode= flags.
  604. if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
  605. StringRef Name = A->getValue();
  606. unsigned Model = llvm::StringSwitch<unsigned>(Name)
  607. .Case("off", EmbedNone)
  608. .Case("all", EmbedBitcode)
  609. .Case("bitcode", EmbedBitcode)
  610. .Case("marker", EmbedMarker)
  611. .Default(~0U);
  612. if (Model == ~0U) {
  613. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
  614. << Name;
  615. } else
  616. BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
  617. }
  618. std::unique_ptr<llvm::opt::InputArgList> UArgs =
  619. llvm::make_unique<InputArgList>(std::move(Args));
  620. // Perform the default argument translations.
  621. DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
  622. // Owned by the host.
  623. const ToolChain &TC = getToolChain(
  624. *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
  625. // The compilation takes ownership of Args.
  626. Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs,
  627. ContainsError);
  628. if (!HandleImmediateArgs(*C))
  629. return C;
  630. // Construct the list of inputs.
  631. InputList Inputs;
  632. BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
  633. // Populate the tool chains for the offloading devices, if any.
  634. CreateOffloadingDeviceToolChains(*C, Inputs);
  635. // Construct the list of abstract actions to perform for this compilation. On
  636. // MachO targets this uses the driver-driver and universal actions.
  637. if (TC.getTriple().isOSBinFormatMachO())
  638. BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
  639. else
  640. BuildActions(*C, C->getArgs(), Inputs, C->getActions());
  641. if (CCCPrintPhases) {
  642. PrintActions(*C);
  643. return C;
  644. }
  645. BuildJobs(*C);
  646. return C;
  647. }
  648. static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
  649. llvm::opt::ArgStringList ASL;
  650. for (const auto *A : Args)
  651. A->render(Args, ASL);
  652. for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
  653. if (I != ASL.begin())
  654. OS << ' ';
  655. Command::printArg(OS, *I, true);
  656. }
  657. OS << '\n';
  658. }
  659. bool Driver::getCrashDiagnosticFile(StringRef ReproCrashFilename,
  660. SmallString<128> &CrashDiagDir) {
  661. using namespace llvm::sys;
  662. assert(llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin() &&
  663. "Only knows about .crash files on Darwin");
  664. // The .crash file can be found on at ~/Library/Logs/DiagnosticReports/
  665. // (or /Library/Logs/DiagnosticReports for root) and has the filename pattern
  666. // clang-<VERSION>_<YYYY-MM-DD-HHMMSS>_<hostname>.crash.
  667. path::home_directory(CrashDiagDir);
  668. if (CrashDiagDir.startswith("/var/root"))
  669. CrashDiagDir = "/";
  670. path::append(CrashDiagDir, "Library/Logs/DiagnosticReports");
  671. int PID =
  672. #if LLVM_ON_UNIX
  673. getpid();
  674. #else
  675. 0;
  676. #endif
  677. std::error_code EC;
  678. fs::file_status FileStatus;
  679. TimePoint<> LastAccessTime;
  680. SmallString<128> CrashFilePath;
  681. // Lookup the .crash files and get the one generated by a subprocess spawned
  682. // by this driver invocation.
  683. for (fs::directory_iterator File(CrashDiagDir, EC), FileEnd;
  684. File != FileEnd && !EC; File.increment(EC)) {
  685. StringRef FileName = path::filename(File->path());
  686. if (!FileName.startswith(Name))
  687. continue;
  688. if (fs::status(File->path(), FileStatus))
  689. continue;
  690. llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> CrashFile =
  691. llvm::MemoryBuffer::getFile(File->path());
  692. if (!CrashFile)
  693. continue;
  694. // The first line should start with "Process:", otherwise this isn't a real
  695. // .crash file.
  696. StringRef Data = CrashFile.get()->getBuffer();
  697. if (!Data.startswith("Process:"))
  698. continue;
  699. // Parse parent process pid line, e.g: "Parent Process: clang-4.0 [79141]"
  700. size_t ParentProcPos = Data.find("Parent Process:");
  701. if (ParentProcPos == StringRef::npos)
  702. continue;
  703. size_t LineEnd = Data.find_first_of("\n", ParentProcPos);
  704. if (LineEnd == StringRef::npos)
  705. continue;
  706. StringRef ParentProcess = Data.slice(ParentProcPos+15, LineEnd).trim();
  707. int OpenBracket = -1, CloseBracket = -1;
  708. for (size_t i = 0, e = ParentProcess.size(); i < e; ++i) {
  709. if (ParentProcess[i] == '[')
  710. OpenBracket = i;
  711. if (ParentProcess[i] == ']')
  712. CloseBracket = i;
  713. }
  714. // Extract the parent process PID from the .crash file and check whether
  715. // it matches this driver invocation pid.
  716. int CrashPID;
  717. if (OpenBracket < 0 || CloseBracket < 0 ||
  718. ParentProcess.slice(OpenBracket + 1, CloseBracket)
  719. .getAsInteger(10, CrashPID) || CrashPID != PID) {
  720. continue;
  721. }
  722. // Found a .crash file matching the driver pid. To avoid getting an older
  723. // and misleading crash file, continue looking for the most recent.
  724. // FIXME: the driver can dispatch multiple cc1 invocations, leading to
  725. // multiple crashes poiting to the same parent process. Since the driver
  726. // does not collect pid information for the dispatched invocation there's
  727. // currently no way to distinguish among them.
  728. const auto FileAccessTime = FileStatus.getLastModificationTime();
  729. if (FileAccessTime > LastAccessTime) {
  730. CrashFilePath.assign(File->path());
  731. LastAccessTime = FileAccessTime;
  732. }
  733. }
  734. // If found, copy it over to the location of other reproducer files.
  735. if (!CrashFilePath.empty()) {
  736. EC = fs::copy_file(CrashFilePath, ReproCrashFilename);
  737. if (EC)
  738. return false;
  739. return true;
  740. }
  741. return false;
  742. }
  743. // When clang crashes, produce diagnostic information including the fully
  744. // preprocessed source file(s). Request that the developer attach the
  745. // diagnostic information to a bug report.
  746. void Driver::generateCompilationDiagnostics(Compilation &C,
  747. const Command &FailingCommand) {
  748. if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
  749. return;
  750. // Don't try to generate diagnostics for link or dsymutil jobs.
  751. if (FailingCommand.getCreator().isLinkJob() ||
  752. FailingCommand.getCreator().isDsymutilJob())
  753. return;
  754. // Print the version of the compiler.
  755. PrintVersion(C, llvm::errs());
  756. Diag(clang::diag::note_drv_command_failed_diag_msg)
  757. << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
  758. "crash backtrace, preprocessed source, and associated run script.";
  759. // Suppress driver output and emit preprocessor output to temp file.
  760. Mode = CPPMode;
  761. CCGenDiagnostics = true;
  762. // Save the original job command(s).
  763. Command Cmd = FailingCommand;
  764. // Keep track of whether we produce any errors while trying to produce
  765. // preprocessed sources.
  766. DiagnosticErrorTrap Trap(Diags);
  767. // Suppress tool output.
  768. C.initCompilationForDiagnostics();
  769. // Construct the list of inputs.
  770. InputList Inputs;
  771. BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
  772. for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
  773. bool IgnoreInput = false;
  774. // Ignore input from stdin or any inputs that cannot be preprocessed.
  775. // Check type first as not all linker inputs have a value.
  776. if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
  777. IgnoreInput = true;
  778. } else if (!strcmp(it->second->getValue(), "-")) {
  779. Diag(clang::diag::note_drv_command_failed_diag_msg)
  780. << "Error generating preprocessed source(s) - "
  781. "ignoring input from stdin.";
  782. IgnoreInput = true;
  783. }
  784. if (IgnoreInput) {
  785. it = Inputs.erase(it);
  786. ie = Inputs.end();
  787. } else {
  788. ++it;
  789. }
  790. }
  791. if (Inputs.empty()) {
  792. Diag(clang::diag::note_drv_command_failed_diag_msg)
  793. << "Error generating preprocessed source(s) - "
  794. "no preprocessable inputs.";
  795. return;
  796. }
  797. // Don't attempt to generate preprocessed files if multiple -arch options are
  798. // used, unless they're all duplicates.
  799. llvm::StringSet<> ArchNames;
  800. for (const Arg *A : C.getArgs()) {
  801. if (A->getOption().matches(options::OPT_arch)) {
  802. StringRef ArchName = A->getValue();
  803. ArchNames.insert(ArchName);
  804. }
  805. }
  806. if (ArchNames.size() > 1) {
  807. Diag(clang::diag::note_drv_command_failed_diag_msg)
  808. << "Error generating preprocessed source(s) - cannot generate "
  809. "preprocessed source with multiple -arch options.";
  810. return;
  811. }
  812. // Construct the list of abstract actions to perform for this compilation. On
  813. // Darwin OSes this uses the driver-driver and builds universal actions.
  814. const ToolChain &TC = C.getDefaultToolChain();
  815. if (TC.getTriple().isOSBinFormatMachO())
  816. BuildUniversalActions(C, TC, Inputs);
  817. else
  818. BuildActions(C, C.getArgs(), Inputs, C.getActions());
  819. BuildJobs(C);
  820. // If there were errors building the compilation, quit now.
  821. if (Trap.hasErrorOccurred()) {
  822. Diag(clang::diag::note_drv_command_failed_diag_msg)
  823. << "Error generating preprocessed source(s).";
  824. return;
  825. }
  826. // Generate preprocessed output.
  827. SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
  828. C.ExecuteJobs(C.getJobs(), FailingCommands);
  829. // If any of the preprocessing commands failed, clean up and exit.
  830. if (!FailingCommands.empty()) {
  831. if (!isSaveTempsEnabled())
  832. C.CleanupFileList(C.getTempFiles(), true);
  833. Diag(clang::diag::note_drv_command_failed_diag_msg)
  834. << "Error generating preprocessed source(s).";
  835. return;
  836. }
  837. const ArgStringList &TempFiles = C.getTempFiles();
  838. if (TempFiles.empty()) {
  839. Diag(clang::diag::note_drv_command_failed_diag_msg)
  840. << "Error generating preprocessed source(s).";
  841. return;
  842. }
  843. Diag(clang::diag::note_drv_command_failed_diag_msg)
  844. << "\n********************\n\n"
  845. "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
  846. "Preprocessed source(s) and associated run script(s) are located at:";
  847. SmallString<128> VFS;
  848. SmallString<128> ReproCrashFilename;
  849. for (const char *TempFile : TempFiles) {
  850. Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
  851. if (ReproCrashFilename.empty()) {
  852. ReproCrashFilename = TempFile;
  853. llvm::sys::path::replace_extension(ReproCrashFilename, ".crash");
  854. }
  855. if (StringRef(TempFile).endswith(".cache")) {
  856. // In some cases (modules) we'll dump extra data to help with reproducing
  857. // the crash into a directory next to the output.
  858. VFS = llvm::sys::path::filename(TempFile);
  859. llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
  860. }
  861. }
  862. // Assume associated files are based off of the first temporary file.
  863. CrashReportInfo CrashInfo(TempFiles[0], VFS);
  864. std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
  865. std::error_code EC;
  866. llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
  867. if (EC) {
  868. Diag(clang::diag::note_drv_command_failed_diag_msg)
  869. << "Error generating run script: " + Script + " " + EC.message();
  870. } else {
  871. ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
  872. << "# Driver args: ";
  873. printArgList(ScriptOS, C.getInputArgs());
  874. ScriptOS << "# Original command: ";
  875. Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
  876. Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
  877. Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
  878. }
  879. // On darwin, provide information about the .crash diagnostic report.
  880. if (llvm::Triple(llvm::sys::getProcessTriple()).isOSDarwin()) {
  881. SmallString<128> CrashDiagDir;
  882. if (getCrashDiagnosticFile(ReproCrashFilename, CrashDiagDir)) {
  883. Diag(clang::diag::note_drv_command_failed_diag_msg)
  884. << ReproCrashFilename.str();
  885. } else { // Suggest a directory for the user to look for .crash files.
  886. llvm::sys::path::append(CrashDiagDir, Name);
  887. CrashDiagDir += "_<YYYY-MM-DD-HHMMSS>_<hostname>.crash";
  888. Diag(clang::diag::note_drv_command_failed_diag_msg)
  889. << "Crash backtrace is located in";
  890. Diag(clang::diag::note_drv_command_failed_diag_msg)
  891. << CrashDiagDir.str();
  892. Diag(clang::diag::note_drv_command_failed_diag_msg)
  893. << "(choose the .crash file that corresponds to your crash)";
  894. }
  895. }
  896. for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
  897. options::OPT_frewrite_map_file_EQ))
  898. Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
  899. Diag(clang::diag::note_drv_command_failed_diag_msg)
  900. << "\n\n********************";
  901. }
  902. void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
  903. // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
  904. // if the tool does not support response files, there is a chance/ that things
  905. // will just work without a response file, so we silently just skip it.
  906. if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
  907. llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
  908. return;
  909. std::string TmpName = GetTemporaryPath("response", "txt");
  910. Cmd.setResponseFile(C.addTempFile(C.getArgs().MakeArgString(TmpName)));
  911. }
  912. int Driver::ExecuteCompilation(
  913. Compilation &C,
  914. SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
  915. // Just print if -### was present.
  916. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  917. C.getJobs().Print(llvm::errs(), "\n", true);
  918. return 0;
  919. }
  920. // If there were errors building the compilation, quit now.
  921. if (Diags.hasErrorOccurred())
  922. return 1;
  923. // Set up response file names for each command, if necessary
  924. for (auto &Job : C.getJobs())
  925. setUpResponseFiles(C, Job);
  926. C.ExecuteJobs(C.getJobs(), FailingCommands);
  927. // Remove temp files.
  928. C.CleanupFileList(C.getTempFiles());
  929. // If the command succeeded, we are done.
  930. if (FailingCommands.empty())
  931. return 0;
  932. // Otherwise, remove result files and print extra information about abnormal
  933. // failures.
  934. for (const auto &CmdPair : FailingCommands) {
  935. int Res = CmdPair.first;
  936. const Command *FailingCommand = CmdPair.second;
  937. // Remove result files if we're not saving temps.
  938. if (!isSaveTempsEnabled()) {
  939. const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
  940. C.CleanupFileMap(C.getResultFiles(), JA, true);
  941. // Failure result files are valid unless we crashed.
  942. if (Res < 0)
  943. C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
  944. }
  945. // Print extra information about abnormal failures, if possible.
  946. //
  947. // This is ad-hoc, but we don't want to be excessively noisy. If the result
  948. // status was 1, assume the command failed normally. In particular, if it
  949. // was the compiler then assume it gave a reasonable error code. Failures
  950. // in other tools are less common, and they generally have worse
  951. // diagnostics, so always print the diagnostic there.
  952. const Tool &FailingTool = FailingCommand->getCreator();
  953. if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
  954. // FIXME: See FIXME above regarding result code interpretation.
  955. if (Res < 0)
  956. Diag(clang::diag::err_drv_command_signalled)
  957. << FailingTool.getShortName();
  958. else
  959. Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
  960. << Res;
  961. }
  962. }
  963. return 0;
  964. }
  965. void Driver::PrintHelp(bool ShowHidden) const {
  966. unsigned IncludedFlagsBitmask;
  967. unsigned ExcludedFlagsBitmask;
  968. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  969. getIncludeExcludeOptionFlagMasks();
  970. ExcludedFlagsBitmask |= options::NoDriverOption;
  971. if (!ShowHidden)
  972. ExcludedFlagsBitmask |= HelpHidden;
  973. getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
  974. IncludedFlagsBitmask, ExcludedFlagsBitmask,
  975. /*ShowAllAliases=*/false);
  976. }
  977. void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
  978. // FIXME: The following handlers should use a callback mechanism, we don't
  979. // know what the client would like to do.
  980. OS << getClangFullVersion() << '\n';
  981. const ToolChain &TC = C.getDefaultToolChain();
  982. OS << "Target: " << TC.getTripleString() << '\n';
  983. // Print the threading model.
  984. if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
  985. // Don't print if the ToolChain would have barfed on it already
  986. if (TC.isThreadModelSupported(A->getValue()))
  987. OS << "Thread model: " << A->getValue();
  988. } else
  989. OS << "Thread model: " << TC.getThreadModel();
  990. OS << '\n';
  991. // Print out the install directory.
  992. OS << "InstalledDir: " << InstalledDir << '\n';
  993. }
  994. /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
  995. /// option.
  996. static void PrintDiagnosticCategories(raw_ostream &OS) {
  997. // Skip the empty category.
  998. for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
  999. ++i)
  1000. OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
  1001. }
  1002. void Driver::handleAutocompletions(StringRef PassedFlags) const {
  1003. // Print out all options that start with a given argument. This is used for
  1004. // shell autocompletion.
  1005. std::vector<std::string> SuggestedCompletions;
  1006. unsigned short DisableFlags =
  1007. options::NoDriverOption | options::Unsupported | options::Ignored;
  1008. // We want to show cc1-only options only when clang is invoked as "clang
  1009. // -cc1". When clang is invoked as "clang -cc1", we add "#" to the beginning
  1010. // of an --autocomplete option so that the clang driver can distinguish
  1011. // whether it is requested to show cc1-only options or not.
  1012. if (PassedFlags.size() > 0 && PassedFlags[0] == '#') {
  1013. DisableFlags &= ~options::NoDriverOption;
  1014. PassedFlags = PassedFlags.substr(1);
  1015. }
  1016. if (PassedFlags.find(',') == StringRef::npos) {
  1017. // If the flag is in the form of "--autocomplete=-foo",
  1018. // we were requested to print out all option names that start with "-foo".
  1019. // For example, "--autocomplete=-fsyn" is expanded to "-fsyntax-only".
  1020. SuggestedCompletions = Opts->findByPrefix(PassedFlags, DisableFlags);
  1021. // We have to query the -W flags manually as they're not in the OptTable.
  1022. // TODO: Find a good way to add them to OptTable instead and them remove
  1023. // this code.
  1024. for (StringRef S : DiagnosticIDs::getDiagnosticFlags())
  1025. if (S.startswith(PassedFlags))
  1026. SuggestedCompletions.push_back(S);
  1027. } else {
  1028. // If the flag is in the form of "--autocomplete=foo,bar", we were
  1029. // requested to print out all option values for "-foo" that start with
  1030. // "bar". For example,
  1031. // "--autocomplete=-stdlib=,l" is expanded to "libc++" and "libstdc++".
  1032. StringRef Option, Arg;
  1033. std::tie(Option, Arg) = PassedFlags.split(',');
  1034. SuggestedCompletions = Opts->suggestValueCompletions(Option, Arg);
  1035. }
  1036. // Sort the autocomplete candidates so that shells print them out in a
  1037. // deterministic order. We could sort in any way, but we chose
  1038. // case-insensitive sorting for consistency with the -help option
  1039. // which prints out options in the case-insensitive alphabetical order.
  1040. std::sort(SuggestedCompletions.begin(), SuggestedCompletions.end(),
  1041. [](StringRef A, StringRef B) { return A.compare_lower(B) < 0; });
  1042. llvm::outs() << llvm::join(SuggestedCompletions, "\n") << '\n';
  1043. }
  1044. bool Driver::HandleImmediateArgs(const Compilation &C) {
  1045. // The order these options are handled in gcc is all over the place, but we
  1046. // don't expect inconsistencies w.r.t. that to matter in practice.
  1047. if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
  1048. llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
  1049. return false;
  1050. }
  1051. if (C.getArgs().hasArg(options::OPT_dumpversion)) {
  1052. // Since -dumpversion is only implemented for pedantic GCC compatibility, we
  1053. // return an answer which matches our definition of __VERSION__.
  1054. //
  1055. // If we want to return a more correct answer some day, then we should
  1056. // introduce a non-pedantically GCC compatible mode to Clang in which we
  1057. // provide sensible definitions for -dumpversion, __VERSION__, etc.
  1058. llvm::outs() << "4.2.1\n";
  1059. return false;
  1060. }
  1061. if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
  1062. PrintDiagnosticCategories(llvm::outs());
  1063. return false;
  1064. }
  1065. if (C.getArgs().hasArg(options::OPT_help) ||
  1066. C.getArgs().hasArg(options::OPT__help_hidden)) {
  1067. PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
  1068. return false;
  1069. }
  1070. if (C.getArgs().hasArg(options::OPT__version)) {
  1071. // Follow gcc behavior and use stdout for --version and stderr for -v.
  1072. PrintVersion(C, llvm::outs());
  1073. return false;
  1074. }
  1075. if (C.getArgs().hasArg(options::OPT_v) ||
  1076. C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  1077. PrintVersion(C, llvm::errs());
  1078. SuppressMissingInputWarning = true;
  1079. }
  1080. const ToolChain &TC = C.getDefaultToolChain();
  1081. if (C.getArgs().hasArg(options::OPT_v))
  1082. TC.printVerboseInfo(llvm::errs());
  1083. if (C.getArgs().hasArg(options::OPT_print_resource_dir)) {
  1084. llvm::outs() << ResourceDir << '\n';
  1085. return false;
  1086. }
  1087. if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
  1088. llvm::outs() << "programs: =";
  1089. bool separator = false;
  1090. for (const std::string &Path : TC.getProgramPaths()) {
  1091. if (separator)
  1092. llvm::outs() << ':';
  1093. llvm::outs() << Path;
  1094. separator = true;
  1095. }
  1096. llvm::outs() << "\n";
  1097. llvm::outs() << "libraries: =" << ResourceDir;
  1098. StringRef sysroot = C.getSysRoot();
  1099. for (const std::string &Path : TC.getFilePaths()) {
  1100. // Always print a separator. ResourceDir was the first item shown.
  1101. llvm::outs() << ':';
  1102. // Interpretation of leading '=' is needed only for NetBSD.
  1103. if (Path[0] == '=')
  1104. llvm::outs() << sysroot << Path.substr(1);
  1105. else
  1106. llvm::outs() << Path;
  1107. }
  1108. llvm::outs() << "\n";
  1109. return false;
  1110. }
  1111. // FIXME: The following handlers should use a callback mechanism, we don't
  1112. // know what the client would like to do.
  1113. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
  1114. llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
  1115. return false;
  1116. }
  1117. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
  1118. llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
  1119. return false;
  1120. }
  1121. if (Arg *A = C.getArgs().getLastArg(options::OPT_autocomplete)) {
  1122. StringRef PassedFlags = A->getValue();
  1123. handleAutocompletions(PassedFlags);
  1124. return false;
  1125. }
  1126. if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
  1127. ToolChain::RuntimeLibType RLT = TC.GetRuntimeLibType(C.getArgs());
  1128. const llvm::Triple Triple(TC.ComputeEffectiveClangTriple(C.getArgs()));
  1129. RegisterEffectiveTriple TripleRAII(TC, Triple);
  1130. switch (RLT) {
  1131. case ToolChain::RLT_CompilerRT:
  1132. llvm::outs() << TC.getCompilerRT(C.getArgs(), "builtins") << "\n";
  1133. break;
  1134. case ToolChain::RLT_Libgcc:
  1135. llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
  1136. break;
  1137. }
  1138. return false;
  1139. }
  1140. if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
  1141. for (const Multilib &Multilib : TC.getMultilibs())
  1142. llvm::outs() << Multilib << "\n";
  1143. return false;
  1144. }
  1145. if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
  1146. for (const Multilib &Multilib : TC.getMultilibs()) {
  1147. if (Multilib.gccSuffix().empty())
  1148. llvm::outs() << ".\n";
  1149. else {
  1150. StringRef Suffix(Multilib.gccSuffix());
  1151. assert(Suffix.front() == '/');
  1152. llvm::outs() << Suffix.substr(1) << "\n";
  1153. }
  1154. }
  1155. return false;
  1156. }
  1157. return true;
  1158. }
  1159. // Display an action graph human-readably. Action A is the "sink" node
  1160. // and latest-occuring action. Traversal is in pre-order, visiting the
  1161. // inputs to each action before printing the action itself.
  1162. static unsigned PrintActions1(const Compilation &C, Action *A,
  1163. std::map<Action *, unsigned> &Ids) {
  1164. if (Ids.count(A)) // A was already visited.
  1165. return Ids[A];
  1166. std::string str;
  1167. llvm::raw_string_ostream os(str);
  1168. os << Action::getClassName(A->getKind()) << ", ";
  1169. if (InputAction *IA = dyn_cast<InputAction>(A)) {
  1170. os << "\"" << IA->getInputArg().getValue() << "\"";
  1171. } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
  1172. os << '"' << BIA->getArchName() << '"' << ", {"
  1173. << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
  1174. } else if (OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
  1175. bool IsFirst = true;
  1176. OA->doOnEachDependence(
  1177. [&](Action *A, const ToolChain *TC, const char *BoundArch) {
  1178. // E.g. for two CUDA device dependences whose bound arch is sm_20 and
  1179. // sm_35 this will generate:
  1180. // "cuda-device" (nvptx64-nvidia-cuda:sm_20) {#ID}, "cuda-device"
  1181. // (nvptx64-nvidia-cuda:sm_35) {#ID}
  1182. if (!IsFirst)
  1183. os << ", ";
  1184. os << '"';
  1185. if (TC)
  1186. os << A->getOffloadingKindPrefix();
  1187. else
  1188. os << "host";
  1189. os << " (";
  1190. os << TC->getTriple().normalize();
  1191. if (BoundArch)
  1192. os << ":" << BoundArch;
  1193. os << ")";
  1194. os << '"';
  1195. os << " {" << PrintActions1(C, A, Ids) << "}";
  1196. IsFirst = false;
  1197. });
  1198. } else {
  1199. const ActionList *AL = &A->getInputs();
  1200. if (AL->size()) {
  1201. const char *Prefix = "{";
  1202. for (Action *PreRequisite : *AL) {
  1203. os << Prefix << PrintActions1(C, PreRequisite, Ids);
  1204. Prefix = ", ";
  1205. }
  1206. os << "}";
  1207. } else
  1208. os << "{}";
  1209. }
  1210. // Append offload info for all options other than the offloading action
  1211. // itself (e.g. (cuda-device, sm_20) or (cuda-host)).
  1212. std::string offload_str;
  1213. llvm::raw_string_ostream offload_os(offload_str);
  1214. if (!isa<OffloadAction>(A)) {
  1215. auto S = A->getOffloadingKindPrefix();
  1216. if (!S.empty()) {
  1217. offload_os << ", (" << S;
  1218. if (A->getOffloadingArch())
  1219. offload_os << ", " << A->getOffloadingArch();
  1220. offload_os << ")";
  1221. }
  1222. }
  1223. unsigned Id = Ids.size();
  1224. Ids[A] = Id;
  1225. llvm::errs() << Id << ": " << os.str() << ", "
  1226. << types::getTypeName(A->getType()) << offload_os.str() << "\n";
  1227. return Id;
  1228. }
  1229. // Print the action graphs in a compilation C.
  1230. // For example "clang -c file1.c file2.c" is composed of two subgraphs.
  1231. void Driver::PrintActions(const Compilation &C) const {
  1232. std::map<Action *, unsigned> Ids;
  1233. for (Action *A : C.getActions())
  1234. PrintActions1(C, A, Ids);
  1235. }
  1236. /// \brief Check whether the given input tree contains any compilation or
  1237. /// assembly actions.
  1238. static bool ContainsCompileOrAssembleAction(const Action *A) {
  1239. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
  1240. isa<AssembleJobAction>(A))
  1241. return true;
  1242. for (const Action *Input : A->inputs())
  1243. if (ContainsCompileOrAssembleAction(Input))
  1244. return true;
  1245. return false;
  1246. }
  1247. void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
  1248. const InputList &BAInputs) const {
  1249. DerivedArgList &Args = C.getArgs();
  1250. ActionList &Actions = C.getActions();
  1251. llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
  1252. // Collect the list of architectures. Duplicates are allowed, but should only
  1253. // be handled once (in the order seen).
  1254. llvm::StringSet<> ArchNames;
  1255. SmallVector<const char *, 4> Archs;
  1256. for (Arg *A : Args) {
  1257. if (A->getOption().matches(options::OPT_arch)) {
  1258. // Validate the option here; we don't save the type here because its
  1259. // particular spelling may participate in other driver choices.
  1260. llvm::Triple::ArchType Arch =
  1261. tools::darwin::getArchTypeForMachOArchName(A->getValue());
  1262. if (Arch == llvm::Triple::UnknownArch) {
  1263. Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
  1264. continue;
  1265. }
  1266. A->claim();
  1267. if (ArchNames.insert(A->getValue()).second)
  1268. Archs.push_back(A->getValue());
  1269. }
  1270. }
  1271. // When there is no explicit arch for this platform, make sure we still bind
  1272. // the architecture (to the default) so that -Xarch_ is handled correctly.
  1273. if (!Archs.size())
  1274. Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
  1275. ActionList SingleActions;
  1276. BuildActions(C, Args, BAInputs, SingleActions);
  1277. // Add in arch bindings for every top level action, as well as lipo and
  1278. // dsymutil steps if needed.
  1279. for (Action* Act : SingleActions) {
  1280. // Make sure we can lipo this kind of output. If not (and it is an actual
  1281. // output) then we disallow, since we can't create an output file with the
  1282. // right name without overwriting it. We could remove this oddity by just
  1283. // changing the output names to include the arch, which would also fix
  1284. // -save-temps. Compatibility wins for now.
  1285. if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
  1286. Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
  1287. << types::getTypeName(Act->getType());
  1288. ActionList Inputs;
  1289. for (unsigned i = 0, e = Archs.size(); i != e; ++i)
  1290. Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
  1291. // Lipo if necessary, we do it this way because we need to set the arch flag
  1292. // so that -Xarch_ gets overwritten.
  1293. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
  1294. Actions.append(Inputs.begin(), Inputs.end());
  1295. else
  1296. Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
  1297. // Handle debug info queries.
  1298. Arg *A = Args.getLastArg(options::OPT_g_Group);
  1299. if (A && !A->getOption().matches(options::OPT_g0) &&
  1300. !A->getOption().matches(options::OPT_gstabs) &&
  1301. ContainsCompileOrAssembleAction(Actions.back())) {
  1302. // Add a 'dsymutil' step if necessary, when debug info is enabled and we
  1303. // have a compile input. We need to run 'dsymutil' ourselves in such cases
  1304. // because the debug info will refer to a temporary object file which
  1305. // will be removed at the end of the compilation process.
  1306. if (Act->getType() == types::TY_Image) {
  1307. ActionList Inputs;
  1308. Inputs.push_back(Actions.back());
  1309. Actions.pop_back();
  1310. Actions.push_back(
  1311. C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
  1312. }
  1313. // Verify the debug info output.
  1314. if (Args.hasArg(options::OPT_verify_debug_info)) {
  1315. Action* LastAction = Actions.back();
  1316. Actions.pop_back();
  1317. Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
  1318. LastAction, types::TY_Nothing));
  1319. }
  1320. }
  1321. }
  1322. }
  1323. /// \brief Check that the file referenced by Value exists. If it doesn't,
  1324. /// issue a diagnostic and return false.
  1325. static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
  1326. StringRef Value, types::ID Ty) {
  1327. if (!D.getCheckInputsExist())
  1328. return true;
  1329. // stdin always exists.
  1330. if (Value == "-")
  1331. return true;
  1332. SmallString<64> Path(Value);
  1333. if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
  1334. if (!llvm::sys::path::is_absolute(Path)) {
  1335. SmallString<64> Directory(WorkDir->getValue());
  1336. llvm::sys::path::append(Directory, Value);
  1337. Path.assign(Directory);
  1338. }
  1339. }
  1340. if (llvm::sys::fs::exists(Twine(Path)))
  1341. return true;
  1342. if (D.IsCLMode()) {
  1343. if (!llvm::sys::path::is_absolute(Twine(Path)) &&
  1344. llvm::sys::Process::FindInEnvPath("LIB", Value))
  1345. return true;
  1346. if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
  1347. // Arguments to the /link flag might cause the linker to search for object
  1348. // and library files in paths we don't know about. Don't error in such
  1349. // cases.
  1350. return true;
  1351. }
  1352. }
  1353. D.Diag(clang::diag::err_drv_no_such_file) << Path;
  1354. return false;
  1355. }
  1356. // Construct a the list of inputs and their types.
  1357. void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
  1358. InputList &Inputs) const {
  1359. // Track the current user specified (-x) input. We also explicitly track the
  1360. // argument used to set the type; we only want to claim the type when we
  1361. // actually use it, so we warn about unused -x arguments.
  1362. types::ID InputType = types::TY_Nothing;
  1363. Arg *InputTypeArg = nullptr;
  1364. // The last /TC or /TP option sets the input type to C or C++ globally.
  1365. if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
  1366. options::OPT__SLASH_TP)) {
  1367. InputTypeArg = TCTP;
  1368. InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
  1369. ? types::TY_C
  1370. : types::TY_CXX;
  1371. Arg *Previous = nullptr;
  1372. bool ShowNote = false;
  1373. for (Arg *A : Args.filtered(options::OPT__SLASH_TC, options::OPT__SLASH_TP)) {
  1374. if (Previous) {
  1375. Diag(clang::diag::warn_drv_overriding_flag_option)
  1376. << Previous->getSpelling() << A->getSpelling();
  1377. ShowNote = true;
  1378. }
  1379. Previous = A;
  1380. }
  1381. if (ShowNote)
  1382. Diag(clang::diag::note_drv_t_option_is_global);
  1383. // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
  1384. assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
  1385. }
  1386. for (Arg *A : Args) {
  1387. if (A->getOption().getKind() == Option::InputClass) {
  1388. const char *Value = A->getValue();
  1389. types::ID Ty = types::TY_INVALID;
  1390. // Infer the input type if necessary.
  1391. if (InputType == types::TY_Nothing) {
  1392. // If there was an explicit arg for this, claim it.
  1393. if (InputTypeArg)
  1394. InputTypeArg->claim();
  1395. // stdin must be handled specially.
  1396. if (memcmp(Value, "-", 2) == 0) {
  1397. // If running with -E, treat as a C input (this changes the builtin
  1398. // macros, for example). This may be overridden by -ObjC below.
  1399. //
  1400. // Otherwise emit an error but still use a valid type to avoid
  1401. // spurious errors (e.g., no inputs).
  1402. if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
  1403. Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
  1404. : clang::diag::err_drv_unknown_stdin_type);
  1405. Ty = types::TY_C;
  1406. } else {
  1407. // Otherwise lookup by extension.
  1408. // Fallback is C if invoked as C preprocessor or Object otherwise.
  1409. // We use a host hook here because Darwin at least has its own
  1410. // idea of what .s is.
  1411. if (const char *Ext = strrchr(Value, '.'))
  1412. Ty = TC.LookupTypeForExtension(Ext + 1);
  1413. if (Ty == types::TY_INVALID) {
  1414. if (CCCIsCPP())
  1415. Ty = types::TY_C;
  1416. else
  1417. Ty = types::TY_Object;
  1418. }
  1419. // If the driver is invoked as C++ compiler (like clang++ or c++) it
  1420. // should autodetect some input files as C++ for g++ compatibility.
  1421. if (CCCIsCXX()) {
  1422. types::ID OldTy = Ty;
  1423. Ty = types::lookupCXXTypeForCType(Ty);
  1424. if (Ty != OldTy)
  1425. Diag(clang::diag::warn_drv_treating_input_as_cxx)
  1426. << getTypeName(OldTy) << getTypeName(Ty);
  1427. }
  1428. }
  1429. // -ObjC and -ObjC++ override the default language, but only for "source
  1430. // files". We just treat everything that isn't a linker input as a
  1431. // source file.
  1432. //
  1433. // FIXME: Clean this up if we move the phase sequence into the type.
  1434. if (Ty != types::TY_Object) {
  1435. if (Args.hasArg(options::OPT_ObjC))
  1436. Ty = types::TY_ObjC;
  1437. else if (Args.hasArg(options::OPT_ObjCXX))
  1438. Ty = types::TY_ObjCXX;
  1439. }
  1440. } else {
  1441. assert(InputTypeArg && "InputType set w/o InputTypeArg");
  1442. if (!InputTypeArg->getOption().matches(options::OPT_x)) {
  1443. // If emulating cl.exe, make sure that /TC and /TP don't affect input
  1444. // object files.
  1445. const char *Ext = strrchr(Value, '.');
  1446. if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
  1447. Ty = types::TY_Object;
  1448. }
  1449. if (Ty == types::TY_INVALID) {
  1450. Ty = InputType;
  1451. InputTypeArg->claim();
  1452. }
  1453. }
  1454. if (DiagnoseInputExistence(*this, Args, Value, Ty))
  1455. Inputs.push_back(std::make_pair(Ty, A));
  1456. } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
  1457. StringRef Value = A->getValue();
  1458. if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
  1459. Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
  1460. Inputs.push_back(std::make_pair(types::TY_C, InputArg));
  1461. }
  1462. A->claim();
  1463. } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
  1464. StringRef Value = A->getValue();
  1465. if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
  1466. Arg *InputArg = MakeInputArg(Args, *Opts, A->getValue());
  1467. Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
  1468. }
  1469. A->claim();
  1470. } else if (A->getOption().hasFlag(options::LinkerInput)) {
  1471. // Just treat as object type, we could make a special type for this if
  1472. // necessary.
  1473. Inputs.push_back(std::make_pair(types::TY_Object, A));
  1474. } else if (A->getOption().matches(options::OPT_x)) {
  1475. InputTypeArg = A;
  1476. InputType = types::lookupTypeForTypeSpecifier(A->getValue());
  1477. A->claim();
  1478. // Follow gcc behavior and treat as linker input for invalid -x
  1479. // options. Its not clear why we shouldn't just revert to unknown; but
  1480. // this isn't very important, we might as well be bug compatible.
  1481. if (!InputType) {
  1482. Diag(clang::diag::err_drv_unknown_language) << A->getValue();
  1483. InputType = types::TY_Object;
  1484. }
  1485. } else if (A->getOption().getID() == options::OPT__SLASH_U) {
  1486. assert(A->getNumValues() == 1 && "The /U option has one value.");
  1487. StringRef Val = A->getValue(0);
  1488. if (Val.find_first_of("/\\") != StringRef::npos) {
  1489. // Warn about e.g. "/Users/me/myfile.c".
  1490. Diag(diag::warn_slash_u_filename) << Val;
  1491. Diag(diag::note_use_dashdash);
  1492. }
  1493. }
  1494. }
  1495. if (CCCIsCPP() && Inputs.empty()) {
  1496. // If called as standalone preprocessor, stdin is processed
  1497. // if no other input is present.
  1498. Arg *A = MakeInputArg(Args, *Opts, "-");
  1499. Inputs.push_back(std::make_pair(types::TY_C, A));
  1500. }
  1501. }
  1502. namespace {
  1503. /// Provides a convenient interface for different programming models to generate
  1504. /// the required device actions.
  1505. class OffloadingActionBuilder final {
  1506. /// Flag used to trace errors in the builder.
  1507. bool IsValid = false;
  1508. /// The compilation that is using this builder.
  1509. Compilation &C;
  1510. /// Map between an input argument and the offload kinds used to process it.
  1511. std::map<const Arg *, unsigned> InputArgToOffloadKindMap;
  1512. /// Builder interface. It doesn't build anything or keep any state.
  1513. class DeviceActionBuilder {
  1514. public:
  1515. typedef llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PhasesTy;
  1516. enum ActionBuilderReturnCode {
  1517. // The builder acted successfully on the current action.
  1518. ABRT_Success,
  1519. // The builder didn't have to act on the current action.
  1520. ABRT_Inactive,
  1521. // The builder was successful and requested the host action to not be
  1522. // generated.
  1523. ABRT_Ignore_Host,
  1524. };
  1525. protected:
  1526. /// Compilation associated with this builder.
  1527. Compilation &C;
  1528. /// Tool chains associated with this builder. The same programming
  1529. /// model may have associated one or more tool chains.
  1530. SmallVector<const ToolChain *, 2> ToolChains;
  1531. /// The derived arguments associated with this builder.
  1532. DerivedArgList &Args;
  1533. /// The inputs associated with this builder.
  1534. const Driver::InputList &Inputs;
  1535. /// The associated offload kind.
  1536. Action::OffloadKind AssociatedOffloadKind = Action::OFK_None;
  1537. public:
  1538. DeviceActionBuilder(Compilation &C, DerivedArgList &Args,
  1539. const Driver::InputList &Inputs,
  1540. Action::OffloadKind AssociatedOffloadKind)
  1541. : C(C), Args(Args), Inputs(Inputs),
  1542. AssociatedOffloadKind(AssociatedOffloadKind) {}
  1543. virtual ~DeviceActionBuilder() {}
  1544. /// Fill up the array \a DA with all the device dependences that should be
  1545. /// added to the provided host action \a HostAction. By default it is
  1546. /// inactive.
  1547. virtual ActionBuilderReturnCode
  1548. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  1549. phases::ID CurPhase, phases::ID FinalPhase,
  1550. PhasesTy &Phases) {
  1551. return ABRT_Inactive;
  1552. }
  1553. /// Update the state to include the provided host action \a HostAction as a
  1554. /// dependency of the current device action. By default it is inactive.
  1555. virtual ActionBuilderReturnCode addDeviceDepences(Action *HostAction) {
  1556. return ABRT_Inactive;
  1557. }
  1558. /// Append top level actions generated by the builder. Return true if errors
  1559. /// were found.
  1560. virtual void appendTopLevelActions(ActionList &AL) {}
  1561. /// Append linker actions generated by the builder. Return true if errors
  1562. /// were found.
  1563. virtual void appendLinkDependences(OffloadAction::DeviceDependences &DA) {}
  1564. /// Initialize the builder. Return true if any initialization errors are
  1565. /// found.
  1566. virtual bool initialize() { return false; }
  1567. /// Return true if the builder can use bundling/unbundling.
  1568. virtual bool canUseBundlerUnbundler() const { return false; }
  1569. /// Return true if this builder is valid. We have a valid builder if we have
  1570. /// associated device tool chains.
  1571. bool isValid() { return !ToolChains.empty(); }
  1572. /// Return the associated offload kind.
  1573. Action::OffloadKind getAssociatedOffloadKind() {
  1574. return AssociatedOffloadKind;
  1575. }
  1576. };
  1577. /// \brief CUDA action builder. It injects device code in the host backend
  1578. /// action.
  1579. class CudaActionBuilder final : public DeviceActionBuilder {
  1580. /// Flags to signal if the user requested host-only or device-only
  1581. /// compilation.
  1582. bool CompileHostOnly = false;
  1583. bool CompileDeviceOnly = false;
  1584. /// List of GPU architectures to use in this compilation.
  1585. SmallVector<CudaArch, 4> GpuArchList;
  1586. /// The CUDA actions for the current input.
  1587. ActionList CudaDeviceActions;
  1588. /// The CUDA fat binary if it was generated for the current input.
  1589. Action *CudaFatBinary = nullptr;
  1590. /// Flag that is set to true if this builder acted on the current input.
  1591. bool IsActive = false;
  1592. public:
  1593. CudaActionBuilder(Compilation &C, DerivedArgList &Args,
  1594. const Driver::InputList &Inputs)
  1595. : DeviceActionBuilder(C, Args, Inputs, Action::OFK_Cuda) {}
  1596. ActionBuilderReturnCode
  1597. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  1598. phases::ID CurPhase, phases::ID FinalPhase,
  1599. PhasesTy &Phases) override {
  1600. if (!IsActive)
  1601. return ABRT_Inactive;
  1602. // If we don't have more CUDA actions, we don't have any dependences to
  1603. // create for the host.
  1604. if (CudaDeviceActions.empty())
  1605. return ABRT_Success;
  1606. assert(CudaDeviceActions.size() == GpuArchList.size() &&
  1607. "Expecting one action per GPU architecture.");
  1608. assert(!CompileHostOnly &&
  1609. "Not expecting CUDA actions in host-only compilation.");
  1610. // If we are generating code for the device or we are in a backend phase,
  1611. // we attempt to generate the fat binary. We compile each arch to ptx and
  1612. // assemble to cubin, then feed the cubin *and* the ptx into a device
  1613. // "link" action, which uses fatbinary to combine these cubins into one
  1614. // fatbin. The fatbin is then an input to the host action if not in
  1615. // device-only mode.
  1616. if (CompileDeviceOnly || CurPhase == phases::Backend) {
  1617. ActionList DeviceActions;
  1618. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  1619. // Produce the device action from the current phase up to the assemble
  1620. // phase.
  1621. for (auto Ph : Phases) {
  1622. // Skip the phases that were already dealt with.
  1623. if (Ph < CurPhase)
  1624. continue;
  1625. // We have to be consistent with the host final phase.
  1626. if (Ph > FinalPhase)
  1627. break;
  1628. CudaDeviceActions[I] = C.getDriver().ConstructPhaseAction(
  1629. C, Args, Ph, CudaDeviceActions[I]);
  1630. if (Ph == phases::Assemble)
  1631. break;
  1632. }
  1633. // If we didn't reach the assemble phase, we can't generate the fat
  1634. // binary. We don't need to generate the fat binary if we are not in
  1635. // device-only mode.
  1636. if (!isa<AssembleJobAction>(CudaDeviceActions[I]) ||
  1637. CompileDeviceOnly)
  1638. continue;
  1639. Action *AssembleAction = CudaDeviceActions[I];
  1640. assert(AssembleAction->getType() == types::TY_Object);
  1641. assert(AssembleAction->getInputs().size() == 1);
  1642. Action *BackendAction = AssembleAction->getInputs()[0];
  1643. assert(BackendAction->getType() == types::TY_PP_Asm);
  1644. for (auto &A : {AssembleAction, BackendAction}) {
  1645. OffloadAction::DeviceDependences DDep;
  1646. DDep.add(*A, *ToolChains.front(), CudaArchToString(GpuArchList[I]),
  1647. Action::OFK_Cuda);
  1648. DeviceActions.push_back(
  1649. C.MakeAction<OffloadAction>(DDep, A->getType()));
  1650. }
  1651. }
  1652. // We generate the fat binary if we have device input actions.
  1653. if (!DeviceActions.empty()) {
  1654. CudaFatBinary =
  1655. C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN);
  1656. if (!CompileDeviceOnly) {
  1657. DA.add(*CudaFatBinary, *ToolChains.front(), /*BoundArch=*/nullptr,
  1658. Action::OFK_Cuda);
  1659. // Clear the fat binary, it is already a dependence to an host
  1660. // action.
  1661. CudaFatBinary = nullptr;
  1662. }
  1663. // Remove the CUDA actions as they are already connected to an host
  1664. // action or fat binary.
  1665. CudaDeviceActions.clear();
  1666. }
  1667. // We avoid creating host action in device-only mode.
  1668. return CompileDeviceOnly ? ABRT_Ignore_Host : ABRT_Success;
  1669. } else if (CurPhase > phases::Backend) {
  1670. // If we are past the backend phase and still have a device action, we
  1671. // don't have to do anything as this action is already a device
  1672. // top-level action.
  1673. return ABRT_Success;
  1674. }
  1675. assert(CurPhase < phases::Backend && "Generating single CUDA "
  1676. "instructions should only occur "
  1677. "before the backend phase!");
  1678. // By default, we produce an action for each device arch.
  1679. for (Action *&A : CudaDeviceActions)
  1680. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
  1681. return ABRT_Success;
  1682. }
  1683. ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
  1684. // While generating code for CUDA, we only depend on the host input action
  1685. // to trigger the creation of all the CUDA device actions.
  1686. // If we are dealing with an input action, replicate it for each GPU
  1687. // architecture. If we are in host-only mode we return 'success' so that
  1688. // the host uses the CUDA offload kind.
  1689. if (auto *IA = dyn_cast<InputAction>(HostAction)) {
  1690. assert(!GpuArchList.empty() &&
  1691. "We should have at least one GPU architecture.");
  1692. // If the host input is not CUDA, we don't need to bother about this
  1693. // input.
  1694. if (IA->getType() != types::TY_CUDA) {
  1695. // The builder will ignore this input.
  1696. IsActive = false;
  1697. return ABRT_Inactive;
  1698. }
  1699. // Set the flag to true, so that the builder acts on the current input.
  1700. IsActive = true;
  1701. if (CompileHostOnly)
  1702. return ABRT_Success;
  1703. // Replicate inputs for each GPU architecture.
  1704. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
  1705. CudaDeviceActions.push_back(C.MakeAction<InputAction>(
  1706. IA->getInputArg(), types::TY_CUDA_DEVICE));
  1707. return ABRT_Success;
  1708. }
  1709. return IsActive ? ABRT_Success : ABRT_Inactive;
  1710. }
  1711. void appendTopLevelActions(ActionList &AL) override {
  1712. // Utility to append actions to the top level list.
  1713. auto AddTopLevel = [&](Action *A, CudaArch BoundArch) {
  1714. OffloadAction::DeviceDependences Dep;
  1715. Dep.add(*A, *ToolChains.front(), CudaArchToString(BoundArch),
  1716. Action::OFK_Cuda);
  1717. AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
  1718. };
  1719. // If we have a fat binary, add it to the list.
  1720. if (CudaFatBinary) {
  1721. AddTopLevel(CudaFatBinary, CudaArch::UNKNOWN);
  1722. CudaDeviceActions.clear();
  1723. CudaFatBinary = nullptr;
  1724. return;
  1725. }
  1726. if (CudaDeviceActions.empty())
  1727. return;
  1728. // If we have CUDA actions at this point, that's because we have a have
  1729. // partial compilation, so we should have an action for each GPU
  1730. // architecture.
  1731. assert(CudaDeviceActions.size() == GpuArchList.size() &&
  1732. "Expecting one action per GPU architecture.");
  1733. assert(ToolChains.size() == 1 &&
  1734. "Expecting to have a sing CUDA toolchain.");
  1735. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
  1736. AddTopLevel(CudaDeviceActions[I], GpuArchList[I]);
  1737. CudaDeviceActions.clear();
  1738. }
  1739. bool initialize() override {
  1740. // We don't need to support CUDA.
  1741. if (!C.hasOffloadToolChain<Action::OFK_Cuda>())
  1742. return false;
  1743. const ToolChain *HostTC = C.getSingleOffloadToolChain<Action::OFK_Host>();
  1744. assert(HostTC && "No toolchain for host compilation.");
  1745. if (HostTC->getTriple().isNVPTX()) {
  1746. // We do not support targeting NVPTX for host compilation. Throw
  1747. // an error and abort pipeline construction early so we don't trip
  1748. // asserts that assume device-side compilation.
  1749. C.getDriver().Diag(diag::err_drv_cuda_nvptx_host);
  1750. return true;
  1751. }
  1752. ToolChains.push_back(C.getSingleOffloadToolChain<Action::OFK_Cuda>());
  1753. Arg *PartialCompilationArg = Args.getLastArg(
  1754. options::OPT_cuda_host_only, options::OPT_cuda_device_only,
  1755. options::OPT_cuda_compile_host_device);
  1756. CompileHostOnly = PartialCompilationArg &&
  1757. PartialCompilationArg->getOption().matches(
  1758. options::OPT_cuda_host_only);
  1759. CompileDeviceOnly = PartialCompilationArg &&
  1760. PartialCompilationArg->getOption().matches(
  1761. options::OPT_cuda_device_only);
  1762. // Collect all cuda_gpu_arch parameters, removing duplicates.
  1763. std::set<CudaArch> GpuArchs;
  1764. bool Error = false;
  1765. for (Arg *A : Args) {
  1766. if (!(A->getOption().matches(options::OPT_cuda_gpu_arch_EQ) ||
  1767. A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ)))
  1768. continue;
  1769. A->claim();
  1770. const StringRef ArchStr = A->getValue();
  1771. if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ) &&
  1772. ArchStr == "all") {
  1773. GpuArchs.clear();
  1774. continue;
  1775. }
  1776. CudaArch Arch = StringToCudaArch(ArchStr);
  1777. if (Arch == CudaArch::UNKNOWN) {
  1778. C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
  1779. Error = true;
  1780. } else if (A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
  1781. GpuArchs.insert(Arch);
  1782. else if (A->getOption().matches(options::OPT_no_cuda_gpu_arch_EQ))
  1783. GpuArchs.erase(Arch);
  1784. else
  1785. llvm_unreachable("Unexpected option.");
  1786. }
  1787. // Collect list of GPUs remaining in the set.
  1788. for (CudaArch Arch : GpuArchs)
  1789. GpuArchList.push_back(Arch);
  1790. // Default to sm_20 which is the lowest common denominator for
  1791. // supported GPUs. sm_20 code should work correctly, if
  1792. // suboptimally, on all newer GPUs.
  1793. if (GpuArchList.empty())
  1794. GpuArchList.push_back(CudaArch::SM_20);
  1795. return Error;
  1796. }
  1797. };
  1798. /// OpenMP action builder. The host bitcode is passed to the device frontend
  1799. /// and all the device linked images are passed to the host link phase.
  1800. class OpenMPActionBuilder final : public DeviceActionBuilder {
  1801. /// The OpenMP actions for the current input.
  1802. ActionList OpenMPDeviceActions;
  1803. /// The linker inputs obtained for each toolchain.
  1804. SmallVector<ActionList, 8> DeviceLinkerInputs;
  1805. public:
  1806. OpenMPActionBuilder(Compilation &C, DerivedArgList &Args,
  1807. const Driver::InputList &Inputs)
  1808. : DeviceActionBuilder(C, Args, Inputs, Action::OFK_OpenMP) {}
  1809. ActionBuilderReturnCode
  1810. getDeviceDependences(OffloadAction::DeviceDependences &DA,
  1811. phases::ID CurPhase, phases::ID FinalPhase,
  1812. PhasesTy &Phases) override {
  1813. // We should always have an action for each input.
  1814. assert(OpenMPDeviceActions.size() == ToolChains.size() &&
  1815. "Number of OpenMP actions and toolchains do not match.");
  1816. // The host only depends on device action in the linking phase, when all
  1817. // the device images have to be embedded in the host image.
  1818. if (CurPhase == phases::Link) {
  1819. assert(ToolChains.size() == DeviceLinkerInputs.size() &&
  1820. "Toolchains and linker inputs sizes do not match.");
  1821. auto LI = DeviceLinkerInputs.begin();
  1822. for (auto *A : OpenMPDeviceActions) {
  1823. LI->push_back(A);
  1824. ++LI;
  1825. }
  1826. // We passed the device action as a host dependence, so we don't need to
  1827. // do anything else with them.
  1828. OpenMPDeviceActions.clear();
  1829. return ABRT_Success;
  1830. }
  1831. // By default, we produce an action for each device arch.
  1832. for (Action *&A : OpenMPDeviceActions)
  1833. A = C.getDriver().ConstructPhaseAction(C, Args, CurPhase, A);
  1834. return ABRT_Success;
  1835. }
  1836. ActionBuilderReturnCode addDeviceDepences(Action *HostAction) override {
  1837. // If this is an input action replicate it for each OpenMP toolchain.
  1838. if (auto *IA = dyn_cast<InputAction>(HostAction)) {
  1839. OpenMPDeviceActions.clear();
  1840. for (unsigned I = 0; I < ToolChains.size(); ++I)
  1841. OpenMPDeviceActions.push_back(
  1842. C.MakeAction<InputAction>(IA->getInputArg(), IA->getType()));
  1843. return ABRT_Success;
  1844. }
  1845. // If this is an unbundling action use it as is for each OpenMP toolchain.
  1846. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(HostAction)) {
  1847. OpenMPDeviceActions.clear();
  1848. for (unsigned I = 0; I < ToolChains.size(); ++I) {
  1849. OpenMPDeviceActions.push_back(UA);
  1850. UA->registerDependentActionInfo(
  1851. ToolChains[I], /*BoundArch=*/StringRef(), Action::OFK_OpenMP);
  1852. }
  1853. return ABRT_Success;
  1854. }
  1855. // When generating code for OpenMP we use the host compile phase result as
  1856. // a dependence to the device compile phase so that it can learn what
  1857. // declarations should be emitted. However, this is not the only use for
  1858. // the host action, so we prevent it from being collapsed.
  1859. if (isa<CompileJobAction>(HostAction)) {
  1860. HostAction->setCannotBeCollapsedWithNextDependentAction();
  1861. assert(ToolChains.size() == OpenMPDeviceActions.size() &&
  1862. "Toolchains and device action sizes do not match.");
  1863. OffloadAction::HostDependence HDep(
  1864. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  1865. /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  1866. auto TC = ToolChains.begin();
  1867. for (Action *&A : OpenMPDeviceActions) {
  1868. assert(isa<CompileJobAction>(A));
  1869. OffloadAction::DeviceDependences DDep;
  1870. DDep.add(*A, **TC, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  1871. A = C.MakeAction<OffloadAction>(HDep, DDep);
  1872. ++TC;
  1873. }
  1874. }
  1875. return ABRT_Success;
  1876. }
  1877. void appendTopLevelActions(ActionList &AL) override {
  1878. if (OpenMPDeviceActions.empty())
  1879. return;
  1880. // We should always have an action for each input.
  1881. assert(OpenMPDeviceActions.size() == ToolChains.size() &&
  1882. "Number of OpenMP actions and toolchains do not match.");
  1883. // Append all device actions followed by the proper offload action.
  1884. auto TI = ToolChains.begin();
  1885. for (auto *A : OpenMPDeviceActions) {
  1886. OffloadAction::DeviceDependences Dep;
  1887. Dep.add(*A, **TI, /*BoundArch=*/nullptr, Action::OFK_OpenMP);
  1888. AL.push_back(C.MakeAction<OffloadAction>(Dep, A->getType()));
  1889. ++TI;
  1890. }
  1891. // We no longer need the action stored in this builder.
  1892. OpenMPDeviceActions.clear();
  1893. }
  1894. void appendLinkDependences(OffloadAction::DeviceDependences &DA) override {
  1895. assert(ToolChains.size() == DeviceLinkerInputs.size() &&
  1896. "Toolchains and linker inputs sizes do not match.");
  1897. // Append a new link action for each device.
  1898. auto TC = ToolChains.begin();
  1899. for (auto &LI : DeviceLinkerInputs) {
  1900. auto *DeviceLinkAction =
  1901. C.MakeAction<LinkJobAction>(LI, types::TY_Image);
  1902. DA.add(*DeviceLinkAction, **TC, /*BoundArch=*/nullptr,
  1903. Action::OFK_OpenMP);
  1904. ++TC;
  1905. }
  1906. }
  1907. bool initialize() override {
  1908. // Get the OpenMP toolchains. If we don't get any, the action builder will
  1909. // know there is nothing to do related to OpenMP offloading.
  1910. auto OpenMPTCRange = C.getOffloadToolChains<Action::OFK_OpenMP>();
  1911. for (auto TI = OpenMPTCRange.first, TE = OpenMPTCRange.second; TI != TE;
  1912. ++TI)
  1913. ToolChains.push_back(TI->second);
  1914. DeviceLinkerInputs.resize(ToolChains.size());
  1915. return false;
  1916. }
  1917. bool canUseBundlerUnbundler() const override {
  1918. // OpenMP should use bundled files whenever possible.
  1919. return true;
  1920. }
  1921. };
  1922. ///
  1923. /// TODO: Add the implementation for other specialized builders here.
  1924. ///
  1925. /// Specialized builders being used by this offloading action builder.
  1926. SmallVector<DeviceActionBuilder *, 4> SpecializedBuilders;
  1927. /// Flag set to true if all valid builders allow file bundling/unbundling.
  1928. bool CanUseBundler;
  1929. public:
  1930. OffloadingActionBuilder(Compilation &C, DerivedArgList &Args,
  1931. const Driver::InputList &Inputs)
  1932. : C(C) {
  1933. // Create a specialized builder for each device toolchain.
  1934. IsValid = true;
  1935. // Create a specialized builder for CUDA.
  1936. SpecializedBuilders.push_back(new CudaActionBuilder(C, Args, Inputs));
  1937. // Create a specialized builder for OpenMP.
  1938. SpecializedBuilders.push_back(new OpenMPActionBuilder(C, Args, Inputs));
  1939. //
  1940. // TODO: Build other specialized builders here.
  1941. //
  1942. // Initialize all the builders, keeping track of errors. If all valid
  1943. // builders agree that we can use bundling, set the flag to true.
  1944. unsigned ValidBuilders = 0u;
  1945. unsigned ValidBuildersSupportingBundling = 0u;
  1946. for (auto *SB : SpecializedBuilders) {
  1947. IsValid = IsValid && !SB->initialize();
  1948. // Update the counters if the builder is valid.
  1949. if (SB->isValid()) {
  1950. ++ValidBuilders;
  1951. if (SB->canUseBundlerUnbundler())
  1952. ++ValidBuildersSupportingBundling;
  1953. }
  1954. }
  1955. CanUseBundler =
  1956. ValidBuilders && ValidBuilders == ValidBuildersSupportingBundling;
  1957. }
  1958. ~OffloadingActionBuilder() {
  1959. for (auto *SB : SpecializedBuilders)
  1960. delete SB;
  1961. }
  1962. /// Generate an action that adds device dependences (if any) to a host action.
  1963. /// If no device dependence actions exist, just return the host action \a
  1964. /// HostAction. If an error is found or if no builder requires the host action
  1965. /// to be generated, return nullptr.
  1966. Action *
  1967. addDeviceDependencesToHostAction(Action *HostAction, const Arg *InputArg,
  1968. phases::ID CurPhase, phases::ID FinalPhase,
  1969. DeviceActionBuilder::PhasesTy &Phases) {
  1970. if (!IsValid)
  1971. return nullptr;
  1972. if (SpecializedBuilders.empty())
  1973. return HostAction;
  1974. assert(HostAction && "Invalid host action!");
  1975. OffloadAction::DeviceDependences DDeps;
  1976. // Check if all the programming models agree we should not emit the host
  1977. // action. Also, keep track of the offloading kinds employed.
  1978. auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
  1979. unsigned InactiveBuilders = 0u;
  1980. unsigned IgnoringBuilders = 0u;
  1981. for (auto *SB : SpecializedBuilders) {
  1982. if (!SB->isValid()) {
  1983. ++InactiveBuilders;
  1984. continue;
  1985. }
  1986. auto RetCode =
  1987. SB->getDeviceDependences(DDeps, CurPhase, FinalPhase, Phases);
  1988. // If the builder explicitly says the host action should be ignored,
  1989. // we need to increment the variable that tracks the builders that request
  1990. // the host object to be ignored.
  1991. if (RetCode == DeviceActionBuilder::ABRT_Ignore_Host)
  1992. ++IgnoringBuilders;
  1993. // Unless the builder was inactive for this action, we have to record the
  1994. // offload kind because the host will have to use it.
  1995. if (RetCode != DeviceActionBuilder::ABRT_Inactive)
  1996. OffloadKind |= SB->getAssociatedOffloadKind();
  1997. }
  1998. // If all builders agree that the host object should be ignored, just return
  1999. // nullptr.
  2000. if (IgnoringBuilders &&
  2001. SpecializedBuilders.size() == (InactiveBuilders + IgnoringBuilders))
  2002. return nullptr;
  2003. if (DDeps.getActions().empty())
  2004. return HostAction;
  2005. // We have dependences we need to bundle together. We use an offload action
  2006. // for that.
  2007. OffloadAction::HostDependence HDep(
  2008. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2009. /*BoundArch=*/nullptr, DDeps);
  2010. return C.MakeAction<OffloadAction>(HDep, DDeps);
  2011. }
  2012. /// Generate an action that adds a host dependence to a device action. The
  2013. /// results will be kept in this action builder. Return true if an error was
  2014. /// found.
  2015. bool addHostDependenceToDeviceActions(Action *&HostAction,
  2016. const Arg *InputArg) {
  2017. if (!IsValid)
  2018. return true;
  2019. // If we are supporting bundling/unbundling and the current action is an
  2020. // input action of non-source file, we replace the host action by the
  2021. // unbundling action. The bundler tool has the logic to detect if an input
  2022. // is a bundle or not and if the input is not a bundle it assumes it is a
  2023. // host file. Therefore it is safe to create an unbundling action even if
  2024. // the input is not a bundle.
  2025. if (CanUseBundler && isa<InputAction>(HostAction) &&
  2026. InputArg->getOption().getKind() == llvm::opt::Option::InputClass &&
  2027. !types::isSrcFile(HostAction->getType())) {
  2028. auto UnbundlingHostAction =
  2029. C.MakeAction<OffloadUnbundlingJobAction>(HostAction);
  2030. UnbundlingHostAction->registerDependentActionInfo(
  2031. C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2032. /*BoundArch=*/StringRef(), Action::OFK_Host);
  2033. HostAction = UnbundlingHostAction;
  2034. }
  2035. assert(HostAction && "Invalid host action!");
  2036. // Register the offload kinds that are used.
  2037. auto &OffloadKind = InputArgToOffloadKindMap[InputArg];
  2038. for (auto *SB : SpecializedBuilders) {
  2039. if (!SB->isValid())
  2040. continue;
  2041. auto RetCode = SB->addDeviceDepences(HostAction);
  2042. // Host dependences for device actions are not compatible with that same
  2043. // action being ignored.
  2044. assert(RetCode != DeviceActionBuilder::ABRT_Ignore_Host &&
  2045. "Host dependence not expected to be ignored.!");
  2046. // Unless the builder was inactive for this action, we have to record the
  2047. // offload kind because the host will have to use it.
  2048. if (RetCode != DeviceActionBuilder::ABRT_Inactive)
  2049. OffloadKind |= SB->getAssociatedOffloadKind();
  2050. }
  2051. return false;
  2052. }
  2053. /// Add the offloading top level actions to the provided action list. This
  2054. /// function can replace the host action by a bundling action if the
  2055. /// programming models allow it.
  2056. bool appendTopLevelActions(ActionList &AL, Action *HostAction,
  2057. const Arg *InputArg) {
  2058. // Get the device actions to be appended.
  2059. ActionList OffloadAL;
  2060. for (auto *SB : SpecializedBuilders) {
  2061. if (!SB->isValid())
  2062. continue;
  2063. SB->appendTopLevelActions(OffloadAL);
  2064. }
  2065. // If we can use the bundler, replace the host action by the bundling one in
  2066. // the resulting list. Otherwise, just append the device actions.
  2067. if (CanUseBundler && !OffloadAL.empty()) {
  2068. // Add the host action to the list in order to create the bundling action.
  2069. OffloadAL.push_back(HostAction);
  2070. // We expect that the host action was just appended to the action list
  2071. // before this method was called.
  2072. assert(HostAction == AL.back() && "Host action not in the list??");
  2073. HostAction = C.MakeAction<OffloadBundlingJobAction>(OffloadAL);
  2074. AL.back() = HostAction;
  2075. } else
  2076. AL.append(OffloadAL.begin(), OffloadAL.end());
  2077. // Propagate to the current host action (if any) the offload information
  2078. // associated with the current input.
  2079. if (HostAction)
  2080. HostAction->propagateHostOffloadInfo(InputArgToOffloadKindMap[InputArg],
  2081. /*BoundArch=*/nullptr);
  2082. return false;
  2083. }
  2084. /// Processes the host linker action. This currently consists of replacing it
  2085. /// with an offload action if there are device link objects and propagate to
  2086. /// the host action all the offload kinds used in the current compilation. The
  2087. /// resulting action is returned.
  2088. Action *processHostLinkAction(Action *HostAction) {
  2089. // Add all the dependences from the device linking actions.
  2090. OffloadAction::DeviceDependences DDeps;
  2091. for (auto *SB : SpecializedBuilders) {
  2092. if (!SB->isValid())
  2093. continue;
  2094. SB->appendLinkDependences(DDeps);
  2095. }
  2096. // Calculate all the offload kinds used in the current compilation.
  2097. unsigned ActiveOffloadKinds = 0u;
  2098. for (auto &I : InputArgToOffloadKindMap)
  2099. ActiveOffloadKinds |= I.second;
  2100. // If we don't have device dependencies, we don't have to create an offload
  2101. // action.
  2102. if (DDeps.getActions().empty()) {
  2103. // Propagate all the active kinds to host action. Given that it is a link
  2104. // action it is assumed to depend on all actions generated so far.
  2105. HostAction->propagateHostOffloadInfo(ActiveOffloadKinds,
  2106. /*BoundArch=*/nullptr);
  2107. return HostAction;
  2108. }
  2109. // Create the offload action with all dependences. When an offload action
  2110. // is created the kinds are propagated to the host action, so we don't have
  2111. // to do that explicitly here.
  2112. OffloadAction::HostDependence HDep(
  2113. *HostAction, *C.getSingleOffloadToolChain<Action::OFK_Host>(),
  2114. /*BoundArch*/ nullptr, ActiveOffloadKinds);
  2115. return C.MakeAction<OffloadAction>(HDep, DDeps);
  2116. }
  2117. };
  2118. } // anonymous namespace.
  2119. void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
  2120. const InputList &Inputs, ActionList &Actions) const {
  2121. llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
  2122. if (!SuppressMissingInputWarning && Inputs.empty()) {
  2123. Diag(clang::diag::err_drv_no_input_files);
  2124. return;
  2125. }
  2126. Arg *FinalPhaseArg;
  2127. phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
  2128. if (FinalPhase == phases::Link) {
  2129. if (Args.hasArg(options::OPT_emit_llvm))
  2130. Diag(clang::diag::err_drv_emit_llvm_link);
  2131. if (IsCLMode() && LTOMode != LTOK_None &&
  2132. !Args.getLastArgValue(options::OPT_fuse_ld_EQ).equals_lower("lld"))
  2133. Diag(clang::diag::err_drv_lto_without_lld);
  2134. }
  2135. // Reject -Z* at the top level, these options should never have been exposed
  2136. // by gcc.
  2137. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
  2138. Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
  2139. // Diagnose misuse of /Fo.
  2140. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
  2141. StringRef V = A->getValue();
  2142. if (Inputs.size() > 1 && !V.empty() &&
  2143. !llvm::sys::path::is_separator(V.back())) {
  2144. // Check whether /Fo tries to name an output file for multiple inputs.
  2145. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  2146. << A->getSpelling() << V;
  2147. Args.eraseArg(options::OPT__SLASH_Fo);
  2148. }
  2149. }
  2150. // Diagnose misuse of /Fa.
  2151. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
  2152. StringRef V = A->getValue();
  2153. if (Inputs.size() > 1 && !V.empty() &&
  2154. !llvm::sys::path::is_separator(V.back())) {
  2155. // Check whether /Fa tries to name an asm file for multiple inputs.
  2156. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  2157. << A->getSpelling() << V;
  2158. Args.eraseArg(options::OPT__SLASH_Fa);
  2159. }
  2160. }
  2161. // Diagnose misuse of /o.
  2162. if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
  2163. if (A->getValue()[0] == '\0') {
  2164. // It has to have a value.
  2165. Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
  2166. Args.eraseArg(options::OPT__SLASH_o);
  2167. }
  2168. }
  2169. // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
  2170. // * no filename after it
  2171. // * both /Yc and /Yu passed but with different filenames
  2172. // * corresponding file not also passed as /FI
  2173. Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  2174. Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  2175. if (YcArg && YcArg->getValue()[0] == '\0') {
  2176. Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
  2177. Args.eraseArg(options::OPT__SLASH_Yc);
  2178. YcArg = nullptr;
  2179. }
  2180. if (YuArg && YuArg->getValue()[0] == '\0') {
  2181. Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
  2182. Args.eraseArg(options::OPT__SLASH_Yu);
  2183. YuArg = nullptr;
  2184. }
  2185. if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
  2186. Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
  2187. Args.eraseArg(options::OPT__SLASH_Yc);
  2188. Args.eraseArg(options::OPT__SLASH_Yu);
  2189. YcArg = YuArg = nullptr;
  2190. }
  2191. if (YcArg || YuArg) {
  2192. StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
  2193. bool FoundMatchingInclude = false;
  2194. for (const Arg *Inc : Args.filtered(options::OPT_include)) {
  2195. // FIXME: Do case-insensitive matching and consider / and \ as equal.
  2196. if (Inc->getValue() == Val)
  2197. FoundMatchingInclude = true;
  2198. }
  2199. if (!FoundMatchingInclude) {
  2200. Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
  2201. << (YcArg ? YcArg : YuArg)->getSpelling();
  2202. Args.eraseArg(options::OPT__SLASH_Yc);
  2203. Args.eraseArg(options::OPT__SLASH_Yu);
  2204. YcArg = YuArg = nullptr;
  2205. }
  2206. }
  2207. if (YcArg && Inputs.size() > 1) {
  2208. Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
  2209. Args.eraseArg(options::OPT__SLASH_Yc);
  2210. YcArg = nullptr;
  2211. }
  2212. if (Args.hasArg(options::OPT__SLASH_Y_)) {
  2213. // /Y- disables all pch handling. Rather than check for it everywhere,
  2214. // just remove clang-cl pch-related flags here.
  2215. Args.eraseArg(options::OPT__SLASH_Fp);
  2216. Args.eraseArg(options::OPT__SLASH_Yc);
  2217. Args.eraseArg(options::OPT__SLASH_Yu);
  2218. YcArg = YuArg = nullptr;
  2219. }
  2220. // Builder to be used to build offloading actions.
  2221. OffloadingActionBuilder OffloadBuilder(C, Args, Inputs);
  2222. // Construct the actions to perform.
  2223. ActionList LinkerInputs;
  2224. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
  2225. for (auto &I : Inputs) {
  2226. types::ID InputType = I.first;
  2227. const Arg *InputArg = I.second;
  2228. PL.clear();
  2229. types::getCompilationPhases(InputType, PL);
  2230. // If the first step comes after the final phase we are doing as part of
  2231. // this compilation, warn the user about it.
  2232. phases::ID InitialPhase = PL[0];
  2233. if (InitialPhase > FinalPhase) {
  2234. // Claim here to avoid the more general unused warning.
  2235. InputArg->claim();
  2236. // Suppress all unused style warnings with -Qunused-arguments
  2237. if (Args.hasArg(options::OPT_Qunused_arguments))
  2238. continue;
  2239. // Special case when final phase determined by binary name, rather than
  2240. // by a command-line argument with a corresponding Arg.
  2241. if (CCCIsCPP())
  2242. Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
  2243. << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
  2244. // Special case '-E' warning on a previously preprocessed file to make
  2245. // more sense.
  2246. else if (InitialPhase == phases::Compile &&
  2247. FinalPhase == phases::Preprocess &&
  2248. getPreprocessedType(InputType) == types::TY_INVALID)
  2249. Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
  2250. << InputArg->getAsString(Args) << !!FinalPhaseArg
  2251. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  2252. else
  2253. Diag(clang::diag::warn_drv_input_file_unused)
  2254. << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
  2255. << !!FinalPhaseArg
  2256. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  2257. continue;
  2258. }
  2259. if (YcArg) {
  2260. // Add a separate precompile phase for the compile phase.
  2261. if (FinalPhase >= phases::Compile) {
  2262. const types::ID HeaderType = lookupHeaderTypeForSourceType(InputType);
  2263. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
  2264. types::getCompilationPhases(HeaderType, PCHPL);
  2265. Arg *PchInputArg = MakeInputArg(Args, *Opts, YcArg->getValue());
  2266. // Build the pipeline for the pch file.
  2267. Action *ClangClPch =
  2268. C.MakeAction<InputAction>(*PchInputArg, HeaderType);
  2269. for (phases::ID Phase : PCHPL)
  2270. ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
  2271. assert(ClangClPch);
  2272. Actions.push_back(ClangClPch);
  2273. // The driver currently exits after the first failed command. This
  2274. // relies on that behavior, to make sure if the pch generation fails,
  2275. // the main compilation won't run.
  2276. }
  2277. }
  2278. // Build the pipeline for this file.
  2279. Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
  2280. // Use the current host action in any of the offloading actions, if
  2281. // required.
  2282. if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
  2283. break;
  2284. for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
  2285. i != e; ++i) {
  2286. phases::ID Phase = *i;
  2287. // We are done if this step is past what the user requested.
  2288. if (Phase > FinalPhase)
  2289. break;
  2290. // Add any offload action the host action depends on.
  2291. Current = OffloadBuilder.addDeviceDependencesToHostAction(
  2292. Current, InputArg, Phase, FinalPhase, PL);
  2293. if (!Current)
  2294. break;
  2295. // Queue linker inputs.
  2296. if (Phase == phases::Link) {
  2297. assert((i + 1) == e && "linking must be final compilation step.");
  2298. LinkerInputs.push_back(Current);
  2299. Current = nullptr;
  2300. break;
  2301. }
  2302. // Otherwise construct the appropriate action.
  2303. auto *NewCurrent = ConstructPhaseAction(C, Args, Phase, Current);
  2304. // We didn't create a new action, so we will just move to the next phase.
  2305. if (NewCurrent == Current)
  2306. continue;
  2307. Current = NewCurrent;
  2308. // Use the current host action in any of the offloading actions, if
  2309. // required.
  2310. if (OffloadBuilder.addHostDependenceToDeviceActions(Current, InputArg))
  2311. break;
  2312. if (Current->getType() == types::TY_Nothing)
  2313. break;
  2314. }
  2315. // If we ended with something, add to the output list.
  2316. if (Current)
  2317. Actions.push_back(Current);
  2318. // Add any top level actions generated for offloading.
  2319. OffloadBuilder.appendTopLevelActions(Actions, Current, InputArg);
  2320. }
  2321. // Add a link action if necessary.
  2322. if (!LinkerInputs.empty()) {
  2323. Action *LA = C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image);
  2324. LA = OffloadBuilder.processHostLinkAction(LA);
  2325. Actions.push_back(LA);
  2326. }
  2327. // If we are linking, claim any options which are obviously only used for
  2328. // compilation.
  2329. if (FinalPhase == phases::Link && PL.size() == 1) {
  2330. Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
  2331. Args.ClaimAllArgs(options::OPT_cl_compile_Group);
  2332. }
  2333. // Claim ignored clang-cl options.
  2334. Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
  2335. // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
  2336. // to non-CUDA compilations and should not trigger warnings there.
  2337. Args.ClaimAllArgs(options::OPT_cuda_host_only);
  2338. Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
  2339. }
  2340. Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
  2341. phases::ID Phase, Action *Input) const {
  2342. llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
  2343. // Some types skip the assembler phase (e.g., llvm-bc), but we can't
  2344. // encode this in the steps because the intermediate type depends on
  2345. // arguments. Just special case here.
  2346. if (Phase == phases::Assemble && Input->getType() != types::TY_PP_Asm)
  2347. return Input;
  2348. // Build the appropriate action.
  2349. switch (Phase) {
  2350. case phases::Link:
  2351. llvm_unreachable("link action invalid here.");
  2352. case phases::Preprocess: {
  2353. types::ID OutputTy;
  2354. // -{M, MM} alter the output type.
  2355. if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
  2356. OutputTy = types::TY_Dependencies;
  2357. } else {
  2358. OutputTy = Input->getType();
  2359. if (!Args.hasFlag(options::OPT_frewrite_includes,
  2360. options::OPT_fno_rewrite_includes, false) &&
  2361. !Args.hasFlag(options::OPT_frewrite_imports,
  2362. options::OPT_fno_rewrite_imports, false) &&
  2363. !CCGenDiagnostics)
  2364. OutputTy = types::getPreprocessedType(OutputTy);
  2365. assert(OutputTy != types::TY_INVALID &&
  2366. "Cannot preprocess this input type!");
  2367. }
  2368. return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
  2369. }
  2370. case phases::Precompile: {
  2371. types::ID OutputTy = getPrecompiledType(Input->getType());
  2372. assert(OutputTy != types::TY_INVALID &&
  2373. "Cannot precompile this input type!");
  2374. if (Args.hasArg(options::OPT_fsyntax_only)) {
  2375. // Syntax checks should not emit a PCH file
  2376. OutputTy = types::TY_Nothing;
  2377. }
  2378. return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
  2379. }
  2380. case phases::Compile: {
  2381. if (Args.hasArg(options::OPT_fsyntax_only))
  2382. return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
  2383. if (Args.hasArg(options::OPT_rewrite_objc))
  2384. return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
  2385. if (Args.hasArg(options::OPT_rewrite_legacy_objc))
  2386. return C.MakeAction<CompileJobAction>(Input,
  2387. types::TY_RewrittenLegacyObjC);
  2388. if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
  2389. return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
  2390. if (Args.hasArg(options::OPT__migrate))
  2391. return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
  2392. if (Args.hasArg(options::OPT_emit_ast))
  2393. return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
  2394. if (Args.hasArg(options::OPT_module_file_info))
  2395. return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
  2396. if (Args.hasArg(options::OPT_verify_pch))
  2397. return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
  2398. return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
  2399. }
  2400. case phases::Backend: {
  2401. if (isUsingLTO()) {
  2402. types::ID Output =
  2403. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  2404. return C.MakeAction<BackendJobAction>(Input, Output);
  2405. }
  2406. if (Args.hasArg(options::OPT_emit_llvm)) {
  2407. types::ID Output =
  2408. Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
  2409. return C.MakeAction<BackendJobAction>(Input, Output);
  2410. }
  2411. return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
  2412. }
  2413. case phases::Assemble:
  2414. return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
  2415. }
  2416. llvm_unreachable("invalid phase in ConstructPhaseAction");
  2417. }
  2418. void Driver::BuildJobs(Compilation &C) const {
  2419. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  2420. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  2421. // It is an error to provide a -o option if we are making multiple output
  2422. // files.
  2423. if (FinalOutput) {
  2424. unsigned NumOutputs = 0;
  2425. for (const Action *A : C.getActions())
  2426. if (A->getType() != types::TY_Nothing)
  2427. ++NumOutputs;
  2428. if (NumOutputs > 1) {
  2429. Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  2430. FinalOutput = nullptr;
  2431. }
  2432. }
  2433. // Collect the list of architectures.
  2434. llvm::StringSet<> ArchNames;
  2435. if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
  2436. for (const Arg *A : C.getArgs())
  2437. if (A->getOption().matches(options::OPT_arch))
  2438. ArchNames.insert(A->getValue());
  2439. // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
  2440. std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
  2441. for (Action *A : C.getActions()) {
  2442. // If we are linking an image for multiple archs then the linker wants
  2443. // -arch_multiple and -final_output <final image name>. Unfortunately, this
  2444. // doesn't fit in cleanly because we have to pass this information down.
  2445. //
  2446. // FIXME: This is a hack; find a cleaner way to integrate this into the
  2447. // process.
  2448. const char *LinkingOutput = nullptr;
  2449. if (isa<LipoJobAction>(A)) {
  2450. if (FinalOutput)
  2451. LinkingOutput = FinalOutput->getValue();
  2452. else
  2453. LinkingOutput = getDefaultImageName();
  2454. }
  2455. BuildJobsForAction(C, A, &C.getDefaultToolChain(),
  2456. /*BoundArch*/ StringRef(),
  2457. /*AtTopLevel*/ true,
  2458. /*MultipleArchs*/ ArchNames.size() > 1,
  2459. /*LinkingOutput*/ LinkingOutput, CachedResults,
  2460. /*TargetDeviceOffloadKind*/ Action::OFK_None);
  2461. }
  2462. // If the user passed -Qunused-arguments or there were errors, don't warn
  2463. // about any unused arguments.
  2464. if (Diags.hasErrorOccurred() ||
  2465. C.getArgs().hasArg(options::OPT_Qunused_arguments))
  2466. return;
  2467. // Claim -### here.
  2468. (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
  2469. // Claim --driver-mode, --rsp-quoting, it was handled earlier.
  2470. (void)C.getArgs().hasArg(options::OPT_driver_mode);
  2471. (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
  2472. for (Arg *A : C.getArgs()) {
  2473. // FIXME: It would be nice to be able to send the argument to the
  2474. // DiagnosticsEngine, so that extra values, position, and so on could be
  2475. // printed.
  2476. if (!A->isClaimed()) {
  2477. if (A->getOption().hasFlag(options::NoArgumentUnused))
  2478. continue;
  2479. // Suppress the warning automatically if this is just a flag, and it is an
  2480. // instance of an argument we already claimed.
  2481. const Option &Opt = A->getOption();
  2482. if (Opt.getKind() == Option::FlagClass) {
  2483. bool DuplicateClaimed = false;
  2484. for (const Arg *AA : C.getArgs().filtered(&Opt)) {
  2485. if (AA->isClaimed()) {
  2486. DuplicateClaimed = true;
  2487. break;
  2488. }
  2489. }
  2490. if (DuplicateClaimed)
  2491. continue;
  2492. }
  2493. // In clang-cl, don't mention unknown arguments here since they have
  2494. // already been warned about.
  2495. if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
  2496. Diag(clang::diag::warn_drv_unused_argument)
  2497. << A->getAsString(C.getArgs());
  2498. }
  2499. }
  2500. }
  2501. namespace {
  2502. /// Utility class to control the collapse of dependent actions and select the
  2503. /// tools accordingly.
  2504. class ToolSelector final {
  2505. /// The tool chain this selector refers to.
  2506. const ToolChain &TC;
  2507. /// The compilation this selector refers to.
  2508. const Compilation &C;
  2509. /// The base action this selector refers to.
  2510. const JobAction *BaseAction;
  2511. /// Set to true if the current toolchain refers to host actions.
  2512. bool IsHostSelector;
  2513. /// Set to true if save-temps and embed-bitcode functionalities are active.
  2514. bool SaveTemps;
  2515. bool EmbedBitcode;
  2516. /// Get previous dependent action or null if that does not exist. If
  2517. /// \a CanBeCollapsed is false, that action must be legal to collapse or
  2518. /// null will be returned.
  2519. const JobAction *getPrevDependentAction(const ActionList &Inputs,
  2520. ActionList &SavedOffloadAction,
  2521. bool CanBeCollapsed = true) {
  2522. // An option can be collapsed only if it has a single input.
  2523. if (Inputs.size() != 1)
  2524. return nullptr;
  2525. Action *CurAction = *Inputs.begin();
  2526. if (CanBeCollapsed &&
  2527. !CurAction->isCollapsingWithNextDependentActionLegal())
  2528. return nullptr;
  2529. // If the input action is an offload action. Look through it and save any
  2530. // offload action that can be dropped in the event of a collapse.
  2531. if (auto *OA = dyn_cast<OffloadAction>(CurAction)) {
  2532. // If the dependent action is a device action, we will attempt to collapse
  2533. // only with other device actions. Otherwise, we would do the same but
  2534. // with host actions only.
  2535. if (!IsHostSelector) {
  2536. if (OA->hasSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)) {
  2537. CurAction =
  2538. OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true);
  2539. if (CanBeCollapsed &&
  2540. !CurAction->isCollapsingWithNextDependentActionLegal())
  2541. return nullptr;
  2542. SavedOffloadAction.push_back(OA);
  2543. return dyn_cast<JobAction>(CurAction);
  2544. }
  2545. } else if (OA->hasHostDependence()) {
  2546. CurAction = OA->getHostDependence();
  2547. if (CanBeCollapsed &&
  2548. !CurAction->isCollapsingWithNextDependentActionLegal())
  2549. return nullptr;
  2550. SavedOffloadAction.push_back(OA);
  2551. return dyn_cast<JobAction>(CurAction);
  2552. }
  2553. return nullptr;
  2554. }
  2555. return dyn_cast<JobAction>(CurAction);
  2556. }
  2557. /// Return true if an assemble action can be collapsed.
  2558. bool canCollapseAssembleAction() const {
  2559. return TC.useIntegratedAs() && !SaveTemps &&
  2560. !C.getArgs().hasArg(options::OPT_via_file_asm) &&
  2561. !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
  2562. !C.getArgs().hasArg(options::OPT__SLASH_Fa);
  2563. }
  2564. /// Return true if a preprocessor action can be collapsed.
  2565. bool canCollapsePreprocessorAction() const {
  2566. return !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
  2567. !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
  2568. !C.getArgs().hasArg(options::OPT_rewrite_objc);
  2569. }
  2570. /// Struct that relates an action with the offload actions that would be
  2571. /// collapsed with it.
  2572. struct JobActionInfo final {
  2573. /// The action this info refers to.
  2574. const JobAction *JA = nullptr;
  2575. /// The offload actions we need to take care off if this action is
  2576. /// collapsed.
  2577. ActionList SavedOffloadAction;
  2578. };
  2579. /// Append collapsed offload actions from the give nnumber of elements in the
  2580. /// action info array.
  2581. static void AppendCollapsedOffloadAction(ActionList &CollapsedOffloadAction,
  2582. ArrayRef<JobActionInfo> &ActionInfo,
  2583. unsigned ElementNum) {
  2584. assert(ElementNum <= ActionInfo.size() && "Invalid number of elements.");
  2585. for (unsigned I = 0; I < ElementNum; ++I)
  2586. CollapsedOffloadAction.append(ActionInfo[I].SavedOffloadAction.begin(),
  2587. ActionInfo[I].SavedOffloadAction.end());
  2588. }
  2589. /// Functions that attempt to perform the combining. They detect if that is
  2590. /// legal, and if so they update the inputs \a Inputs and the offload action
  2591. /// that were collapsed in \a CollapsedOffloadAction. A tool that deals with
  2592. /// the combined action is returned. If the combining is not legal or if the
  2593. /// tool does not exist, null is returned.
  2594. /// Currently three kinds of collapsing are supported:
  2595. /// - Assemble + Backend + Compile;
  2596. /// - Assemble + Backend ;
  2597. /// - Backend + Compile.
  2598. const Tool *
  2599. combineAssembleBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
  2600. const ActionList *&Inputs,
  2601. ActionList &CollapsedOffloadAction) {
  2602. if (ActionInfo.size() < 3 || !canCollapseAssembleAction())
  2603. return nullptr;
  2604. auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
  2605. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
  2606. auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[2].JA);
  2607. if (!AJ || !BJ || !CJ)
  2608. return nullptr;
  2609. // Get compiler tool.
  2610. const Tool *T = TC.SelectTool(*CJ);
  2611. if (!T)
  2612. return nullptr;
  2613. // When using -fembed-bitcode, it is required to have the same tool (clang)
  2614. // for both CompilerJA and BackendJA. Otherwise, combine two stages.
  2615. if (EmbedBitcode) {
  2616. const Tool *BT = TC.SelectTool(*BJ);
  2617. if (BT == T)
  2618. return nullptr;
  2619. }
  2620. if (!T->hasIntegratedAssembler())
  2621. return nullptr;
  2622. Inputs = &CJ->getInputs();
  2623. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  2624. /*NumElements=*/3);
  2625. return T;
  2626. }
  2627. const Tool *combineAssembleBackend(ArrayRef<JobActionInfo> ActionInfo,
  2628. const ActionList *&Inputs,
  2629. ActionList &CollapsedOffloadAction) {
  2630. if (ActionInfo.size() < 2 || !canCollapseAssembleAction())
  2631. return nullptr;
  2632. auto *AJ = dyn_cast<AssembleJobAction>(ActionInfo[0].JA);
  2633. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[1].JA);
  2634. if (!AJ || !BJ)
  2635. return nullptr;
  2636. // Retrieve the compile job, backend action must always be preceded by one.
  2637. ActionList CompileJobOffloadActions;
  2638. auto *CJ = getPrevDependentAction(BJ->getInputs(), CompileJobOffloadActions,
  2639. /*CanBeCollapsed=*/false);
  2640. if (!AJ || !BJ || !CJ)
  2641. return nullptr;
  2642. assert(isa<CompileJobAction>(CJ) &&
  2643. "Expecting compile job preceding backend job.");
  2644. // Get compiler tool.
  2645. const Tool *T = TC.SelectTool(*CJ);
  2646. if (!T)
  2647. return nullptr;
  2648. if (!T->hasIntegratedAssembler())
  2649. return nullptr;
  2650. Inputs = &BJ->getInputs();
  2651. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  2652. /*NumElements=*/2);
  2653. return T;
  2654. }
  2655. const Tool *combineBackendCompile(ArrayRef<JobActionInfo> ActionInfo,
  2656. const ActionList *&Inputs,
  2657. ActionList &CollapsedOffloadAction) {
  2658. if (ActionInfo.size() < 2 || !canCollapsePreprocessorAction())
  2659. return nullptr;
  2660. auto *BJ = dyn_cast<BackendJobAction>(ActionInfo[0].JA);
  2661. auto *CJ = dyn_cast<CompileJobAction>(ActionInfo[1].JA);
  2662. if (!BJ || !CJ)
  2663. return nullptr;
  2664. // Get compiler tool.
  2665. const Tool *T = TC.SelectTool(*CJ);
  2666. if (!T)
  2667. return nullptr;
  2668. if (T->canEmitIR() && (SaveTemps || EmbedBitcode))
  2669. return nullptr;
  2670. Inputs = &CJ->getInputs();
  2671. AppendCollapsedOffloadAction(CollapsedOffloadAction, ActionInfo,
  2672. /*NumElements=*/2);
  2673. return T;
  2674. }
  2675. /// Updates the inputs if the obtained tool supports combining with
  2676. /// preprocessor action, and the current input is indeed a preprocessor
  2677. /// action. If combining results in the collapse of offloading actions, those
  2678. /// are appended to \a CollapsedOffloadAction.
  2679. void combineWithPreprocessor(const Tool *T, const ActionList *&Inputs,
  2680. ActionList &CollapsedOffloadAction) {
  2681. if (!T || !canCollapsePreprocessorAction() || !T->hasIntegratedCPP())
  2682. return;
  2683. // Attempt to get a preprocessor action dependence.
  2684. ActionList PreprocessJobOffloadActions;
  2685. auto *PJ = getPrevDependentAction(*Inputs, PreprocessJobOffloadActions);
  2686. if (!PJ || !isa<PreprocessJobAction>(PJ))
  2687. return;
  2688. // This is legal to combine. Append any offload action we found and set the
  2689. // current inputs to preprocessor inputs.
  2690. CollapsedOffloadAction.append(PreprocessJobOffloadActions.begin(),
  2691. PreprocessJobOffloadActions.end());
  2692. Inputs = &PJ->getInputs();
  2693. }
  2694. public:
  2695. ToolSelector(const JobAction *BaseAction, const ToolChain &TC,
  2696. const Compilation &C, bool SaveTemps, bool EmbedBitcode)
  2697. : TC(TC), C(C), BaseAction(BaseAction), SaveTemps(SaveTemps),
  2698. EmbedBitcode(EmbedBitcode) {
  2699. assert(BaseAction && "Invalid base action.");
  2700. IsHostSelector = BaseAction->getOffloadingDeviceKind() == Action::OFK_None;
  2701. }
  2702. /// Check if a chain of actions can be combined and return the tool that can
  2703. /// handle the combination of actions. The pointer to the current inputs \a
  2704. /// Inputs and the list of offload actions \a CollapsedOffloadActions
  2705. /// connected to collapsed actions are updated accordingly. The latter enables
  2706. /// the caller of the selector to process them afterwards instead of just
  2707. /// dropping them. If no suitable tool is found, null will be returned.
  2708. const Tool *getTool(const ActionList *&Inputs,
  2709. ActionList &CollapsedOffloadAction) {
  2710. //
  2711. // Get the largest chain of actions that we could combine.
  2712. //
  2713. SmallVector<JobActionInfo, 5> ActionChain(1);
  2714. ActionChain.back().JA = BaseAction;
  2715. while (ActionChain.back().JA) {
  2716. const Action *CurAction = ActionChain.back().JA;
  2717. // Grow the chain by one element.
  2718. ActionChain.resize(ActionChain.size() + 1);
  2719. JobActionInfo &AI = ActionChain.back();
  2720. // Attempt to fill it with the
  2721. AI.JA =
  2722. getPrevDependentAction(CurAction->getInputs(), AI.SavedOffloadAction);
  2723. }
  2724. // Pop the last action info as it could not be filled.
  2725. ActionChain.pop_back();
  2726. //
  2727. // Attempt to combine actions. If all combining attempts failed, just return
  2728. // the tool of the provided action. At the end we attempt to combine the
  2729. // action with any preprocessor action it may depend on.
  2730. //
  2731. const Tool *T = combineAssembleBackendCompile(ActionChain, Inputs,
  2732. CollapsedOffloadAction);
  2733. if (!T)
  2734. T = combineAssembleBackend(ActionChain, Inputs, CollapsedOffloadAction);
  2735. if (!T)
  2736. T = combineBackendCompile(ActionChain, Inputs, CollapsedOffloadAction);
  2737. if (!T) {
  2738. Inputs = &BaseAction->getInputs();
  2739. T = TC.SelectTool(*BaseAction);
  2740. }
  2741. combineWithPreprocessor(T, Inputs, CollapsedOffloadAction);
  2742. return T;
  2743. }
  2744. };
  2745. }
  2746. /// Return a string that uniquely identifies the result of a job. The bound arch
  2747. /// is not necessarily represented in the toolchain's triple -- for example,
  2748. /// armv7 and armv7s both map to the same triple -- so we need both in our map.
  2749. /// Also, we need to add the offloading device kind, as the same tool chain can
  2750. /// be used for host and device for some programming models, e.g. OpenMP.
  2751. static std::string GetTriplePlusArchString(const ToolChain *TC,
  2752. StringRef BoundArch,
  2753. Action::OffloadKind OffloadKind) {
  2754. std::string TriplePlusArch = TC->getTriple().normalize();
  2755. if (!BoundArch.empty()) {
  2756. TriplePlusArch += "-";
  2757. TriplePlusArch += BoundArch;
  2758. }
  2759. TriplePlusArch += "-";
  2760. TriplePlusArch += Action::GetOffloadKindName(OffloadKind);
  2761. return TriplePlusArch;
  2762. }
  2763. InputInfo Driver::BuildJobsForAction(
  2764. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  2765. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  2766. std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
  2767. Action::OffloadKind TargetDeviceOffloadKind) const {
  2768. std::pair<const Action *, std::string> ActionTC = {
  2769. A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
  2770. auto CachedResult = CachedResults.find(ActionTC);
  2771. if (CachedResult != CachedResults.end()) {
  2772. return CachedResult->second;
  2773. }
  2774. InputInfo Result = BuildJobsForActionNoCache(
  2775. C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
  2776. CachedResults, TargetDeviceOffloadKind);
  2777. CachedResults[ActionTC] = Result;
  2778. return Result;
  2779. }
  2780. InputInfo Driver::BuildJobsForActionNoCache(
  2781. Compilation &C, const Action *A, const ToolChain *TC, StringRef BoundArch,
  2782. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  2783. std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults,
  2784. Action::OffloadKind TargetDeviceOffloadKind) const {
  2785. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  2786. InputInfoList OffloadDependencesInputInfo;
  2787. bool BuildingForOffloadDevice = TargetDeviceOffloadKind != Action::OFK_None;
  2788. if (const OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
  2789. // The 'Darwin' toolchain is initialized only when its arguments are
  2790. // computed. Get the default arguments for OFK_None to ensure that
  2791. // initialization is performed before processing the offload action.
  2792. // FIXME: Remove when darwin's toolchain is initialized during construction.
  2793. C.getArgsForToolChain(TC, BoundArch, Action::OFK_None);
  2794. // The offload action is expected to be used in four different situations.
  2795. //
  2796. // a) Set a toolchain/architecture/kind for a host action:
  2797. // Host Action 1 -> OffloadAction -> Host Action 2
  2798. //
  2799. // b) Set a toolchain/architecture/kind for a device action;
  2800. // Device Action 1 -> OffloadAction -> Device Action 2
  2801. //
  2802. // c) Specify a device dependence to a host action;
  2803. // Device Action 1 _
  2804. // \
  2805. // Host Action 1 ---> OffloadAction -> Host Action 2
  2806. //
  2807. // d) Specify a host dependence to a device action.
  2808. // Host Action 1 _
  2809. // \
  2810. // Device Action 1 ---> OffloadAction -> Device Action 2
  2811. //
  2812. // For a) and b), we just return the job generated for the dependence. For
  2813. // c) and d) we override the current action with the host/device dependence
  2814. // if the current toolchain is host/device and set the offload dependences
  2815. // info with the jobs obtained from the device/host dependence(s).
  2816. // If there is a single device option, just generate the job for it.
  2817. if (OA->hasSingleDeviceDependence()) {
  2818. InputInfo DevA;
  2819. OA->doOnEachDeviceDependence([&](Action *DepA, const ToolChain *DepTC,
  2820. const char *DepBoundArch) {
  2821. DevA =
  2822. BuildJobsForAction(C, DepA, DepTC, DepBoundArch, AtTopLevel,
  2823. /*MultipleArchs*/ !!DepBoundArch, LinkingOutput,
  2824. CachedResults, DepA->getOffloadingDeviceKind());
  2825. });
  2826. return DevA;
  2827. }
  2828. // If 'Action 2' is host, we generate jobs for the device dependences and
  2829. // override the current action with the host dependence. Otherwise, we
  2830. // generate the host dependences and override the action with the device
  2831. // dependence. The dependences can't therefore be a top-level action.
  2832. OA->doOnEachDependence(
  2833. /*IsHostDependence=*/BuildingForOffloadDevice,
  2834. [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
  2835. OffloadDependencesInputInfo.push_back(BuildJobsForAction(
  2836. C, DepA, DepTC, DepBoundArch, /*AtTopLevel=*/false,
  2837. /*MultipleArchs*/ !!DepBoundArch, LinkingOutput, CachedResults,
  2838. DepA->getOffloadingDeviceKind()));
  2839. });
  2840. A = BuildingForOffloadDevice
  2841. ? OA->getSingleDeviceDependence(/*DoNotConsiderHostActions=*/true)
  2842. : OA->getHostDependence();
  2843. }
  2844. if (const InputAction *IA = dyn_cast<InputAction>(A)) {
  2845. // FIXME: It would be nice to not claim this here; maybe the old scheme of
  2846. // just using Args was better?
  2847. const Arg &Input = IA->getInputArg();
  2848. Input.claim();
  2849. if (Input.getOption().matches(options::OPT_INPUT)) {
  2850. const char *Name = Input.getValue();
  2851. return InputInfo(A, Name, /* BaseInput = */ Name);
  2852. }
  2853. return InputInfo(A, &Input, /* BaseInput = */ "");
  2854. }
  2855. if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
  2856. const ToolChain *TC;
  2857. StringRef ArchName = BAA->getArchName();
  2858. if (!ArchName.empty())
  2859. TC = &getToolChain(C.getArgs(),
  2860. computeTargetTriple(*this, DefaultTargetTriple,
  2861. C.getArgs(), ArchName));
  2862. else
  2863. TC = &C.getDefaultToolChain();
  2864. return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
  2865. MultipleArchs, LinkingOutput, CachedResults,
  2866. TargetDeviceOffloadKind);
  2867. }
  2868. const ActionList *Inputs = &A->getInputs();
  2869. const JobAction *JA = cast<JobAction>(A);
  2870. ActionList CollapsedOffloadActions;
  2871. ToolSelector TS(JA, *TC, C, isSaveTempsEnabled(),
  2872. embedBitcodeInObject() && !isUsingLTO());
  2873. const Tool *T = TS.getTool(Inputs, CollapsedOffloadActions);
  2874. if (!T)
  2875. return InputInfo();
  2876. // If we've collapsed action list that contained OffloadAction we
  2877. // need to build jobs for host/device-side inputs it may have held.
  2878. for (const auto *OA : CollapsedOffloadActions)
  2879. cast<OffloadAction>(OA)->doOnEachDependence(
  2880. /*IsHostDependence=*/BuildingForOffloadDevice,
  2881. [&](Action *DepA, const ToolChain *DepTC, const char *DepBoundArch) {
  2882. OffloadDependencesInputInfo.push_back(BuildJobsForAction(
  2883. C, DepA, DepTC, DepBoundArch, /* AtTopLevel */ false,
  2884. /*MultipleArchs=*/!!DepBoundArch, LinkingOutput, CachedResults,
  2885. DepA->getOffloadingDeviceKind()));
  2886. });
  2887. // Only use pipes when there is exactly one input.
  2888. InputInfoList InputInfos;
  2889. for (const Action *Input : *Inputs) {
  2890. // Treat dsymutil and verify sub-jobs as being at the top-level too, they
  2891. // shouldn't get temporary output names.
  2892. // FIXME: Clean this up.
  2893. bool SubJobAtTopLevel =
  2894. AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
  2895. InputInfos.push_back(BuildJobsForAction(
  2896. C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
  2897. CachedResults, A->getOffloadingDeviceKind()));
  2898. }
  2899. // Always use the first input as the base input.
  2900. const char *BaseInput = InputInfos[0].getBaseInput();
  2901. // ... except dsymutil actions, which use their actual input as the base
  2902. // input.
  2903. if (JA->getType() == types::TY_dSYM)
  2904. BaseInput = InputInfos[0].getFilename();
  2905. // Append outputs of offload device jobs to the input list
  2906. if (!OffloadDependencesInputInfo.empty())
  2907. InputInfos.append(OffloadDependencesInputInfo.begin(),
  2908. OffloadDependencesInputInfo.end());
  2909. // Set the effective triple of the toolchain for the duration of this job.
  2910. llvm::Triple EffectiveTriple;
  2911. const ToolChain &ToolTC = T->getToolChain();
  2912. const ArgList &Args =
  2913. C.getArgsForToolChain(TC, BoundArch, A->getOffloadingDeviceKind());
  2914. if (InputInfos.size() != 1) {
  2915. EffectiveTriple = llvm::Triple(ToolTC.ComputeEffectiveClangTriple(Args));
  2916. } else {
  2917. // Pass along the input type if it can be unambiguously determined.
  2918. EffectiveTriple = llvm::Triple(
  2919. ToolTC.ComputeEffectiveClangTriple(Args, InputInfos[0].getType()));
  2920. }
  2921. RegisterEffectiveTriple TripleRAII(ToolTC, EffectiveTriple);
  2922. // Determine the place to write output to, if any.
  2923. InputInfo Result;
  2924. InputInfoList UnbundlingResults;
  2925. if (auto *UA = dyn_cast<OffloadUnbundlingJobAction>(JA)) {
  2926. // If we have an unbundling job, we need to create results for all the
  2927. // outputs. We also update the results cache so that other actions using
  2928. // this unbundling action can get the right results.
  2929. for (auto &UI : UA->getDependentActionsInfo()) {
  2930. assert(UI.DependentOffloadKind != Action::OFK_None &&
  2931. "Unbundling with no offloading??");
  2932. // Unbundling actions are never at the top level. When we generate the
  2933. // offloading prefix, we also do that for the host file because the
  2934. // unbundling action does not change the type of the output which can
  2935. // cause a overwrite.
  2936. std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
  2937. UI.DependentOffloadKind,
  2938. UI.DependentToolChain->getTriple().normalize(),
  2939. /*CreatePrefixForHost=*/true);
  2940. auto CurI = InputInfo(
  2941. UA, GetNamedOutputPath(C, *UA, BaseInput, UI.DependentBoundArch,
  2942. /*AtTopLevel=*/false, MultipleArchs,
  2943. OffloadingPrefix),
  2944. BaseInput);
  2945. // Save the unbundling result.
  2946. UnbundlingResults.push_back(CurI);
  2947. // Get the unique string identifier for this dependence and cache the
  2948. // result.
  2949. CachedResults[{A, GetTriplePlusArchString(
  2950. UI.DependentToolChain, BoundArch,
  2951. UI.DependentOffloadKind)}] = CurI;
  2952. }
  2953. // Now that we have all the results generated, select the one that should be
  2954. // returned for the current depending action.
  2955. std::pair<const Action *, std::string> ActionTC = {
  2956. A, GetTriplePlusArchString(TC, BoundArch, TargetDeviceOffloadKind)};
  2957. assert(CachedResults.find(ActionTC) != CachedResults.end() &&
  2958. "Result does not exist??");
  2959. Result = CachedResults[ActionTC];
  2960. } else if (JA->getType() == types::TY_Nothing)
  2961. Result = InputInfo(A, BaseInput);
  2962. else {
  2963. // We only have to generate a prefix for the host if this is not a top-level
  2964. // action.
  2965. std::string OffloadingPrefix = Action::GetOffloadingFileNamePrefix(
  2966. A->getOffloadingDeviceKind(), TC->getTriple().normalize(),
  2967. /*CreatePrefixForHost=*/!!A->getOffloadingHostActiveKinds() &&
  2968. !AtTopLevel);
  2969. Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
  2970. AtTopLevel, MultipleArchs,
  2971. OffloadingPrefix),
  2972. BaseInput);
  2973. }
  2974. if (CCCPrintBindings && !CCGenDiagnostics) {
  2975. llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
  2976. << " - \"" << T->getName() << "\", inputs: [";
  2977. for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
  2978. llvm::errs() << InputInfos[i].getAsString();
  2979. if (i + 1 != e)
  2980. llvm::errs() << ", ";
  2981. }
  2982. if (UnbundlingResults.empty())
  2983. llvm::errs() << "], output: " << Result.getAsString() << "\n";
  2984. else {
  2985. llvm::errs() << "], outputs: [";
  2986. for (unsigned i = 0, e = UnbundlingResults.size(); i != e; ++i) {
  2987. llvm::errs() << UnbundlingResults[i].getAsString();
  2988. if (i + 1 != e)
  2989. llvm::errs() << ", ";
  2990. }
  2991. llvm::errs() << "] \n";
  2992. }
  2993. } else {
  2994. if (UnbundlingResults.empty())
  2995. T->ConstructJob(
  2996. C, *JA, Result, InputInfos,
  2997. C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
  2998. LinkingOutput);
  2999. else
  3000. T->ConstructJobMultipleOutputs(
  3001. C, *JA, UnbundlingResults, InputInfos,
  3002. C.getArgsForToolChain(TC, BoundArch, JA->getOffloadingDeviceKind()),
  3003. LinkingOutput);
  3004. }
  3005. return Result;
  3006. }
  3007. const char *Driver::getDefaultImageName() const {
  3008. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  3009. return Target.isOSWindows() ? "a.exe" : "a.out";
  3010. }
  3011. /// \brief Create output filename based on ArgValue, which could either be a
  3012. /// full filename, filename without extension, or a directory. If ArgValue
  3013. /// does not provide a filename, then use BaseName, and use the extension
  3014. /// suitable for FileType.
  3015. static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
  3016. StringRef BaseName,
  3017. types::ID FileType) {
  3018. SmallString<128> Filename = ArgValue;
  3019. if (ArgValue.empty()) {
  3020. // If the argument is empty, output to BaseName in the current dir.
  3021. Filename = BaseName;
  3022. } else if (llvm::sys::path::is_separator(Filename.back())) {
  3023. // If the argument is a directory, output to BaseName in that dir.
  3024. llvm::sys::path::append(Filename, BaseName);
  3025. }
  3026. if (!llvm::sys::path::has_extension(ArgValue)) {
  3027. // If the argument didn't provide an extension, then set it.
  3028. const char *Extension = types::getTypeTempSuffix(FileType, true);
  3029. if (FileType == types::TY_Image &&
  3030. Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
  3031. // The output file is a dll.
  3032. Extension = "dll";
  3033. }
  3034. llvm::sys::path::replace_extension(Filename, Extension);
  3035. }
  3036. return Args.MakeArgString(Filename.c_str());
  3037. }
  3038. const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
  3039. const char *BaseInput,
  3040. StringRef BoundArch, bool AtTopLevel,
  3041. bool MultipleArchs,
  3042. StringRef OffloadingPrefix) const {
  3043. llvm::PrettyStackTraceString CrashInfo("Computing output path");
  3044. // Output to a user requested destination?
  3045. if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
  3046. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  3047. return C.addResultFile(FinalOutput->getValue(), &JA);
  3048. }
  3049. // For /P, preprocess to file named after BaseInput.
  3050. if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
  3051. assert(AtTopLevel && isa<PreprocessJobAction>(JA));
  3052. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  3053. StringRef NameArg;
  3054. if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
  3055. NameArg = A->getValue();
  3056. return C.addResultFile(
  3057. MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
  3058. &JA);
  3059. }
  3060. // Default to writing to stdout?
  3061. if (AtTopLevel && !CCGenDiagnostics &&
  3062. (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
  3063. return "-";
  3064. // Is this the assembly listing for /FA?
  3065. if (JA.getType() == types::TY_PP_Asm &&
  3066. (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
  3067. C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
  3068. // Use /Fa and the input filename to determine the asm file name.
  3069. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  3070. StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
  3071. return C.addResultFile(
  3072. MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
  3073. &JA);
  3074. }
  3075. // Output to a temporary file?
  3076. if ((!AtTopLevel && !isSaveTempsEnabled() &&
  3077. !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
  3078. CCGenDiagnostics) {
  3079. StringRef Name = llvm::sys::path::filename(BaseInput);
  3080. std::pair<StringRef, StringRef> Split = Name.split('.');
  3081. std::string TmpName = GetTemporaryPath(
  3082. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  3083. return C.addTempFile(C.getArgs().MakeArgString(TmpName));
  3084. }
  3085. SmallString<128> BasePath(BaseInput);
  3086. StringRef BaseName;
  3087. // Dsymutil actions should use the full path.
  3088. if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
  3089. BaseName = BasePath;
  3090. else
  3091. BaseName = llvm::sys::path::filename(BasePath);
  3092. // Determine what the derived output name should be.
  3093. const char *NamedOutput;
  3094. if ((JA.getType() == types::TY_Object || JA.getType() == types::TY_LTO_BC) &&
  3095. C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
  3096. // The /Fo or /o flag decides the object filename.
  3097. StringRef Val =
  3098. C.getArgs()
  3099. .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
  3100. ->getValue();
  3101. NamedOutput =
  3102. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
  3103. } else if (JA.getType() == types::TY_Image &&
  3104. C.getArgs().hasArg(options::OPT__SLASH_Fe,
  3105. options::OPT__SLASH_o)) {
  3106. // The /Fe or /o flag names the linked file.
  3107. StringRef Val =
  3108. C.getArgs()
  3109. .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
  3110. ->getValue();
  3111. NamedOutput =
  3112. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
  3113. } else if (JA.getType() == types::TY_Image) {
  3114. if (IsCLMode()) {
  3115. // clang-cl uses BaseName for the executable name.
  3116. NamedOutput =
  3117. MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
  3118. } else {
  3119. SmallString<128> Output(getDefaultImageName());
  3120. Output += OffloadingPrefix;
  3121. if (MultipleArchs && !BoundArch.empty()) {
  3122. Output += "-";
  3123. Output.append(BoundArch);
  3124. }
  3125. NamedOutput = C.getArgs().MakeArgString(Output.c_str());
  3126. }
  3127. } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
  3128. NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName));
  3129. } else {
  3130. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  3131. assert(Suffix && "All types used for output should have a suffix.");
  3132. std::string::size_type End = std::string::npos;
  3133. if (!types::appendSuffixForType(JA.getType()))
  3134. End = BaseName.rfind('.');
  3135. SmallString<128> Suffixed(BaseName.substr(0, End));
  3136. Suffixed += OffloadingPrefix;
  3137. if (MultipleArchs && !BoundArch.empty()) {
  3138. Suffixed += "-";
  3139. Suffixed.append(BoundArch);
  3140. }
  3141. // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
  3142. // the unoptimized bitcode so that it does not get overwritten by the ".bc"
  3143. // optimized bitcode output.
  3144. if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
  3145. JA.getType() == types::TY_LLVM_BC)
  3146. Suffixed += ".tmp";
  3147. Suffixed += '.';
  3148. Suffixed += Suffix;
  3149. NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
  3150. }
  3151. // Prepend object file path if -save-temps=obj
  3152. if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
  3153. JA.getType() != types::TY_PCH) {
  3154. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  3155. SmallString<128> TempPath(FinalOutput->getValue());
  3156. llvm::sys::path::remove_filename(TempPath);
  3157. StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
  3158. llvm::sys::path::append(TempPath, OutputFileName);
  3159. NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
  3160. }
  3161. // If we're saving temps and the temp file conflicts with the input file,
  3162. // then avoid overwriting input file.
  3163. if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
  3164. bool SameFile = false;
  3165. SmallString<256> Result;
  3166. llvm::sys::fs::current_path(Result);
  3167. llvm::sys::path::append(Result, BaseName);
  3168. llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
  3169. // Must share the same path to conflict.
  3170. if (SameFile) {
  3171. StringRef Name = llvm::sys::path::filename(BaseInput);
  3172. std::pair<StringRef, StringRef> Split = Name.split('.');
  3173. std::string TmpName = GetTemporaryPath(
  3174. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  3175. return C.addTempFile(C.getArgs().MakeArgString(TmpName));
  3176. }
  3177. }
  3178. // As an annoying special case, PCH generation doesn't strip the pathname.
  3179. if (JA.getType() == types::TY_PCH && !IsCLMode()) {
  3180. llvm::sys::path::remove_filename(BasePath);
  3181. if (BasePath.empty())
  3182. BasePath = NamedOutput;
  3183. else
  3184. llvm::sys::path::append(BasePath, NamedOutput);
  3185. return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
  3186. } else {
  3187. return C.addResultFile(NamedOutput, &JA);
  3188. }
  3189. }
  3190. std::string Driver::GetFilePath(StringRef Name, const ToolChain &TC) const {
  3191. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  3192. // attempting to use this prefix when looking for file paths.
  3193. for (const std::string &Dir : PrefixDirs) {
  3194. if (Dir.empty())
  3195. continue;
  3196. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  3197. llvm::sys::path::append(P, Name);
  3198. if (llvm::sys::fs::exists(Twine(P)))
  3199. return P.str();
  3200. }
  3201. SmallString<128> R(ResourceDir);
  3202. llvm::sys::path::append(R, Name);
  3203. if (llvm::sys::fs::exists(Twine(R)))
  3204. return R.str();
  3205. SmallString<128> P(TC.getCompilerRTPath());
  3206. llvm::sys::path::append(P, Name);
  3207. if (llvm::sys::fs::exists(Twine(P)))
  3208. return P.str();
  3209. for (const std::string &Dir : TC.getFilePaths()) {
  3210. if (Dir.empty())
  3211. continue;
  3212. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  3213. llvm::sys::path::append(P, Name);
  3214. if (llvm::sys::fs::exists(Twine(P)))
  3215. return P.str();
  3216. }
  3217. return Name;
  3218. }
  3219. void Driver::generatePrefixedToolNames(
  3220. StringRef Tool, const ToolChain &TC,
  3221. SmallVectorImpl<std::string> &Names) const {
  3222. // FIXME: Needs a better variable than DefaultTargetTriple
  3223. Names.emplace_back((DefaultTargetTriple + "-" + Tool).str());
  3224. Names.emplace_back(Tool);
  3225. // Allow the discovery of tools prefixed with LLVM's default target triple.
  3226. std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
  3227. if (LLVMDefaultTargetTriple != DefaultTargetTriple)
  3228. Names.emplace_back((LLVMDefaultTargetTriple + "-" + Tool).str());
  3229. }
  3230. static bool ScanDirForExecutable(SmallString<128> &Dir,
  3231. ArrayRef<std::string> Names) {
  3232. for (const auto &Name : Names) {
  3233. llvm::sys::path::append(Dir, Name);
  3234. if (llvm::sys::fs::can_execute(Twine(Dir)))
  3235. return true;
  3236. llvm::sys::path::remove_filename(Dir);
  3237. }
  3238. return false;
  3239. }
  3240. std::string Driver::GetProgramPath(StringRef Name, const ToolChain &TC) const {
  3241. SmallVector<std::string, 2> TargetSpecificExecutables;
  3242. generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
  3243. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  3244. // attempting to use this prefix when looking for program paths.
  3245. for (const auto &PrefixDir : PrefixDirs) {
  3246. if (llvm::sys::fs::is_directory(PrefixDir)) {
  3247. SmallString<128> P(PrefixDir);
  3248. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  3249. return P.str();
  3250. } else {
  3251. SmallString<128> P((PrefixDir + Name).str());
  3252. if (llvm::sys::fs::can_execute(Twine(P)))
  3253. return P.str();
  3254. }
  3255. }
  3256. const ToolChain::path_list &List = TC.getProgramPaths();
  3257. for (const auto &Path : List) {
  3258. SmallString<128> P(Path);
  3259. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  3260. return P.str();
  3261. }
  3262. // If all else failed, search the path.
  3263. for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
  3264. if (llvm::ErrorOr<std::string> P =
  3265. llvm::sys::findProgramByName(TargetSpecificExecutable))
  3266. return *P;
  3267. return Name;
  3268. }
  3269. std::string Driver::GetTemporaryPath(StringRef Prefix, StringRef Suffix) const {
  3270. SmallString<128> Path;
  3271. std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
  3272. if (EC) {
  3273. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  3274. return "";
  3275. }
  3276. return Path.str();
  3277. }
  3278. std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
  3279. SmallString<128> Output;
  3280. if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
  3281. // FIXME: If anybody needs it, implement this obscure rule:
  3282. // "If you specify a directory without a file name, the default file name
  3283. // is VCx0.pch., where x is the major version of Visual C++ in use."
  3284. Output = FpArg->getValue();
  3285. // "If you do not specify an extension as part of the path name, an
  3286. // extension of .pch is assumed. "
  3287. if (!llvm::sys::path::has_extension(Output))
  3288. Output += ".pch";
  3289. } else {
  3290. Output = BaseName;
  3291. llvm::sys::path::replace_extension(Output, ".pch");
  3292. }
  3293. return Output.str();
  3294. }
  3295. const ToolChain &Driver::getToolChain(const ArgList &Args,
  3296. const llvm::Triple &Target) const {
  3297. auto &TC = ToolChains[Target.str()];
  3298. if (!TC) {
  3299. switch (Target.getOS()) {
  3300. case llvm::Triple::Haiku:
  3301. TC = llvm::make_unique<toolchains::Haiku>(*this, Target, Args);
  3302. break;
  3303. case llvm::Triple::Ananas:
  3304. TC = llvm::make_unique<toolchains::Ananas>(*this, Target, Args);
  3305. break;
  3306. case llvm::Triple::CloudABI:
  3307. TC = llvm::make_unique<toolchains::CloudABI>(*this, Target, Args);
  3308. break;
  3309. case llvm::Triple::Darwin:
  3310. case llvm::Triple::MacOSX:
  3311. case llvm::Triple::IOS:
  3312. case llvm::Triple::TvOS:
  3313. case llvm::Triple::WatchOS:
  3314. TC = llvm::make_unique<toolchains::DarwinClang>(*this, Target, Args);
  3315. break;
  3316. case llvm::Triple::DragonFly:
  3317. TC = llvm::make_unique<toolchains::DragonFly>(*this, Target, Args);
  3318. break;
  3319. case llvm::Triple::OpenBSD:
  3320. TC = llvm::make_unique<toolchains::OpenBSD>(*this, Target, Args);
  3321. break;
  3322. case llvm::Triple::NetBSD:
  3323. TC = llvm::make_unique<toolchains::NetBSD>(*this, Target, Args);
  3324. break;
  3325. case llvm::Triple::FreeBSD:
  3326. TC = llvm::make_unique<toolchains::FreeBSD>(*this, Target, Args);
  3327. break;
  3328. case llvm::Triple::Minix:
  3329. TC = llvm::make_unique<toolchains::Minix>(*this, Target, Args);
  3330. break;
  3331. case llvm::Triple::Linux:
  3332. case llvm::Triple::ELFIAMCU:
  3333. if (Target.getArch() == llvm::Triple::hexagon)
  3334. TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
  3335. Args);
  3336. else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
  3337. !Target.hasEnvironment())
  3338. TC = llvm::make_unique<toolchains::MipsLLVMToolChain>(*this, Target,
  3339. Args);
  3340. else
  3341. TC = llvm::make_unique<toolchains::Linux>(*this, Target, Args);
  3342. break;
  3343. case llvm::Triple::NaCl:
  3344. TC = llvm::make_unique<toolchains::NaClToolChain>(*this, Target, Args);
  3345. break;
  3346. case llvm::Triple::Fuchsia:
  3347. TC = llvm::make_unique<toolchains::Fuchsia>(*this, Target, Args);
  3348. break;
  3349. case llvm::Triple::Solaris:
  3350. TC = llvm::make_unique<toolchains::Solaris>(*this, Target, Args);
  3351. break;
  3352. case llvm::Triple::AMDHSA:
  3353. TC = llvm::make_unique<toolchains::AMDGPUToolChain>(*this, Target, Args);
  3354. break;
  3355. case llvm::Triple::Win32:
  3356. switch (Target.getEnvironment()) {
  3357. default:
  3358. if (Target.isOSBinFormatELF())
  3359. TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
  3360. else if (Target.isOSBinFormatMachO())
  3361. TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
  3362. else
  3363. TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
  3364. break;
  3365. case llvm::Triple::GNU:
  3366. TC = llvm::make_unique<toolchains::MinGW>(*this, Target, Args);
  3367. break;
  3368. case llvm::Triple::Itanium:
  3369. TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(*this, Target,
  3370. Args);
  3371. break;
  3372. case llvm::Triple::MSVC:
  3373. case llvm::Triple::UnknownEnvironment:
  3374. if (Args.getLastArgValue(options::OPT_fuse_ld_EQ)
  3375. .startswith_lower("bfd"))
  3376. TC = llvm::make_unique<toolchains::CrossWindowsToolChain>(
  3377. *this, Target, Args);
  3378. else
  3379. TC =
  3380. llvm::make_unique<toolchains::MSVCToolChain>(*this, Target, Args);
  3381. break;
  3382. }
  3383. break;
  3384. case llvm::Triple::PS4:
  3385. TC = llvm::make_unique<toolchains::PS4CPU>(*this, Target, Args);
  3386. break;
  3387. case llvm::Triple::Contiki:
  3388. TC = llvm::make_unique<toolchains::Contiki>(*this, Target, Args);
  3389. break;
  3390. default:
  3391. // Of these targets, Hexagon is the only one that might have
  3392. // an OS of Linux, in which case it got handled above already.
  3393. switch (Target.getArch()) {
  3394. case llvm::Triple::tce:
  3395. TC = llvm::make_unique<toolchains::TCEToolChain>(*this, Target, Args);
  3396. break;
  3397. case llvm::Triple::tcele:
  3398. TC = llvm::make_unique<toolchains::TCELEToolChain>(*this, Target, Args);
  3399. break;
  3400. case llvm::Triple::hexagon:
  3401. TC = llvm::make_unique<toolchains::HexagonToolChain>(*this, Target,
  3402. Args);
  3403. break;
  3404. case llvm::Triple::lanai:
  3405. TC = llvm::make_unique<toolchains::LanaiToolChain>(*this, Target, Args);
  3406. break;
  3407. case llvm::Triple::xcore:
  3408. TC = llvm::make_unique<toolchains::XCoreToolChain>(*this, Target, Args);
  3409. break;
  3410. case llvm::Triple::wasm32:
  3411. case llvm::Triple::wasm64:
  3412. TC = llvm::make_unique<toolchains::WebAssembly>(*this, Target, Args);
  3413. break;
  3414. case llvm::Triple::avr:
  3415. TC = llvm::make_unique<toolchains::AVRToolChain>(*this, Target, Args);
  3416. break;
  3417. default:
  3418. if (Target.getVendor() == llvm::Triple::Myriad)
  3419. TC = llvm::make_unique<toolchains::MyriadToolChain>(*this, Target,
  3420. Args);
  3421. else if (toolchains::BareMetal::handlesTarget(Target))
  3422. TC = llvm::make_unique<toolchains::BareMetal>(*this, Target, Args);
  3423. else if (Target.isOSBinFormatELF())
  3424. TC = llvm::make_unique<toolchains::Generic_ELF>(*this, Target, Args);
  3425. else if (Target.isOSBinFormatMachO())
  3426. TC = llvm::make_unique<toolchains::MachO>(*this, Target, Args);
  3427. else
  3428. TC = llvm::make_unique<toolchains::Generic_GCC>(*this, Target, Args);
  3429. }
  3430. }
  3431. }
  3432. // Intentionally omitted from the switch above: llvm::Triple::CUDA. CUDA
  3433. // compiles always need two toolchains, the CUDA toolchain and the host
  3434. // toolchain. So the only valid way to create a CUDA toolchain is via
  3435. // CreateOffloadingDeviceToolChains.
  3436. return *TC;
  3437. }
  3438. bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
  3439. // Say "no" if there is not exactly one input of a type clang understands.
  3440. if (JA.size() != 1 ||
  3441. !types::isAcceptedByClang((*JA.input_begin())->getType()))
  3442. return false;
  3443. // And say "no" if this is not a kind of action clang understands.
  3444. if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
  3445. !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  3446. return false;
  3447. return true;
  3448. }
  3449. /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
  3450. /// grouped values as integers. Numbers which are not provided are set to 0.
  3451. ///
  3452. /// \return True if the entire string was parsed (9.2), or all groups were
  3453. /// parsed (10.3.5extrastuff).
  3454. bool Driver::GetReleaseVersion(StringRef Str, unsigned &Major, unsigned &Minor,
  3455. unsigned &Micro, bool &HadExtra) {
  3456. HadExtra = false;
  3457. Major = Minor = Micro = 0;
  3458. if (Str.empty())
  3459. return false;
  3460. if (Str.consumeInteger(10, Major))
  3461. return false;
  3462. if (Str.empty())
  3463. return true;
  3464. if (Str[0] != '.')
  3465. return false;
  3466. Str = Str.drop_front(1);
  3467. if (Str.consumeInteger(10, Minor))
  3468. return false;
  3469. if (Str.empty())
  3470. return true;
  3471. if (Str[0] != '.')
  3472. return false;
  3473. Str = Str.drop_front(1);
  3474. if (Str.consumeInteger(10, Micro))
  3475. return false;
  3476. if (!Str.empty())
  3477. HadExtra = true;
  3478. return true;
  3479. }
  3480. /// Parse digits from a string \p Str and fulfill \p Digits with
  3481. /// the parsed numbers. This method assumes that the max number of
  3482. /// digits to look for is equal to Digits.size().
  3483. ///
  3484. /// \return True if the entire string was parsed and there are
  3485. /// no extra characters remaining at the end.
  3486. bool Driver::GetReleaseVersion(StringRef Str,
  3487. MutableArrayRef<unsigned> Digits) {
  3488. if (Str.empty())
  3489. return false;
  3490. unsigned CurDigit = 0;
  3491. while (CurDigit < Digits.size()) {
  3492. unsigned Digit;
  3493. if (Str.consumeInteger(10, Digit))
  3494. return false;
  3495. Digits[CurDigit] = Digit;
  3496. if (Str.empty())
  3497. return true;
  3498. if (Str[0] != '.')
  3499. return false;
  3500. Str = Str.drop_front(1);
  3501. CurDigit++;
  3502. }
  3503. // More digits than requested, bail out...
  3504. return false;
  3505. }
  3506. std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
  3507. unsigned IncludedFlagsBitmask = 0;
  3508. unsigned ExcludedFlagsBitmask = options::NoDriverOption;
  3509. if (Mode == CLMode) {
  3510. // Include CL and Core options.
  3511. IncludedFlagsBitmask |= options::CLOption;
  3512. IncludedFlagsBitmask |= options::CoreOption;
  3513. } else {
  3514. ExcludedFlagsBitmask |= options::CLOption;
  3515. }
  3516. return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
  3517. }
  3518. bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
  3519. return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
  3520. }