Driver.cpp 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646
  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.h"
  12. #include "clang/Basic/Version.h"
  13. #include "clang/Basic/VirtualFileSystem.h"
  14. #include "clang/Config/config.h"
  15. #include "clang/Driver/Action.h"
  16. #include "clang/Driver/Compilation.h"
  17. #include "clang/Driver/DriverDiagnostic.h"
  18. #include "clang/Driver/Job.h"
  19. #include "clang/Driver/Options.h"
  20. #include "clang/Driver/SanitizerArgs.h"
  21. #include "clang/Driver/Tool.h"
  22. #include "clang/Driver/ToolChain.h"
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/StringExtras.h"
  26. #include "llvm/ADT/StringSet.h"
  27. #include "llvm/ADT/StringSwitch.h"
  28. #include "llvm/Option/Arg.h"
  29. #include "llvm/Option/ArgList.h"
  30. #include "llvm/Option/OptSpecifier.h"
  31. #include "llvm/Option/OptTable.h"
  32. #include "llvm/Option/Option.h"
  33. #include "llvm/Support/Debug.h"
  34. #include "llvm/Support/ErrorHandling.h"
  35. #include "llvm/Support/FileSystem.h"
  36. #include "llvm/Support/Path.h"
  37. #include "llvm/Support/PrettyStackTrace.h"
  38. #include "llvm/Support/Process.h"
  39. #include "llvm/Support/Program.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <map>
  42. #include <memory>
  43. using namespace clang::driver;
  44. using namespace clang;
  45. using namespace llvm::opt;
  46. Driver::Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple,
  47. DiagnosticsEngine &Diags,
  48. IntrusiveRefCntPtr<vfs::FileSystem> VFS)
  49. : Opts(createDriverOptTable()), Diags(Diags), VFS(VFS), Mode(GCCMode),
  50. SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone), LTOMode(LTOK_None),
  51. ClangExecutable(ClangExecutable),
  52. SysRoot(DEFAULT_SYSROOT), UseStdLib(true),
  53. DefaultTargetTriple(DefaultTargetTriple),
  54. DriverTitle("clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
  55. CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
  56. CCCPrintBindings(false), CCPrintHeaders(false), CCLogDiagnostics(false),
  57. CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
  58. CCCUsePCH(true), SuppressMissingInputWarning(false) {
  59. // Provide a sane fallback if no VFS is specified.
  60. if (!this->VFS)
  61. this->VFS = vfs::getRealFileSystem();
  62. Name = llvm::sys::path::filename(ClangExecutable);
  63. Dir = llvm::sys::path::parent_path(ClangExecutable);
  64. InstalledDir = Dir; // Provide a sensible default installed dir.
  65. // Compute the path to the resource directory.
  66. StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
  67. SmallString<128> P(Dir);
  68. if (ClangResourceDir != "") {
  69. llvm::sys::path::append(P, ClangResourceDir);
  70. } else {
  71. StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
  72. llvm::sys::path::append(P, "..", Twine("lib") + ClangLibdirSuffix, "clang",
  73. CLANG_VERSION_STRING);
  74. }
  75. ResourceDir = P.str();
  76. }
  77. Driver::~Driver() {
  78. delete Opts;
  79. llvm::DeleteContainerSeconds(ToolChains);
  80. }
  81. void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
  82. const std::string OptName =
  83. getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
  84. for (const char *ArgPtr : Args) {
  85. // Ingore nullptrs, they are response file's EOL markers
  86. if (ArgPtr == nullptr)
  87. continue;
  88. const StringRef Arg = ArgPtr;
  89. if (!Arg.startswith(OptName))
  90. continue;
  91. const StringRef Value = Arg.drop_front(OptName.size());
  92. const unsigned M = llvm::StringSwitch<unsigned>(Value)
  93. .Case("gcc", GCCMode)
  94. .Case("g++", GXXMode)
  95. .Case("cpp", CPPMode)
  96. .Case("cl", CLMode)
  97. .Default(~0U);
  98. if (M != ~0U)
  99. Mode = static_cast<DriverMode>(M);
  100. else
  101. Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
  102. }
  103. }
  104. InputArgList Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
  105. llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
  106. unsigned IncludedFlagsBitmask;
  107. unsigned ExcludedFlagsBitmask;
  108. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  109. getIncludeExcludeOptionFlagMasks();
  110. unsigned MissingArgIndex, MissingArgCount;
  111. InputArgList Args =
  112. getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
  113. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  114. // Check for missing argument error.
  115. if (MissingArgCount)
  116. Diag(clang::diag::err_drv_missing_argument)
  117. << Args.getArgString(MissingArgIndex) << MissingArgCount;
  118. // Check for unsupported options.
  119. for (const Arg *A : Args) {
  120. if (A->getOption().hasFlag(options::Unsupported)) {
  121. Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
  122. continue;
  123. }
  124. // Warn about -mcpu= without an argument.
  125. if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue("")) {
  126. Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
  127. }
  128. }
  129. for (const Arg *A : Args.filtered(options::OPT_UNKNOWN))
  130. Diags.Report(IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
  131. diag::err_drv_unknown_argument)
  132. << A->getAsString(Args);
  133. return Args;
  134. }
  135. // Determine which compilation mode we are in. We look for options which
  136. // affect the phase, starting with the earliest phases, and record which
  137. // option we used to determine the final phase.
  138. phases::ID Driver::getFinalPhase(const DerivedArgList &DAL,
  139. Arg **FinalPhaseArg) const {
  140. Arg *PhaseArg = nullptr;
  141. phases::ID FinalPhase;
  142. // -{E,EP,P,M,MM} only run the preprocessor.
  143. if (CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
  144. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
  145. (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
  146. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
  147. FinalPhase = phases::Preprocess;
  148. // -{fsyntax-only,-analyze,emit-ast} only run up to the compiler.
  149. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
  150. (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
  151. (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
  152. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
  153. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
  154. (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
  155. (PhaseArg = DAL.getLastArg(options::OPT__analyze,
  156. options::OPT__analyze_auto)) ||
  157. (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
  158. FinalPhase = phases::Compile;
  159. // -S only runs up to the backend.
  160. } else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
  161. FinalPhase = phases::Backend;
  162. // -c compilation only runs up to the assembler.
  163. } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
  164. FinalPhase = phases::Assemble;
  165. // Otherwise do everything.
  166. } else
  167. FinalPhase = phases::Link;
  168. if (FinalPhaseArg)
  169. *FinalPhaseArg = PhaseArg;
  170. return FinalPhase;
  171. }
  172. static Arg *MakeInputArg(DerivedArgList &Args, OptTable *Opts,
  173. StringRef Value) {
  174. Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
  175. Args.getBaseArgs().MakeIndex(Value), Value.data());
  176. Args.AddSynthesizedArg(A);
  177. A->claim();
  178. return A;
  179. }
  180. DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
  181. DerivedArgList *DAL = new DerivedArgList(Args);
  182. bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
  183. bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
  184. for (Arg *A : Args) {
  185. // Unfortunately, we have to parse some forwarding options (-Xassembler,
  186. // -Xlinker, -Xpreprocessor) because we either integrate their functionality
  187. // (assembler and preprocessor), or bypass a previous driver ('collect2').
  188. // Rewrite linker options, to replace --no-demangle with a custom internal
  189. // option.
  190. if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
  191. A->getOption().matches(options::OPT_Xlinker)) &&
  192. A->containsValue("--no-demangle")) {
  193. // Add the rewritten no-demangle argument.
  194. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
  195. // Add the remaining values as Xlinker arguments.
  196. for (StringRef Val : A->getValues())
  197. if (Val != "--no-demangle")
  198. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
  199. continue;
  200. }
  201. // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
  202. // some build systems. We don't try to be complete here because we don't
  203. // care to encourage this usage model.
  204. if (A->getOption().matches(options::OPT_Wp_COMMA) &&
  205. (A->getValue(0) == StringRef("-MD") ||
  206. A->getValue(0) == StringRef("-MMD"))) {
  207. // Rewrite to -MD/-MMD along with -MF.
  208. if (A->getValue(0) == StringRef("-MD"))
  209. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
  210. else
  211. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
  212. if (A->getNumValues() == 2)
  213. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
  214. A->getValue(1));
  215. continue;
  216. }
  217. // Rewrite reserved library names.
  218. if (A->getOption().matches(options::OPT_l)) {
  219. StringRef Value = A->getValue();
  220. // Rewrite unless -nostdlib is present.
  221. if (!HasNostdlib && !HasNodefaultlib && Value == "stdc++") {
  222. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
  223. continue;
  224. }
  225. // Rewrite unconditionally.
  226. if (Value == "cc_kext") {
  227. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
  228. continue;
  229. }
  230. }
  231. // Pick up inputs via the -- option.
  232. if (A->getOption().matches(options::OPT__DASH_DASH)) {
  233. A->claim();
  234. for (StringRef Val : A->getValues())
  235. DAL->append(MakeInputArg(*DAL, Opts, Val));
  236. continue;
  237. }
  238. DAL->append(A);
  239. }
  240. // Enforce -static if -miamcu is present.
  241. if (Args.hasArg(options::OPT_miamcu))
  242. DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
  243. // Add a default value of -mlinker-version=, if one was given and the user
  244. // didn't specify one.
  245. #if defined(HOST_LINK_VERSION)
  246. if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
  247. strlen(HOST_LINK_VERSION) > 0) {
  248. DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
  249. HOST_LINK_VERSION);
  250. DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
  251. }
  252. #endif
  253. return DAL;
  254. }
  255. /// \brief Compute target triple from args.
  256. ///
  257. /// This routine provides the logic to compute a target triple from various
  258. /// args passed to the driver and the default triple string.
  259. static llvm::Triple computeTargetTriple(const Driver &D,
  260. StringRef DefaultTargetTriple,
  261. const ArgList &Args,
  262. StringRef DarwinArchName = "") {
  263. // FIXME: Already done in Compilation *Driver::BuildCompilation
  264. if (const Arg *A = Args.getLastArg(options::OPT_target))
  265. DefaultTargetTriple = A->getValue();
  266. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  267. // Handle Apple-specific options available here.
  268. if (Target.isOSBinFormatMachO()) {
  269. // If an explict Darwin arch name is given, that trumps all.
  270. if (!DarwinArchName.empty()) {
  271. tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
  272. return Target;
  273. }
  274. // Handle the Darwin '-arch' flag.
  275. if (Arg *A = Args.getLastArg(options::OPT_arch)) {
  276. StringRef ArchName = A->getValue();
  277. tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
  278. }
  279. }
  280. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  281. // '-mbig-endian'/'-EB'.
  282. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  283. options::OPT_mbig_endian)) {
  284. if (A->getOption().matches(options::OPT_mlittle_endian)) {
  285. llvm::Triple LE = Target.getLittleEndianArchVariant();
  286. if (LE.getArch() != llvm::Triple::UnknownArch)
  287. Target = std::move(LE);
  288. } else {
  289. llvm::Triple BE = Target.getBigEndianArchVariant();
  290. if (BE.getArch() != llvm::Triple::UnknownArch)
  291. Target = std::move(BE);
  292. }
  293. }
  294. // Skip further flag support on OSes which don't support '-m32' or '-m64'.
  295. if (Target.getArch() == llvm::Triple::tce ||
  296. Target.getOS() == llvm::Triple::Minix)
  297. return Target;
  298. // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
  299. Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
  300. options::OPT_m32, options::OPT_m16);
  301. if (A) {
  302. llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
  303. if (A->getOption().matches(options::OPT_m64)) {
  304. AT = Target.get64BitArchVariant().getArch();
  305. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  306. Target.setEnvironment(llvm::Triple::GNU);
  307. } else if (A->getOption().matches(options::OPT_mx32) &&
  308. Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
  309. AT = llvm::Triple::x86_64;
  310. Target.setEnvironment(llvm::Triple::GNUX32);
  311. } else if (A->getOption().matches(options::OPT_m32)) {
  312. AT = Target.get32BitArchVariant().getArch();
  313. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  314. Target.setEnvironment(llvm::Triple::GNU);
  315. } else if (A->getOption().matches(options::OPT_m16) &&
  316. Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
  317. AT = llvm::Triple::x86;
  318. Target.setEnvironment(llvm::Triple::CODE16);
  319. }
  320. if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
  321. Target.setArch(AT);
  322. }
  323. // Handle -miamcu flag.
  324. if (Args.hasArg(options::OPT_miamcu)) {
  325. if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
  326. D.Diag(diag::err_drv_unsupported_opt_for_target) << "-miamcu"
  327. << Target.str();
  328. if (A && !A->getOption().matches(options::OPT_m32))
  329. D.Diag(diag::err_drv_argument_not_allowed_with)
  330. << "-miamcu" << A->getBaseArg().getAsString(Args);
  331. Target.setArch(llvm::Triple::x86);
  332. Target.setArchName("i586");
  333. Target.setEnvironment(llvm::Triple::UnknownEnvironment);
  334. Target.setEnvironmentName("");
  335. Target.setOS(llvm::Triple::ELFIAMCU);
  336. Target.setVendor(llvm::Triple::UnknownVendor);
  337. Target.setVendorName("intel");
  338. }
  339. return Target;
  340. }
  341. // \brief Parse the LTO options and record the type of LTO compilation
  342. // based on which -f(no-)?lto(=.*)? option occurs last.
  343. void Driver::setLTOMode(const llvm::opt::ArgList &Args) {
  344. LTOMode = LTOK_None;
  345. if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
  346. options::OPT_fno_lto, false))
  347. return;
  348. StringRef LTOName("full");
  349. const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
  350. if (A)
  351. LTOName = A->getValue();
  352. LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
  353. .Case("full", LTOK_Full)
  354. .Case("thin", LTOK_Thin)
  355. .Default(LTOK_Unknown);
  356. if (LTOMode == LTOK_Unknown) {
  357. assert(A);
  358. Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
  359. << A->getValue();
  360. }
  361. }
  362. Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
  363. llvm::PrettyStackTraceString CrashInfo("Compilation construction");
  364. // FIXME: Handle environment options which affect driver behavior, somewhere
  365. // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
  366. if (char *env = ::getenv("COMPILER_PATH")) {
  367. StringRef CompilerPath = env;
  368. while (!CompilerPath.empty()) {
  369. std::pair<StringRef, StringRef> Split =
  370. CompilerPath.split(llvm::sys::EnvPathSeparator);
  371. PrefixDirs.push_back(Split.first);
  372. CompilerPath = Split.second;
  373. }
  374. }
  375. // We look for the driver mode option early, because the mode can affect
  376. // how other options are parsed.
  377. ParseDriverMode(ArgList.slice(1));
  378. // FIXME: What are we going to do with -V and -b?
  379. // FIXME: This stuff needs to go into the Compilation, not the driver.
  380. bool CCCPrintPhases;
  381. InputArgList Args = ParseArgStrings(ArgList.slice(1));
  382. // Silence driver warnings if requested
  383. Diags.setIgnoreAllWarnings(Args.hasArg(options::OPT_w));
  384. // -no-canonical-prefixes is used very early in main.
  385. Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
  386. // Ignore -pipe.
  387. Args.ClaimAllArgs(options::OPT_pipe);
  388. // Extract -ccc args.
  389. //
  390. // FIXME: We need to figure out where this behavior should live. Most of it
  391. // should be outside in the client; the parts that aren't should have proper
  392. // options, either by introducing new ones or by overloading gcc ones like -V
  393. // or -b.
  394. CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
  395. CCCPrintBindings = Args.hasArg(options::OPT_ccc_print_bindings);
  396. if (const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
  397. CCCGenericGCCName = A->getValue();
  398. CCCUsePCH =
  399. Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
  400. // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
  401. // and getToolChain is const.
  402. if (IsCLMode()) {
  403. // clang-cl targets MSVC-style Win32.
  404. llvm::Triple T(DefaultTargetTriple);
  405. T.setOS(llvm::Triple::Win32);
  406. T.setVendor(llvm::Triple::PC);
  407. T.setEnvironment(llvm::Triple::MSVC);
  408. DefaultTargetTriple = T.str();
  409. }
  410. if (const Arg *A = Args.getLastArg(options::OPT_target))
  411. DefaultTargetTriple = A->getValue();
  412. if (const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
  413. Dir = InstalledDir = A->getValue();
  414. for (const Arg *A : Args.filtered(options::OPT_B)) {
  415. A->claim();
  416. PrefixDirs.push_back(A->getValue(0));
  417. }
  418. if (const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
  419. SysRoot = A->getValue();
  420. if (const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
  421. DyldPrefix = A->getValue();
  422. if (Args.hasArg(options::OPT_nostdlib))
  423. UseStdLib = false;
  424. if (const Arg *A = Args.getLastArg(options::OPT_resource_dir))
  425. ResourceDir = A->getValue();
  426. if (const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
  427. SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
  428. .Case("cwd", SaveTempsCwd)
  429. .Case("obj", SaveTempsObj)
  430. .Default(SaveTempsCwd);
  431. }
  432. // Ignore -fembed-bitcode options with LTO
  433. // since the output will be bitcode anyway.
  434. if (!Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false)) {
  435. if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
  436. StringRef Name = A->getValue();
  437. unsigned Model = llvm::StringSwitch<unsigned>(Name)
  438. .Case("off", EmbedNone)
  439. .Case("all", EmbedBitcode)
  440. .Case("bitcode", EmbedBitcode)
  441. .Case("marker", EmbedMarker)
  442. .Default(~0U);
  443. if (Model == ~0U) {
  444. Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args)
  445. << Name;
  446. } else
  447. BitcodeEmbed = static_cast<BitcodeEmbedMode>(Model);
  448. }
  449. } else {
  450. // claim the bitcode option under LTO so no warning is issued.
  451. Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
  452. }
  453. setLTOMode(Args);
  454. std::unique_ptr<llvm::opt::InputArgList> UArgs =
  455. llvm::make_unique<InputArgList>(std::move(Args));
  456. // Perform the default argument translations.
  457. DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
  458. // Owned by the host.
  459. const ToolChain &TC = getToolChain(
  460. *UArgs, computeTargetTriple(*this, DefaultTargetTriple, *UArgs));
  461. // The compilation takes ownership of Args.
  462. Compilation *C = new Compilation(*this, TC, UArgs.release(), TranslatedArgs);
  463. if (!HandleImmediateArgs(*C))
  464. return C;
  465. // Construct the list of inputs.
  466. InputList Inputs;
  467. BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
  468. // Initialize the CUDA device TC only if we have any CUDA Inputs. This is
  469. // necessary so that we don't break compilations that pass flags that are
  470. // incompatible with the NVPTX TC (e.g. -mthread-model single).
  471. if (llvm::any_of(Inputs, [](const std::pair<types::ID, const Arg *> &I) {
  472. return I.first == types::TY_CUDA || I.first == types::TY_PP_CUDA ||
  473. I.first == types::TY_CUDA_DEVICE;
  474. })) {
  475. C->setCudaDeviceToolChain(
  476. &getToolChain(C->getArgs(), llvm::Triple(TC.getTriple().isArch64Bit()
  477. ? "nvptx64-nvidia-cuda"
  478. : "nvptx-nvidia-cuda")));
  479. }
  480. // Construct the list of abstract actions to perform for this compilation. On
  481. // MachO targets this uses the driver-driver and universal actions.
  482. if (TC.getTriple().isOSBinFormatMachO())
  483. BuildUniversalActions(*C, C->getDefaultToolChain(), Inputs);
  484. else
  485. BuildActions(*C, C->getArgs(), Inputs, C->getActions());
  486. if (CCCPrintPhases) {
  487. PrintActions(*C);
  488. return C;
  489. }
  490. BuildJobs(*C);
  491. return C;
  492. }
  493. static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args) {
  494. llvm::opt::ArgStringList ASL;
  495. for (const auto *A : Args)
  496. A->render(Args, ASL);
  497. for (auto I = ASL.begin(), E = ASL.end(); I != E; ++I) {
  498. if (I != ASL.begin())
  499. OS << ' ';
  500. Command::printArg(OS, *I, true);
  501. }
  502. OS << '\n';
  503. }
  504. // When clang crashes, produce diagnostic information including the fully
  505. // preprocessed source file(s). Request that the developer attach the
  506. // diagnostic information to a bug report.
  507. void Driver::generateCompilationDiagnostics(Compilation &C,
  508. const Command &FailingCommand) {
  509. if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
  510. return;
  511. // Don't try to generate diagnostics for link or dsymutil jobs.
  512. if (FailingCommand.getCreator().isLinkJob() ||
  513. FailingCommand.getCreator().isDsymutilJob())
  514. return;
  515. // Print the version of the compiler.
  516. PrintVersion(C, llvm::errs());
  517. Diag(clang::diag::note_drv_command_failed_diag_msg)
  518. << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
  519. "crash backtrace, preprocessed source, and associated run script.";
  520. // Suppress driver output and emit preprocessor output to temp file.
  521. Mode = CPPMode;
  522. CCGenDiagnostics = true;
  523. // Save the original job command(s).
  524. Command Cmd = FailingCommand;
  525. // Keep track of whether we produce any errors while trying to produce
  526. // preprocessed sources.
  527. DiagnosticErrorTrap Trap(Diags);
  528. // Suppress tool output.
  529. C.initCompilationForDiagnostics();
  530. // Construct the list of inputs.
  531. InputList Inputs;
  532. BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
  533. for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
  534. bool IgnoreInput = false;
  535. // Ignore input from stdin or any inputs that cannot be preprocessed.
  536. // Check type first as not all linker inputs have a value.
  537. if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
  538. IgnoreInput = true;
  539. } else if (!strcmp(it->second->getValue(), "-")) {
  540. Diag(clang::diag::note_drv_command_failed_diag_msg)
  541. << "Error generating preprocessed source(s) - "
  542. "ignoring input from stdin.";
  543. IgnoreInput = true;
  544. }
  545. if (IgnoreInput) {
  546. it = Inputs.erase(it);
  547. ie = Inputs.end();
  548. } else {
  549. ++it;
  550. }
  551. }
  552. if (Inputs.empty()) {
  553. Diag(clang::diag::note_drv_command_failed_diag_msg)
  554. << "Error generating preprocessed source(s) - "
  555. "no preprocessable inputs.";
  556. return;
  557. }
  558. // Don't attempt to generate preprocessed files if multiple -arch options are
  559. // used, unless they're all duplicates.
  560. llvm::StringSet<> ArchNames;
  561. for (const Arg *A : C.getArgs()) {
  562. if (A->getOption().matches(options::OPT_arch)) {
  563. StringRef ArchName = A->getValue();
  564. ArchNames.insert(ArchName);
  565. }
  566. }
  567. if (ArchNames.size() > 1) {
  568. Diag(clang::diag::note_drv_command_failed_diag_msg)
  569. << "Error generating preprocessed source(s) - cannot generate "
  570. "preprocessed source with multiple -arch options.";
  571. return;
  572. }
  573. // Construct the list of abstract actions to perform for this compilation. On
  574. // Darwin OSes this uses the driver-driver and builds universal actions.
  575. const ToolChain &TC = C.getDefaultToolChain();
  576. if (TC.getTriple().isOSBinFormatMachO())
  577. BuildUniversalActions(C, TC, Inputs);
  578. else
  579. BuildActions(C, C.getArgs(), Inputs, C.getActions());
  580. BuildJobs(C);
  581. // If there were errors building the compilation, quit now.
  582. if (Trap.hasErrorOccurred()) {
  583. Diag(clang::diag::note_drv_command_failed_diag_msg)
  584. << "Error generating preprocessed source(s).";
  585. return;
  586. }
  587. // Generate preprocessed output.
  588. SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
  589. C.ExecuteJobs(C.getJobs(), FailingCommands);
  590. // If any of the preprocessing commands failed, clean up and exit.
  591. if (!FailingCommands.empty()) {
  592. if (!isSaveTempsEnabled())
  593. C.CleanupFileList(C.getTempFiles(), true);
  594. Diag(clang::diag::note_drv_command_failed_diag_msg)
  595. << "Error generating preprocessed source(s).";
  596. return;
  597. }
  598. const ArgStringList &TempFiles = C.getTempFiles();
  599. if (TempFiles.empty()) {
  600. Diag(clang::diag::note_drv_command_failed_diag_msg)
  601. << "Error generating preprocessed source(s).";
  602. return;
  603. }
  604. Diag(clang::diag::note_drv_command_failed_diag_msg)
  605. << "\n********************\n\n"
  606. "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
  607. "Preprocessed source(s) and associated run script(s) are located at:";
  608. SmallString<128> VFS;
  609. for (const char *TempFile : TempFiles) {
  610. Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
  611. if (StringRef(TempFile).endswith(".cache")) {
  612. // In some cases (modules) we'll dump extra data to help with reproducing
  613. // the crash into a directory next to the output.
  614. VFS = llvm::sys::path::filename(TempFile);
  615. llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
  616. }
  617. }
  618. // Assume associated files are based off of the first temporary file.
  619. CrashReportInfo CrashInfo(TempFiles[0], VFS);
  620. std::string Script = CrashInfo.Filename.rsplit('.').first.str() + ".sh";
  621. std::error_code EC;
  622. llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
  623. if (EC) {
  624. Diag(clang::diag::note_drv_command_failed_diag_msg)
  625. << "Error generating run script: " + Script + " " + EC.message();
  626. } else {
  627. ScriptOS << "# Crash reproducer for " << getClangFullVersion() << "\n"
  628. << "# Driver args: ";
  629. printArgList(ScriptOS, C.getInputArgs());
  630. ScriptOS << "# Original command: ";
  631. Cmd.Print(ScriptOS, "\n", /*Quote=*/true);
  632. Cmd.Print(ScriptOS, "\n", /*Quote=*/true, &CrashInfo);
  633. Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
  634. }
  635. for (const auto &A : C.getArgs().filtered(options::OPT_frewrite_map_file,
  636. options::OPT_frewrite_map_file_EQ))
  637. Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
  638. Diag(clang::diag::note_drv_command_failed_diag_msg)
  639. << "\n\n********************";
  640. }
  641. void Driver::setUpResponseFiles(Compilation &C, Command &Cmd) {
  642. // Since commandLineFitsWithinSystemLimits() may underestimate system's capacity
  643. // if the tool does not support response files, there is a chance/ that things
  644. // will just work without a response file, so we silently just skip it.
  645. if (Cmd.getCreator().getResponseFilesSupport() == Tool::RF_None ||
  646. llvm::sys::commandLineFitsWithinSystemLimits(Cmd.getExecutable(), Cmd.getArguments()))
  647. return;
  648. std::string TmpName = GetTemporaryPath("response", "txt");
  649. Cmd.setResponseFile(
  650. C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str())));
  651. }
  652. int Driver::ExecuteCompilation(
  653. Compilation &C,
  654. SmallVectorImpl<std::pair<int, const Command *>> &FailingCommands) {
  655. // Just print if -### was present.
  656. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  657. C.getJobs().Print(llvm::errs(), "\n", true);
  658. return 0;
  659. }
  660. // If there were errors building the compilation, quit now.
  661. if (Diags.hasErrorOccurred())
  662. return 1;
  663. // Set up response file names for each command, if necessary
  664. for (auto &Job : C.getJobs())
  665. setUpResponseFiles(C, Job);
  666. C.ExecuteJobs(C.getJobs(), FailingCommands);
  667. // Remove temp files.
  668. C.CleanupFileList(C.getTempFiles());
  669. // If the command succeeded, we are done.
  670. if (FailingCommands.empty())
  671. return 0;
  672. // Otherwise, remove result files and print extra information about abnormal
  673. // failures.
  674. for (const auto &CmdPair : FailingCommands) {
  675. int Res = CmdPair.first;
  676. const Command *FailingCommand = CmdPair.second;
  677. // Remove result files if we're not saving temps.
  678. if (!isSaveTempsEnabled()) {
  679. const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
  680. C.CleanupFileMap(C.getResultFiles(), JA, true);
  681. // Failure result files are valid unless we crashed.
  682. if (Res < 0)
  683. C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
  684. }
  685. // Print extra information about abnormal failures, if possible.
  686. //
  687. // This is ad-hoc, but we don't want to be excessively noisy. If the result
  688. // status was 1, assume the command failed normally. In particular, if it
  689. // was the compiler then assume it gave a reasonable error code. Failures
  690. // in other tools are less common, and they generally have worse
  691. // diagnostics, so always print the diagnostic there.
  692. const Tool &FailingTool = FailingCommand->getCreator();
  693. if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
  694. // FIXME: See FIXME above regarding result code interpretation.
  695. if (Res < 0)
  696. Diag(clang::diag::err_drv_command_signalled)
  697. << FailingTool.getShortName();
  698. else
  699. Diag(clang::diag::err_drv_command_failed) << FailingTool.getShortName()
  700. << Res;
  701. }
  702. }
  703. return 0;
  704. }
  705. void Driver::PrintHelp(bool ShowHidden) const {
  706. unsigned IncludedFlagsBitmask;
  707. unsigned ExcludedFlagsBitmask;
  708. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  709. getIncludeExcludeOptionFlagMasks();
  710. ExcludedFlagsBitmask |= options::NoDriverOption;
  711. if (!ShowHidden)
  712. ExcludedFlagsBitmask |= HelpHidden;
  713. getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
  714. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  715. }
  716. void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
  717. // FIXME: The following handlers should use a callback mechanism, we don't
  718. // know what the client would like to do.
  719. OS << getClangFullVersion() << '\n';
  720. const ToolChain &TC = C.getDefaultToolChain();
  721. OS << "Target: " << TC.getTripleString() << '\n';
  722. // Print the threading model.
  723. if (Arg *A = C.getArgs().getLastArg(options::OPT_mthread_model)) {
  724. // Don't print if the ToolChain would have barfed on it already
  725. if (TC.isThreadModelSupported(A->getValue()))
  726. OS << "Thread model: " << A->getValue();
  727. } else
  728. OS << "Thread model: " << TC.getThreadModel();
  729. OS << '\n';
  730. // Print out the install directory.
  731. OS << "InstalledDir: " << InstalledDir << '\n';
  732. }
  733. /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
  734. /// option.
  735. static void PrintDiagnosticCategories(raw_ostream &OS) {
  736. // Skip the empty category.
  737. for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories(); i != max;
  738. ++i)
  739. OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
  740. }
  741. bool Driver::HandleImmediateArgs(const Compilation &C) {
  742. // The order these options are handled in gcc is all over the place, but we
  743. // don't expect inconsistencies w.r.t. that to matter in practice.
  744. if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
  745. llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
  746. return false;
  747. }
  748. if (C.getArgs().hasArg(options::OPT_dumpversion)) {
  749. // Since -dumpversion is only implemented for pedantic GCC compatibility, we
  750. // return an answer which matches our definition of __VERSION__.
  751. //
  752. // If we want to return a more correct answer some day, then we should
  753. // introduce a non-pedantically GCC compatible mode to Clang in which we
  754. // provide sensible definitions for -dumpversion, __VERSION__, etc.
  755. llvm::outs() << "4.2.1\n";
  756. return false;
  757. }
  758. if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
  759. PrintDiagnosticCategories(llvm::outs());
  760. return false;
  761. }
  762. if (C.getArgs().hasArg(options::OPT_help) ||
  763. C.getArgs().hasArg(options::OPT__help_hidden)) {
  764. PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
  765. return false;
  766. }
  767. if (C.getArgs().hasArg(options::OPT__version)) {
  768. // Follow gcc behavior and use stdout for --version and stderr for -v.
  769. PrintVersion(C, llvm::outs());
  770. return false;
  771. }
  772. if (C.getArgs().hasArg(options::OPT_v) ||
  773. C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  774. PrintVersion(C, llvm::errs());
  775. SuppressMissingInputWarning = true;
  776. }
  777. const ToolChain &TC = C.getDefaultToolChain();
  778. if (C.getArgs().hasArg(options::OPT_v))
  779. TC.printVerboseInfo(llvm::errs());
  780. if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
  781. llvm::outs() << "programs: =";
  782. bool separator = false;
  783. for (const std::string &Path : TC.getProgramPaths()) {
  784. if (separator)
  785. llvm::outs() << ':';
  786. llvm::outs() << Path;
  787. separator = true;
  788. }
  789. llvm::outs() << "\n";
  790. llvm::outs() << "libraries: =" << ResourceDir;
  791. StringRef sysroot = C.getSysRoot();
  792. for (const std::string &Path : TC.getFilePaths()) {
  793. // Always print a separator. ResourceDir was the first item shown.
  794. llvm::outs() << ':';
  795. // Interpretation of leading '=' is needed only for NetBSD.
  796. if (Path[0] == '=')
  797. llvm::outs() << sysroot << Path.substr(1);
  798. else
  799. llvm::outs() << Path;
  800. }
  801. llvm::outs() << "\n";
  802. return false;
  803. }
  804. // FIXME: The following handlers should use a callback mechanism, we don't
  805. // know what the client would like to do.
  806. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
  807. llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
  808. return false;
  809. }
  810. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
  811. llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
  812. return false;
  813. }
  814. if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
  815. llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
  816. return false;
  817. }
  818. if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
  819. for (const Multilib &Multilib : TC.getMultilibs())
  820. llvm::outs() << Multilib << "\n";
  821. return false;
  822. }
  823. if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
  824. for (const Multilib &Multilib : TC.getMultilibs()) {
  825. if (Multilib.gccSuffix().empty())
  826. llvm::outs() << ".\n";
  827. else {
  828. StringRef Suffix(Multilib.gccSuffix());
  829. assert(Suffix.front() == '/');
  830. llvm::outs() << Suffix.substr(1) << "\n";
  831. }
  832. }
  833. return false;
  834. }
  835. return true;
  836. }
  837. // Display an action graph human-readably. Action A is the "sink" node
  838. // and latest-occuring action. Traversal is in pre-order, visiting the
  839. // inputs to each action before printing the action itself.
  840. static unsigned PrintActions1(const Compilation &C, Action *A,
  841. std::map<Action *, unsigned> &Ids) {
  842. if (Ids.count(A)) // A was already visited.
  843. return Ids[A];
  844. std::string str;
  845. llvm::raw_string_ostream os(str);
  846. os << Action::getClassName(A->getKind()) << ", ";
  847. if (InputAction *IA = dyn_cast<InputAction>(A)) {
  848. os << "\"" << IA->getInputArg().getValue() << "\"";
  849. } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
  850. os << '"' << BIA->getArchName() << '"' << ", {"
  851. << PrintActions1(C, *BIA->input_begin(), Ids) << "}";
  852. } else if (CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
  853. os << '"'
  854. << (CDA->getGpuArchName() ? CDA->getGpuArchName() : "(multiple archs)")
  855. << '"' << ", {" << PrintActions1(C, *CDA->input_begin(), Ids) << "}";
  856. } else {
  857. const ActionList *AL;
  858. if (CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
  859. os << "{" << PrintActions1(C, *CHA->input_begin(), Ids) << "}"
  860. << ", gpu binaries ";
  861. AL = &CHA->getDeviceActions();
  862. } else
  863. AL = &A->getInputs();
  864. if (AL->size()) {
  865. const char *Prefix = "{";
  866. for (Action *PreRequisite : *AL) {
  867. os << Prefix << PrintActions1(C, PreRequisite, Ids);
  868. Prefix = ", ";
  869. }
  870. os << "}";
  871. } else
  872. os << "{}";
  873. }
  874. unsigned Id = Ids.size();
  875. Ids[A] = Id;
  876. llvm::errs() << Id << ": " << os.str() << ", "
  877. << types::getTypeName(A->getType()) << "\n";
  878. return Id;
  879. }
  880. // Print the action graphs in a compilation C.
  881. // For example "clang -c file1.c file2.c" is composed of two subgraphs.
  882. void Driver::PrintActions(const Compilation &C) const {
  883. std::map<Action *, unsigned> Ids;
  884. for (Action *A : C.getActions())
  885. PrintActions1(C, A, Ids);
  886. }
  887. /// \brief Check whether the given input tree contains any compilation or
  888. /// assembly actions.
  889. static bool ContainsCompileOrAssembleAction(const Action *A) {
  890. if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
  891. isa<AssembleJobAction>(A))
  892. return true;
  893. for (const Action *Input : A->inputs())
  894. if (ContainsCompileOrAssembleAction(Input))
  895. return true;
  896. return false;
  897. }
  898. void Driver::BuildUniversalActions(Compilation &C, const ToolChain &TC,
  899. const InputList &BAInputs) const {
  900. DerivedArgList &Args = C.getArgs();
  901. ActionList &Actions = C.getActions();
  902. llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
  903. // Collect the list of architectures. Duplicates are allowed, but should only
  904. // be handled once (in the order seen).
  905. llvm::StringSet<> ArchNames;
  906. SmallVector<const char *, 4> Archs;
  907. for (Arg *A : Args) {
  908. if (A->getOption().matches(options::OPT_arch)) {
  909. // Validate the option here; we don't save the type here because its
  910. // particular spelling may participate in other driver choices.
  911. llvm::Triple::ArchType Arch =
  912. tools::darwin::getArchTypeForMachOArchName(A->getValue());
  913. if (Arch == llvm::Triple::UnknownArch) {
  914. Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
  915. continue;
  916. }
  917. A->claim();
  918. if (ArchNames.insert(A->getValue()).second)
  919. Archs.push_back(A->getValue());
  920. }
  921. }
  922. // When there is no explicit arch for this platform, make sure we still bind
  923. // the architecture (to the default) so that -Xarch_ is handled correctly.
  924. if (!Archs.size())
  925. Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
  926. ActionList SingleActions;
  927. BuildActions(C, Args, BAInputs, SingleActions);
  928. // Add in arch bindings for every top level action, as well as lipo and
  929. // dsymutil steps if needed.
  930. for (Action* Act : SingleActions) {
  931. // Make sure we can lipo this kind of output. If not (and it is an actual
  932. // output) then we disallow, since we can't create an output file with the
  933. // right name without overwriting it. We could remove this oddity by just
  934. // changing the output names to include the arch, which would also fix
  935. // -save-temps. Compatibility wins for now.
  936. if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
  937. Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
  938. << types::getTypeName(Act->getType());
  939. ActionList Inputs;
  940. for (unsigned i = 0, e = Archs.size(); i != e; ++i)
  941. Inputs.push_back(C.MakeAction<BindArchAction>(Act, Archs[i]));
  942. // Lipo if necessary, we do it this way because we need to set the arch flag
  943. // so that -Xarch_ gets overwritten.
  944. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
  945. Actions.append(Inputs.begin(), Inputs.end());
  946. else
  947. Actions.push_back(C.MakeAction<LipoJobAction>(Inputs, Act->getType()));
  948. // Handle debug info queries.
  949. Arg *A = Args.getLastArg(options::OPT_g_Group);
  950. if (A && !A->getOption().matches(options::OPT_g0) &&
  951. !A->getOption().matches(options::OPT_gstabs) &&
  952. ContainsCompileOrAssembleAction(Actions.back())) {
  953. // Add a 'dsymutil' step if necessary, when debug info is enabled and we
  954. // have a compile input. We need to run 'dsymutil' ourselves in such cases
  955. // because the debug info will refer to a temporary object file which
  956. // will be removed at the end of the compilation process.
  957. if (Act->getType() == types::TY_Image) {
  958. ActionList Inputs;
  959. Inputs.push_back(Actions.back());
  960. Actions.pop_back();
  961. Actions.push_back(
  962. C.MakeAction<DsymutilJobAction>(Inputs, types::TY_dSYM));
  963. }
  964. // Verify the debug info output.
  965. if (Args.hasArg(options::OPT_verify_debug_info)) {
  966. Action* LastAction = Actions.back();
  967. Actions.pop_back();
  968. Actions.push_back(C.MakeAction<VerifyDebugInfoJobAction>(
  969. LastAction, types::TY_Nothing));
  970. }
  971. }
  972. }
  973. }
  974. /// \brief Check that the file referenced by Value exists. If it doesn't,
  975. /// issue a diagnostic and return false.
  976. static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
  977. StringRef Value, types::ID Ty) {
  978. if (!D.getCheckInputsExist())
  979. return true;
  980. // stdin always exists.
  981. if (Value == "-")
  982. return true;
  983. SmallString<64> Path(Value);
  984. if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
  985. if (!llvm::sys::path::is_absolute(Path)) {
  986. SmallString<64> Directory(WorkDir->getValue());
  987. llvm::sys::path::append(Directory, Value);
  988. Path.assign(Directory);
  989. }
  990. }
  991. if (llvm::sys::fs::exists(Twine(Path)))
  992. return true;
  993. if (D.IsCLMode()) {
  994. if (!llvm::sys::path::is_absolute(Twine(Path)) &&
  995. llvm::sys::Process::FindInEnvPath("LIB", Value))
  996. return true;
  997. if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
  998. // Arguments to the /link flag might cause the linker to search for object
  999. // and library files in paths we don't know about. Don't error in such
  1000. // cases.
  1001. return true;
  1002. }
  1003. }
  1004. D.Diag(clang::diag::err_drv_no_such_file) << Path;
  1005. return false;
  1006. }
  1007. // Construct a the list of inputs and their types.
  1008. void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
  1009. InputList &Inputs) const {
  1010. // Track the current user specified (-x) input. We also explicitly track the
  1011. // argument used to set the type; we only want to claim the type when we
  1012. // actually use it, so we warn about unused -x arguments.
  1013. types::ID InputType = types::TY_Nothing;
  1014. Arg *InputTypeArg = nullptr;
  1015. // The last /TC or /TP option sets the input type to C or C++ globally.
  1016. if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
  1017. options::OPT__SLASH_TP)) {
  1018. InputTypeArg = TCTP;
  1019. InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
  1020. ? types::TY_C
  1021. : types::TY_CXX;
  1022. arg_iterator it =
  1023. Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
  1024. const arg_iterator ie = Args.filtered_end();
  1025. Arg *Previous = *it++;
  1026. bool ShowNote = false;
  1027. while (it != ie) {
  1028. Diag(clang::diag::warn_drv_overriding_flag_option)
  1029. << Previous->getSpelling() << (*it)->getSpelling();
  1030. Previous = *it++;
  1031. ShowNote = true;
  1032. }
  1033. if (ShowNote)
  1034. Diag(clang::diag::note_drv_t_option_is_global);
  1035. // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
  1036. assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
  1037. }
  1038. for (Arg *A : Args) {
  1039. if (A->getOption().getKind() == Option::InputClass) {
  1040. const char *Value = A->getValue();
  1041. types::ID Ty = types::TY_INVALID;
  1042. // Infer the input type if necessary.
  1043. if (InputType == types::TY_Nothing) {
  1044. // If there was an explicit arg for this, claim it.
  1045. if (InputTypeArg)
  1046. InputTypeArg->claim();
  1047. // stdin must be handled specially.
  1048. if (memcmp(Value, "-", 2) == 0) {
  1049. // If running with -E, treat as a C input (this changes the builtin
  1050. // macros, for example). This may be overridden by -ObjC below.
  1051. //
  1052. // Otherwise emit an error but still use a valid type to avoid
  1053. // spurious errors (e.g., no inputs).
  1054. if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
  1055. Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
  1056. : clang::diag::err_drv_unknown_stdin_type);
  1057. Ty = types::TY_C;
  1058. } else {
  1059. // Otherwise lookup by extension.
  1060. // Fallback is C if invoked as C preprocessor or Object otherwise.
  1061. // We use a host hook here because Darwin at least has its own
  1062. // idea of what .s is.
  1063. if (const char *Ext = strrchr(Value, '.'))
  1064. Ty = TC.LookupTypeForExtension(Ext + 1);
  1065. if (Ty == types::TY_INVALID) {
  1066. if (CCCIsCPP())
  1067. Ty = types::TY_C;
  1068. else
  1069. Ty = types::TY_Object;
  1070. }
  1071. // If the driver is invoked as C++ compiler (like clang++ or c++) it
  1072. // should autodetect some input files as C++ for g++ compatibility.
  1073. if (CCCIsCXX()) {
  1074. types::ID OldTy = Ty;
  1075. Ty = types::lookupCXXTypeForCType(Ty);
  1076. if (Ty != OldTy)
  1077. Diag(clang::diag::warn_drv_treating_input_as_cxx)
  1078. << getTypeName(OldTy) << getTypeName(Ty);
  1079. }
  1080. }
  1081. // -ObjC and -ObjC++ override the default language, but only for "source
  1082. // files". We just treat everything that isn't a linker input as a
  1083. // source file.
  1084. //
  1085. // FIXME: Clean this up if we move the phase sequence into the type.
  1086. if (Ty != types::TY_Object) {
  1087. if (Args.hasArg(options::OPT_ObjC))
  1088. Ty = types::TY_ObjC;
  1089. else if (Args.hasArg(options::OPT_ObjCXX))
  1090. Ty = types::TY_ObjCXX;
  1091. }
  1092. } else {
  1093. assert(InputTypeArg && "InputType set w/o InputTypeArg");
  1094. if (!InputTypeArg->getOption().matches(options::OPT_x)) {
  1095. // If emulating cl.exe, make sure that /TC and /TP don't affect input
  1096. // object files.
  1097. const char *Ext = strrchr(Value, '.');
  1098. if (Ext && TC.LookupTypeForExtension(Ext + 1) == types::TY_Object)
  1099. Ty = types::TY_Object;
  1100. }
  1101. if (Ty == types::TY_INVALID) {
  1102. Ty = InputType;
  1103. InputTypeArg->claim();
  1104. }
  1105. }
  1106. if (DiagnoseInputExistence(*this, Args, Value, Ty))
  1107. Inputs.push_back(std::make_pair(Ty, A));
  1108. } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
  1109. StringRef Value = A->getValue();
  1110. if (DiagnoseInputExistence(*this, Args, Value, types::TY_C)) {
  1111. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  1112. Inputs.push_back(std::make_pair(types::TY_C, InputArg));
  1113. }
  1114. A->claim();
  1115. } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
  1116. StringRef Value = A->getValue();
  1117. if (DiagnoseInputExistence(*this, Args, Value, types::TY_CXX)) {
  1118. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  1119. Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
  1120. }
  1121. A->claim();
  1122. } else if (A->getOption().hasFlag(options::LinkerInput)) {
  1123. // Just treat as object type, we could make a special type for this if
  1124. // necessary.
  1125. Inputs.push_back(std::make_pair(types::TY_Object, A));
  1126. } else if (A->getOption().matches(options::OPT_x)) {
  1127. InputTypeArg = A;
  1128. InputType = types::lookupTypeForTypeSpecifier(A->getValue());
  1129. A->claim();
  1130. // Follow gcc behavior and treat as linker input for invalid -x
  1131. // options. Its not clear why we shouldn't just revert to unknown; but
  1132. // this isn't very important, we might as well be bug compatible.
  1133. if (!InputType) {
  1134. Diag(clang::diag::err_drv_unknown_language) << A->getValue();
  1135. InputType = types::TY_Object;
  1136. }
  1137. }
  1138. }
  1139. if (CCCIsCPP() && Inputs.empty()) {
  1140. // If called as standalone preprocessor, stdin is processed
  1141. // if no other input is present.
  1142. Arg *A = MakeInputArg(Args, Opts, "-");
  1143. Inputs.push_back(std::make_pair(types::TY_C, A));
  1144. }
  1145. }
  1146. // For each unique --cuda-gpu-arch= argument creates a TY_CUDA_DEVICE
  1147. // input action and then wraps each in CudaDeviceAction paired with
  1148. // appropriate GPU arch name. In case of partial (i.e preprocessing
  1149. // only) or device-only compilation, each device action is added to /p
  1150. // Actions and /p Current is released. Otherwise the function creates
  1151. // and returns a new CudaHostAction which wraps /p Current and device
  1152. // side actions.
  1153. static Action *buildCudaActions(Compilation &C, DerivedArgList &Args,
  1154. const Arg *InputArg, Action *HostAction,
  1155. ActionList &Actions) {
  1156. Arg *PartialCompilationArg = Args.getLastArg(
  1157. options::OPT_cuda_host_only, options::OPT_cuda_device_only,
  1158. options::OPT_cuda_compile_host_device);
  1159. bool CompileHostOnly =
  1160. PartialCompilationArg &&
  1161. PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only);
  1162. bool CompileDeviceOnly =
  1163. PartialCompilationArg &&
  1164. PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only);
  1165. if (CompileHostOnly)
  1166. return C.MakeAction<CudaHostAction>(HostAction, ActionList());
  1167. // Collect all cuda_gpu_arch parameters, removing duplicates.
  1168. SmallVector<const char *, 4> GpuArchList;
  1169. llvm::StringSet<> GpuArchNames;
  1170. for (Arg *A : Args) {
  1171. if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
  1172. continue;
  1173. A->claim();
  1174. const auto& Arch = A->getValue();
  1175. if (!CudaDeviceAction::IsValidGpuArchName(Arch))
  1176. C.getDriver().Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << Arch;
  1177. else if (GpuArchNames.insert(Arch).second)
  1178. GpuArchList.push_back(Arch);
  1179. }
  1180. // Default to sm_20 which is the lowest common denominator for supported GPUs.
  1181. // sm_20 code should work correctly, if suboptimally, on all newer GPUs.
  1182. if (GpuArchList.empty())
  1183. GpuArchList.push_back("sm_20");
  1184. // Replicate inputs for each GPU architecture.
  1185. Driver::InputList CudaDeviceInputs;
  1186. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
  1187. CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
  1188. // Build actions for all device inputs.
  1189. assert(C.getCudaDeviceToolChain() &&
  1190. "Missing toolchain for device-side compilation.");
  1191. ActionList CudaDeviceActions;
  1192. C.getDriver().BuildActions(C, Args, CudaDeviceInputs, CudaDeviceActions);
  1193. assert(GpuArchList.size() == CudaDeviceActions.size() &&
  1194. "Failed to create actions for all devices");
  1195. // Check whether any of device actions stopped before they could generate PTX.
  1196. bool PartialCompilation =
  1197. llvm::any_of(CudaDeviceActions, [](const Action *a) {
  1198. return a->getKind() != Action::AssembleJobClass;
  1199. });
  1200. // Figure out what to do with device actions -- pass them as inputs to the
  1201. // host action or run each of them independently.
  1202. if (PartialCompilation || CompileDeviceOnly) {
  1203. // In case of partial or device-only compilation results of device actions
  1204. // are not consumed by the host action device actions have to be added to
  1205. // top-level actions list with AtTopLevel=true and run independently.
  1206. // -o is ambiguous if we have more than one top-level action.
  1207. if (Args.hasArg(options::OPT_o) &&
  1208. (!CompileDeviceOnly || GpuArchList.size() > 1)) {
  1209. C.getDriver().Diag(
  1210. clang::diag::err_drv_output_argument_with_multiple_files);
  1211. return nullptr;
  1212. }
  1213. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I)
  1214. Actions.push_back(C.MakeAction<CudaDeviceAction>(CudaDeviceActions[I],
  1215. GpuArchList[I],
  1216. /* AtTopLevel */ true));
  1217. // Kill host action in case of device-only compilation.
  1218. if (CompileDeviceOnly)
  1219. return nullptr;
  1220. return HostAction;
  1221. }
  1222. // If we're not a partial or device-only compilation, we compile each arch to
  1223. // ptx and assemble to cubin, then feed the cubin *and* the ptx into a device
  1224. // "link" action, which uses fatbinary to combine these cubins into one
  1225. // fatbin. The fatbin is then an input to the host compilation.
  1226. ActionList DeviceActions;
  1227. for (unsigned I = 0, E = GpuArchList.size(); I != E; ++I) {
  1228. Action* AssembleAction = CudaDeviceActions[I];
  1229. assert(AssembleAction->getType() == types::TY_Object);
  1230. assert(AssembleAction->getInputs().size() == 1);
  1231. Action* BackendAction = AssembleAction->getInputs()[0];
  1232. assert(BackendAction->getType() == types::TY_PP_Asm);
  1233. for (const auto& A : {AssembleAction, BackendAction}) {
  1234. DeviceActions.push_back(C.MakeAction<CudaDeviceAction>(
  1235. A, GpuArchList[I], /* AtTopLevel */ false));
  1236. }
  1237. }
  1238. auto FatbinAction = C.MakeAction<CudaDeviceAction>(
  1239. C.MakeAction<LinkJobAction>(DeviceActions, types::TY_CUDA_FATBIN),
  1240. /* GpuArchName = */ nullptr,
  1241. /* AtTopLevel = */ false);
  1242. // Return a new host action that incorporates original host action and all
  1243. // device actions.
  1244. return C.MakeAction<CudaHostAction>(std::move(HostAction),
  1245. ActionList({FatbinAction}));
  1246. }
  1247. void Driver::BuildActions(Compilation &C, DerivedArgList &Args,
  1248. const InputList &Inputs, ActionList &Actions) const {
  1249. llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
  1250. if (!SuppressMissingInputWarning && Inputs.empty()) {
  1251. Diag(clang::diag::err_drv_no_input_files);
  1252. return;
  1253. }
  1254. Arg *FinalPhaseArg;
  1255. phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
  1256. if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
  1257. Diag(clang::diag::err_drv_emit_llvm_link);
  1258. }
  1259. // Reject -Z* at the top level, these options should never have been exposed
  1260. // by gcc.
  1261. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
  1262. Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
  1263. // Diagnose misuse of /Fo.
  1264. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
  1265. StringRef V = A->getValue();
  1266. if (Inputs.size() > 1 && !V.empty() &&
  1267. !llvm::sys::path::is_separator(V.back())) {
  1268. // Check whether /Fo tries to name an output file for multiple inputs.
  1269. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  1270. << A->getSpelling() << V;
  1271. Args.eraseArg(options::OPT__SLASH_Fo);
  1272. }
  1273. }
  1274. // Diagnose misuse of /Fa.
  1275. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
  1276. StringRef V = A->getValue();
  1277. if (Inputs.size() > 1 && !V.empty() &&
  1278. !llvm::sys::path::is_separator(V.back())) {
  1279. // Check whether /Fa tries to name an asm file for multiple inputs.
  1280. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  1281. << A->getSpelling() << V;
  1282. Args.eraseArg(options::OPT__SLASH_Fa);
  1283. }
  1284. }
  1285. // Diagnose misuse of /o.
  1286. if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
  1287. if (A->getValue()[0] == '\0') {
  1288. // It has to have a value.
  1289. Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
  1290. Args.eraseArg(options::OPT__SLASH_o);
  1291. }
  1292. }
  1293. // Diagnose unsupported forms of /Yc /Yu. Ignore /Yc/Yu for now if:
  1294. // * no filename after it
  1295. // * both /Yc and /Yu passed but with different filenames
  1296. // * corresponding file not also passed as /FI
  1297. Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
  1298. Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
  1299. if (YcArg && YcArg->getValue()[0] == '\0') {
  1300. Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
  1301. Args.eraseArg(options::OPT__SLASH_Yc);
  1302. YcArg = nullptr;
  1303. }
  1304. if (YuArg && YuArg->getValue()[0] == '\0') {
  1305. Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
  1306. Args.eraseArg(options::OPT__SLASH_Yu);
  1307. YuArg = nullptr;
  1308. }
  1309. if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
  1310. Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
  1311. Args.eraseArg(options::OPT__SLASH_Yc);
  1312. Args.eraseArg(options::OPT__SLASH_Yu);
  1313. YcArg = YuArg = nullptr;
  1314. }
  1315. if (YcArg || YuArg) {
  1316. StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
  1317. bool FoundMatchingInclude = false;
  1318. for (const Arg *Inc : Args.filtered(options::OPT_include)) {
  1319. // FIXME: Do case-insensitive matching and consider / and \ as equal.
  1320. if (Inc->getValue() == Val)
  1321. FoundMatchingInclude = true;
  1322. }
  1323. if (!FoundMatchingInclude) {
  1324. Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
  1325. << (YcArg ? YcArg : YuArg)->getSpelling();
  1326. Args.eraseArg(options::OPT__SLASH_Yc);
  1327. Args.eraseArg(options::OPT__SLASH_Yu);
  1328. YcArg = YuArg = nullptr;
  1329. }
  1330. }
  1331. if (YcArg && Inputs.size() > 1) {
  1332. Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
  1333. Args.eraseArg(options::OPT__SLASH_Yc);
  1334. YcArg = nullptr;
  1335. }
  1336. if (Args.hasArg(options::OPT__SLASH_Y_)) {
  1337. // /Y- disables all pch handling. Rather than check for it everywhere,
  1338. // just remove clang-cl pch-related flags here.
  1339. Args.eraseArg(options::OPT__SLASH_Fp);
  1340. Args.eraseArg(options::OPT__SLASH_Yc);
  1341. Args.eraseArg(options::OPT__SLASH_Yu);
  1342. YcArg = YuArg = nullptr;
  1343. }
  1344. // Construct the actions to perform.
  1345. ActionList LinkerInputs;
  1346. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
  1347. for (auto &I : Inputs) {
  1348. types::ID InputType = I.first;
  1349. const Arg *InputArg = I.second;
  1350. PL.clear();
  1351. types::getCompilationPhases(InputType, PL);
  1352. // If the first step comes after the final phase we are doing as part of
  1353. // this compilation, warn the user about it.
  1354. phases::ID InitialPhase = PL[0];
  1355. if (InitialPhase > FinalPhase) {
  1356. // Claim here to avoid the more general unused warning.
  1357. InputArg->claim();
  1358. // Suppress all unused style warnings with -Qunused-arguments
  1359. if (Args.hasArg(options::OPT_Qunused_arguments))
  1360. continue;
  1361. // Special case when final phase determined by binary name, rather than
  1362. // by a command-line argument with a corresponding Arg.
  1363. if (CCCIsCPP())
  1364. Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
  1365. << InputArg->getAsString(Args) << getPhaseName(InitialPhase);
  1366. // Special case '-E' warning on a previously preprocessed file to make
  1367. // more sense.
  1368. else if (InitialPhase == phases::Compile &&
  1369. FinalPhase == phases::Preprocess &&
  1370. getPreprocessedType(InputType) == types::TY_INVALID)
  1371. Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
  1372. << InputArg->getAsString(Args) << !!FinalPhaseArg
  1373. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  1374. else
  1375. Diag(clang::diag::warn_drv_input_file_unused)
  1376. << InputArg->getAsString(Args) << getPhaseName(InitialPhase)
  1377. << !!FinalPhaseArg
  1378. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  1379. continue;
  1380. }
  1381. if (YcArg) {
  1382. // Add a separate precompile phase for the compile phase.
  1383. if (FinalPhase >= phases::Compile) {
  1384. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PCHPL;
  1385. types::getCompilationPhases(types::TY_CXXHeader, PCHPL);
  1386. Arg *PchInputArg = MakeInputArg(Args, Opts, YcArg->getValue());
  1387. // Build the pipeline for the pch file.
  1388. Action *ClangClPch = C.MakeAction<InputAction>(*PchInputArg, InputType);
  1389. for (phases::ID Phase : PCHPL)
  1390. ClangClPch = ConstructPhaseAction(C, Args, Phase, ClangClPch);
  1391. assert(ClangClPch);
  1392. Actions.push_back(ClangClPch);
  1393. // The driver currently exits after the first failed command. This
  1394. // relies on that behavior, to make sure if the pch generation fails,
  1395. // the main compilation won't run.
  1396. }
  1397. }
  1398. phases::ID CudaInjectionPhase =
  1399. (phases::Compile < FinalPhase &&
  1400. llvm::find(PL, phases::Compile) != PL.end())
  1401. ? phases::Compile
  1402. : FinalPhase;
  1403. // Build the pipeline for this file.
  1404. Action *Current = C.MakeAction<InputAction>(*InputArg, InputType);
  1405. for (SmallVectorImpl<phases::ID>::iterator i = PL.begin(), e = PL.end();
  1406. i != e; ++i) {
  1407. phases::ID Phase = *i;
  1408. // We are done if this step is past what the user requested.
  1409. if (Phase > FinalPhase)
  1410. break;
  1411. // Queue linker inputs.
  1412. if (Phase == phases::Link) {
  1413. assert((i + 1) == e && "linking must be final compilation step.");
  1414. LinkerInputs.push_back(Current);
  1415. Current = nullptr;
  1416. break;
  1417. }
  1418. // Some types skip the assembler phase (e.g., llvm-bc), but we can't
  1419. // encode this in the steps because the intermediate type depends on
  1420. // arguments. Just special case here.
  1421. if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
  1422. continue;
  1423. // Otherwise construct the appropriate action.
  1424. Current = ConstructPhaseAction(C, Args, Phase, Current);
  1425. if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
  1426. Current = buildCudaActions(C, Args, InputArg, Current, Actions);
  1427. if (!Current)
  1428. break;
  1429. }
  1430. if (Current->getType() == types::TY_Nothing)
  1431. break;
  1432. }
  1433. // If we ended with something, add to the output list.
  1434. if (Current)
  1435. Actions.push_back(Current);
  1436. }
  1437. // Add a link action if necessary.
  1438. if (!LinkerInputs.empty())
  1439. Actions.push_back(
  1440. C.MakeAction<LinkJobAction>(LinkerInputs, types::TY_Image));
  1441. // If we are linking, claim any options which are obviously only used for
  1442. // compilation.
  1443. if (FinalPhase == phases::Link && PL.size() == 1) {
  1444. Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
  1445. Args.ClaimAllArgs(options::OPT_cl_compile_Group);
  1446. }
  1447. // Claim ignored clang-cl options.
  1448. Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
  1449. // Claim --cuda-host-only and --cuda-compile-host-device, which may be passed
  1450. // to non-CUDA compilations and should not trigger warnings there.
  1451. Args.ClaimAllArgs(options::OPT_cuda_host_only);
  1452. Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
  1453. }
  1454. Action *Driver::ConstructPhaseAction(Compilation &C, const ArgList &Args,
  1455. phases::ID Phase, Action *Input) const {
  1456. llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
  1457. // Build the appropriate action.
  1458. switch (Phase) {
  1459. case phases::Link:
  1460. llvm_unreachable("link action invalid here.");
  1461. case phases::Preprocess: {
  1462. types::ID OutputTy;
  1463. // -{M, MM} alter the output type.
  1464. if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
  1465. OutputTy = types::TY_Dependencies;
  1466. } else {
  1467. OutputTy = Input->getType();
  1468. if (!Args.hasFlag(options::OPT_frewrite_includes,
  1469. options::OPT_fno_rewrite_includes, false) &&
  1470. !CCGenDiagnostics)
  1471. OutputTy = types::getPreprocessedType(OutputTy);
  1472. assert(OutputTy != types::TY_INVALID &&
  1473. "Cannot preprocess this input type!");
  1474. }
  1475. return C.MakeAction<PreprocessJobAction>(Input, OutputTy);
  1476. }
  1477. case phases::Precompile: {
  1478. types::ID OutputTy = types::TY_PCH;
  1479. if (Args.hasArg(options::OPT_fsyntax_only)) {
  1480. // Syntax checks should not emit a PCH file
  1481. OutputTy = types::TY_Nothing;
  1482. }
  1483. return C.MakeAction<PrecompileJobAction>(Input, OutputTy);
  1484. }
  1485. case phases::Compile: {
  1486. if (Args.hasArg(options::OPT_fsyntax_only))
  1487. return C.MakeAction<CompileJobAction>(Input, types::TY_Nothing);
  1488. if (Args.hasArg(options::OPT_rewrite_objc))
  1489. return C.MakeAction<CompileJobAction>(Input, types::TY_RewrittenObjC);
  1490. if (Args.hasArg(options::OPT_rewrite_legacy_objc))
  1491. return C.MakeAction<CompileJobAction>(Input,
  1492. types::TY_RewrittenLegacyObjC);
  1493. if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
  1494. return C.MakeAction<AnalyzeJobAction>(Input, types::TY_Plist);
  1495. if (Args.hasArg(options::OPT__migrate))
  1496. return C.MakeAction<MigrateJobAction>(Input, types::TY_Remap);
  1497. if (Args.hasArg(options::OPT_emit_ast))
  1498. return C.MakeAction<CompileJobAction>(Input, types::TY_AST);
  1499. if (Args.hasArg(options::OPT_module_file_info))
  1500. return C.MakeAction<CompileJobAction>(Input, types::TY_ModuleFile);
  1501. if (Args.hasArg(options::OPT_verify_pch))
  1502. return C.MakeAction<VerifyPCHJobAction>(Input, types::TY_Nothing);
  1503. return C.MakeAction<CompileJobAction>(Input, types::TY_LLVM_BC);
  1504. }
  1505. case phases::Backend: {
  1506. if (isUsingLTO()) {
  1507. types::ID Output =
  1508. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  1509. return C.MakeAction<BackendJobAction>(Input, Output);
  1510. }
  1511. if (Args.hasArg(options::OPT_emit_llvm)) {
  1512. types::ID Output =
  1513. Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
  1514. return C.MakeAction<BackendJobAction>(Input, Output);
  1515. }
  1516. return C.MakeAction<BackendJobAction>(Input, types::TY_PP_Asm);
  1517. }
  1518. case phases::Assemble:
  1519. return C.MakeAction<AssembleJobAction>(std::move(Input), types::TY_Object);
  1520. }
  1521. llvm_unreachable("invalid phase in ConstructPhaseAction");
  1522. }
  1523. void Driver::BuildJobs(Compilation &C) const {
  1524. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1525. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  1526. // It is an error to provide a -o option if we are making multiple output
  1527. // files.
  1528. if (FinalOutput) {
  1529. unsigned NumOutputs = 0;
  1530. for (const Action *A : C.getActions())
  1531. if (A->getType() != types::TY_Nothing)
  1532. ++NumOutputs;
  1533. if (NumOutputs > 1) {
  1534. Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  1535. FinalOutput = nullptr;
  1536. }
  1537. }
  1538. // Collect the list of architectures.
  1539. llvm::StringSet<> ArchNames;
  1540. if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO())
  1541. for (const Arg *A : C.getArgs())
  1542. if (A->getOption().matches(options::OPT_arch))
  1543. ArchNames.insert(A->getValue());
  1544. // Set of (Action, canonical ToolChain triple) pairs we've built jobs for.
  1545. std::map<std::pair<const Action *, std::string>, InputInfo> CachedResults;
  1546. for (Action *A : C.getActions()) {
  1547. // If we are linking an image for multiple archs then the linker wants
  1548. // -arch_multiple and -final_output <final image name>. Unfortunately, this
  1549. // doesn't fit in cleanly because we have to pass this information down.
  1550. //
  1551. // FIXME: This is a hack; find a cleaner way to integrate this into the
  1552. // process.
  1553. const char *LinkingOutput = nullptr;
  1554. if (isa<LipoJobAction>(A)) {
  1555. if (FinalOutput)
  1556. LinkingOutput = FinalOutput->getValue();
  1557. else
  1558. LinkingOutput = getDefaultImageName();
  1559. }
  1560. BuildJobsForAction(C, A, &C.getDefaultToolChain(),
  1561. /*BoundArch*/ nullptr,
  1562. /*AtTopLevel*/ true,
  1563. /*MultipleArchs*/ ArchNames.size() > 1,
  1564. /*LinkingOutput*/ LinkingOutput, CachedResults);
  1565. }
  1566. // If the user passed -Qunused-arguments or there were errors, don't warn
  1567. // about any unused arguments.
  1568. if (Diags.hasErrorOccurred() ||
  1569. C.getArgs().hasArg(options::OPT_Qunused_arguments))
  1570. return;
  1571. // Claim -### here.
  1572. (void)C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
  1573. // Claim --driver-mode, --rsp-quoting, it was handled earlier.
  1574. (void)C.getArgs().hasArg(options::OPT_driver_mode);
  1575. (void)C.getArgs().hasArg(options::OPT_rsp_quoting);
  1576. for (Arg *A : C.getArgs()) {
  1577. // FIXME: It would be nice to be able to send the argument to the
  1578. // DiagnosticsEngine, so that extra values, position, and so on could be
  1579. // printed.
  1580. if (!A->isClaimed()) {
  1581. if (A->getOption().hasFlag(options::NoArgumentUnused))
  1582. continue;
  1583. // Suppress the warning automatically if this is just a flag, and it is an
  1584. // instance of an argument we already claimed.
  1585. const Option &Opt = A->getOption();
  1586. if (Opt.getKind() == Option::FlagClass) {
  1587. bool DuplicateClaimed = false;
  1588. for (const Arg *AA : C.getArgs().filtered(&Opt)) {
  1589. if (AA->isClaimed()) {
  1590. DuplicateClaimed = true;
  1591. break;
  1592. }
  1593. }
  1594. if (DuplicateClaimed)
  1595. continue;
  1596. }
  1597. // In clang-cl, don't mention unknown arguments here since they have
  1598. // already been warned about.
  1599. if (!IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
  1600. Diag(clang::diag::warn_drv_unused_argument)
  1601. << A->getAsString(C.getArgs());
  1602. }
  1603. }
  1604. }
  1605. // Returns a Tool for a given JobAction. In case the action and its
  1606. // predecessors can be combined, updates Inputs with the inputs of the
  1607. // first combined action. If one of the collapsed actions is a
  1608. // CudaHostAction, updates CollapsedCHA with the pointer to it so the
  1609. // caller can deal with extra handling such action requires.
  1610. static const Tool *selectToolForJob(Compilation &C, bool SaveTemps,
  1611. bool EmbedBitcode, const ToolChain *TC,
  1612. const JobAction *JA,
  1613. const ActionList *&Inputs,
  1614. const CudaHostAction *&CollapsedCHA) {
  1615. const Tool *ToolForJob = nullptr;
  1616. CollapsedCHA = nullptr;
  1617. // See if we should look for a compiler with an integrated assembler. We match
  1618. // bottom up, so what we are actually looking for is an assembler job with a
  1619. // compiler input.
  1620. if (TC->useIntegratedAs() && !SaveTemps &&
  1621. !C.getArgs().hasArg(options::OPT_via_file_asm) &&
  1622. !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
  1623. !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
  1624. isa<AssembleJobAction>(JA) && Inputs->size() == 1 &&
  1625. isa<BackendJobAction>(*Inputs->begin())) {
  1626. // A BackendJob is always preceded by a CompileJob, and without -save-temps
  1627. // or -fembed-bitcode, they will always get combined together, so instead of
  1628. // checking the backend tool, check if the tool for the CompileJob has an
  1629. // integrated assembler. For -fembed-bitcode, CompileJob is still used to
  1630. // look up tools for BackendJob, but they need to match before we can split
  1631. // them.
  1632. const ActionList *BackendInputs = &(*Inputs)[0]->getInputs();
  1633. // Compile job may be wrapped in CudaHostAction, extract it if
  1634. // that's the case and update CollapsedCHA if we combine phases.
  1635. CudaHostAction *CHA = dyn_cast<CudaHostAction>(*BackendInputs->begin());
  1636. JobAction *CompileJA = cast<CompileJobAction>(
  1637. CHA ? *CHA->input_begin() : *BackendInputs->begin());
  1638. assert(CompileJA && "Backend job is not preceeded by compile job.");
  1639. const Tool *Compiler = TC->SelectTool(*CompileJA);
  1640. if (!Compiler)
  1641. return nullptr;
  1642. // When using -fembed-bitcode, it is required to have the same tool (clang)
  1643. // for both CompilerJA and BackendJA. Otherwise, combine two stages.
  1644. if (EmbedBitcode) {
  1645. JobAction *InputJA = cast<JobAction>(*Inputs->begin());
  1646. const Tool *BackendTool = TC->SelectTool(*InputJA);
  1647. if (BackendTool == Compiler)
  1648. CompileJA = InputJA;
  1649. }
  1650. if (Compiler->hasIntegratedAssembler()) {
  1651. Inputs = &CompileJA->getInputs();
  1652. ToolForJob = Compiler;
  1653. CollapsedCHA = CHA;
  1654. }
  1655. }
  1656. // A backend job should always be combined with the preceding compile job
  1657. // unless OPT_save_temps or OPT_fembed_bitcode is enabled and the compiler is
  1658. // capable of emitting LLVM IR as an intermediate output.
  1659. if (isa<BackendJobAction>(JA)) {
  1660. // Check if the compiler supports emitting LLVM IR.
  1661. assert(Inputs->size() == 1);
  1662. // Compile job may be wrapped in CudaHostAction, extract it if
  1663. // that's the case and update CollapsedCHA if we combine phases.
  1664. CudaHostAction *CHA = dyn_cast<CudaHostAction>(*Inputs->begin());
  1665. JobAction *CompileJA =
  1666. cast<CompileJobAction>(CHA ? *CHA->input_begin() : *Inputs->begin());
  1667. assert(CompileJA && "Backend job is not preceeded by compile job.");
  1668. const Tool *Compiler = TC->SelectTool(*CompileJA);
  1669. if (!Compiler)
  1670. return nullptr;
  1671. if (!Compiler->canEmitIR() ||
  1672. (!SaveTemps && !EmbedBitcode)) {
  1673. Inputs = &CompileJA->getInputs();
  1674. ToolForJob = Compiler;
  1675. CollapsedCHA = CHA;
  1676. }
  1677. }
  1678. // Otherwise use the tool for the current job.
  1679. if (!ToolForJob)
  1680. ToolForJob = TC->SelectTool(*JA);
  1681. // See if we should use an integrated preprocessor. We do so when we have
  1682. // exactly one input, since this is the only use case we care about
  1683. // (irrelevant since we don't support combine yet).
  1684. if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
  1685. !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
  1686. !C.getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
  1687. !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
  1688. ToolForJob->hasIntegratedCPP())
  1689. Inputs = &(*Inputs)[0]->getInputs();
  1690. return ToolForJob;
  1691. }
  1692. InputInfo Driver::BuildJobsForAction(
  1693. Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
  1694. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  1695. std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults)
  1696. const {
  1697. // The bound arch is not necessarily represented in the toolchain's triple --
  1698. // for example, armv7 and armv7s both map to the same triple -- so we need
  1699. // both in our map.
  1700. std::string TriplePlusArch = TC->getTriple().normalize();
  1701. if (BoundArch) {
  1702. TriplePlusArch += "-";
  1703. TriplePlusArch += BoundArch;
  1704. }
  1705. std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch};
  1706. auto CachedResult = CachedResults.find(ActionTC);
  1707. if (CachedResult != CachedResults.end()) {
  1708. return CachedResult->second;
  1709. }
  1710. InputInfo Result =
  1711. BuildJobsForActionNoCache(C, A, TC, BoundArch, AtTopLevel, MultipleArchs,
  1712. LinkingOutput, CachedResults);
  1713. CachedResults[ActionTC] = Result;
  1714. return Result;
  1715. }
  1716. InputInfo Driver::BuildJobsForActionNoCache(
  1717. Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch,
  1718. bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput,
  1719. std::map<std::pair<const Action *, std::string>, InputInfo> &CachedResults)
  1720. const {
  1721. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1722. InputInfoList CudaDeviceInputInfos;
  1723. if (const CudaHostAction *CHA = dyn_cast<CudaHostAction>(A)) {
  1724. // Append outputs of device jobs to the input list.
  1725. for (const Action *DA : CHA->getDeviceActions()) {
  1726. CudaDeviceInputInfos.push_back(BuildJobsForAction(
  1727. C, DA, TC, nullptr, AtTopLevel,
  1728. /*MultipleArchs*/ false, LinkingOutput, CachedResults));
  1729. }
  1730. // Override current action with a real host compile action and continue
  1731. // processing it.
  1732. A = *CHA->input_begin();
  1733. }
  1734. if (const InputAction *IA = dyn_cast<InputAction>(A)) {
  1735. // FIXME: It would be nice to not claim this here; maybe the old scheme of
  1736. // just using Args was better?
  1737. const Arg &Input = IA->getInputArg();
  1738. Input.claim();
  1739. if (Input.getOption().matches(options::OPT_INPUT)) {
  1740. const char *Name = Input.getValue();
  1741. return InputInfo(A, Name, /* BaseInput = */ Name);
  1742. }
  1743. return InputInfo(A, &Input, /* BaseInput = */ "");
  1744. }
  1745. if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
  1746. const ToolChain *TC;
  1747. const char *ArchName = BAA->getArchName();
  1748. if (ArchName)
  1749. TC = &getToolChain(C.getArgs(),
  1750. computeTargetTriple(*this, DefaultTargetTriple,
  1751. C.getArgs(), ArchName));
  1752. else
  1753. TC = &C.getDefaultToolChain();
  1754. return BuildJobsForAction(C, *BAA->input_begin(), TC, ArchName, AtTopLevel,
  1755. MultipleArchs, LinkingOutput, CachedResults);
  1756. }
  1757. if (const CudaDeviceAction *CDA = dyn_cast<CudaDeviceAction>(A)) {
  1758. // Initial processing of CudaDeviceAction carries host params.
  1759. // Call BuildJobsForAction() again, now with correct device parameters.
  1760. InputInfo II = BuildJobsForAction(
  1761. C, *CDA->input_begin(), C.getCudaDeviceToolChain(),
  1762. CDA->getGpuArchName(), CDA->isAtTopLevel(), /*MultipleArchs=*/true,
  1763. LinkingOutput, CachedResults);
  1764. // Currently II's Action is *CDA->input_begin(). Set it to CDA instead, so
  1765. // that one can retrieve II's GPU arch.
  1766. II.setAction(A);
  1767. return II;
  1768. }
  1769. const ActionList *Inputs = &A->getInputs();
  1770. const JobAction *JA = cast<JobAction>(A);
  1771. const CudaHostAction *CollapsedCHA = nullptr;
  1772. const Tool *T =
  1773. selectToolForJob(C, isSaveTempsEnabled(), embedBitcodeEnabled(), TC, JA,
  1774. Inputs, CollapsedCHA);
  1775. if (!T)
  1776. return InputInfo();
  1777. // If we've collapsed action list that contained CudaHostAction we
  1778. // need to build jobs for device-side inputs it may have held.
  1779. if (CollapsedCHA) {
  1780. for (const Action *DA : CollapsedCHA->getDeviceActions()) {
  1781. CudaDeviceInputInfos.push_back(BuildJobsForAction(
  1782. C, DA, TC, "", AtTopLevel,
  1783. /*MultipleArchs*/ false, LinkingOutput, CachedResults));
  1784. }
  1785. }
  1786. // Only use pipes when there is exactly one input.
  1787. InputInfoList InputInfos;
  1788. for (const Action *Input : *Inputs) {
  1789. // Treat dsymutil and verify sub-jobs as being at the top-level too, they
  1790. // shouldn't get temporary output names.
  1791. // FIXME: Clean this up.
  1792. bool SubJobAtTopLevel =
  1793. AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
  1794. InputInfos.push_back(BuildJobsForAction(C, Input, TC, BoundArch,
  1795. SubJobAtTopLevel, MultipleArchs,
  1796. LinkingOutput, CachedResults));
  1797. }
  1798. // Always use the first input as the base input.
  1799. const char *BaseInput = InputInfos[0].getBaseInput();
  1800. // ... except dsymutil actions, which use their actual input as the base
  1801. // input.
  1802. if (JA->getType() == types::TY_dSYM)
  1803. BaseInput = InputInfos[0].getFilename();
  1804. // Append outputs of cuda device jobs to the input list
  1805. if (CudaDeviceInputInfos.size())
  1806. InputInfos.append(CudaDeviceInputInfos.begin(), CudaDeviceInputInfos.end());
  1807. // Determine the place to write output to, if any.
  1808. InputInfo Result;
  1809. if (JA->getType() == types::TY_Nothing)
  1810. Result = InputInfo(A, BaseInput);
  1811. else
  1812. Result = InputInfo(A, GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
  1813. AtTopLevel, MultipleArchs),
  1814. BaseInput);
  1815. if (CCCPrintBindings && !CCGenDiagnostics) {
  1816. llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
  1817. << " - \"" << T->getName() << "\", inputs: [";
  1818. for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
  1819. llvm::errs() << InputInfos[i].getAsString();
  1820. if (i + 1 != e)
  1821. llvm::errs() << ", ";
  1822. }
  1823. llvm::errs() << "], output: " << Result.getAsString() << "\n";
  1824. } else {
  1825. T->ConstructJob(C, *JA, Result, InputInfos,
  1826. C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
  1827. }
  1828. return Result;
  1829. }
  1830. const char *Driver::getDefaultImageName() const {
  1831. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  1832. return Target.isOSWindows() ? "a.exe" : "a.out";
  1833. }
  1834. /// \brief Create output filename based on ArgValue, which could either be a
  1835. /// full filename, filename without extension, or a directory. If ArgValue
  1836. /// does not provide a filename, then use BaseName, and use the extension
  1837. /// suitable for FileType.
  1838. static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
  1839. StringRef BaseName,
  1840. types::ID FileType) {
  1841. SmallString<128> Filename = ArgValue;
  1842. if (ArgValue.empty()) {
  1843. // If the argument is empty, output to BaseName in the current dir.
  1844. Filename = BaseName;
  1845. } else if (llvm::sys::path::is_separator(Filename.back())) {
  1846. // If the argument is a directory, output to BaseName in that dir.
  1847. llvm::sys::path::append(Filename, BaseName);
  1848. }
  1849. if (!llvm::sys::path::has_extension(ArgValue)) {
  1850. // If the argument didn't provide an extension, then set it.
  1851. const char *Extension = types::getTypeTempSuffix(FileType, true);
  1852. if (FileType == types::TY_Image &&
  1853. Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
  1854. // The output file is a dll.
  1855. Extension = "dll";
  1856. }
  1857. llvm::sys::path::replace_extension(Filename, Extension);
  1858. }
  1859. return Args.MakeArgString(Filename.c_str());
  1860. }
  1861. const char *Driver::GetNamedOutputPath(Compilation &C, const JobAction &JA,
  1862. const char *BaseInput,
  1863. const char *BoundArch, bool AtTopLevel,
  1864. bool MultipleArchs) const {
  1865. llvm::PrettyStackTraceString CrashInfo("Computing output path");
  1866. // Output to a user requested destination?
  1867. if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
  1868. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  1869. return C.addResultFile(FinalOutput->getValue(), &JA);
  1870. }
  1871. // For /P, preprocess to file named after BaseInput.
  1872. if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
  1873. assert(AtTopLevel && isa<PreprocessJobAction>(JA));
  1874. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  1875. StringRef NameArg;
  1876. if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
  1877. NameArg = A->getValue();
  1878. return C.addResultFile(
  1879. MakeCLOutputFilename(C.getArgs(), NameArg, BaseName, types::TY_PP_C),
  1880. &JA);
  1881. }
  1882. // Default to writing to stdout?
  1883. if (AtTopLevel && !CCGenDiagnostics &&
  1884. (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
  1885. return "-";
  1886. // Is this the assembly listing for /FA?
  1887. if (JA.getType() == types::TY_PP_Asm &&
  1888. (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
  1889. C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
  1890. // Use /Fa and the input filename to determine the asm file name.
  1891. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  1892. StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
  1893. return C.addResultFile(
  1894. MakeCLOutputFilename(C.getArgs(), FaValue, BaseName, JA.getType()),
  1895. &JA);
  1896. }
  1897. // Output to a temporary file?
  1898. if ((!AtTopLevel && !isSaveTempsEnabled() &&
  1899. !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
  1900. CCGenDiagnostics) {
  1901. StringRef Name = llvm::sys::path::filename(BaseInput);
  1902. std::pair<StringRef, StringRef> Split = Name.split('.');
  1903. std::string TmpName = GetTemporaryPath(
  1904. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  1905. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1906. }
  1907. SmallString<128> BasePath(BaseInput);
  1908. StringRef BaseName;
  1909. // Dsymutil actions should use the full path.
  1910. if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
  1911. BaseName = BasePath;
  1912. else
  1913. BaseName = llvm::sys::path::filename(BasePath);
  1914. // Determine what the derived output name should be.
  1915. const char *NamedOutput;
  1916. if (JA.getType() == types::TY_Object &&
  1917. C.getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
  1918. // The /Fo or /o flag decides the object filename.
  1919. StringRef Val =
  1920. C.getArgs()
  1921. .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
  1922. ->getValue();
  1923. NamedOutput =
  1924. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Object);
  1925. } else if (JA.getType() == types::TY_Image &&
  1926. C.getArgs().hasArg(options::OPT__SLASH_Fe,
  1927. options::OPT__SLASH_o)) {
  1928. // The /Fe or /o flag names the linked file.
  1929. StringRef Val =
  1930. C.getArgs()
  1931. .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
  1932. ->getValue();
  1933. NamedOutput =
  1934. MakeCLOutputFilename(C.getArgs(), Val, BaseName, types::TY_Image);
  1935. } else if (JA.getType() == types::TY_Image) {
  1936. if (IsCLMode()) {
  1937. // clang-cl uses BaseName for the executable name.
  1938. NamedOutput =
  1939. MakeCLOutputFilename(C.getArgs(), "", BaseName, types::TY_Image);
  1940. } else if (MultipleArchs && BoundArch) {
  1941. SmallString<128> Output(getDefaultImageName());
  1942. Output += "-";
  1943. Output.append(BoundArch);
  1944. NamedOutput = C.getArgs().MakeArgString(Output.c_str());
  1945. } else {
  1946. NamedOutput = getDefaultImageName();
  1947. }
  1948. } else if (JA.getType() == types::TY_PCH && IsCLMode()) {
  1949. NamedOutput = C.getArgs().MakeArgString(GetClPchPath(C, BaseName).c_str());
  1950. } else {
  1951. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  1952. assert(Suffix && "All types used for output should have a suffix.");
  1953. std::string::size_type End = std::string::npos;
  1954. if (!types::appendSuffixForType(JA.getType()))
  1955. End = BaseName.rfind('.');
  1956. SmallString<128> Suffixed(BaseName.substr(0, End));
  1957. if (MultipleArchs && BoundArch) {
  1958. Suffixed += "-";
  1959. Suffixed.append(BoundArch);
  1960. }
  1961. // When using both -save-temps and -emit-llvm, use a ".tmp.bc" suffix for
  1962. // the unoptimized bitcode so that it does not get overwritten by the ".bc"
  1963. // optimized bitcode output.
  1964. if (!AtTopLevel && C.getArgs().hasArg(options::OPT_emit_llvm) &&
  1965. JA.getType() == types::TY_LLVM_BC)
  1966. Suffixed += ".tmp";
  1967. Suffixed += '.';
  1968. Suffixed += Suffix;
  1969. NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
  1970. }
  1971. // Prepend object file path if -save-temps=obj
  1972. if (!AtTopLevel && isSaveTempsObj() && C.getArgs().hasArg(options::OPT_o) &&
  1973. JA.getType() != types::TY_PCH) {
  1974. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  1975. SmallString<128> TempPath(FinalOutput->getValue());
  1976. llvm::sys::path::remove_filename(TempPath);
  1977. StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
  1978. llvm::sys::path::append(TempPath, OutputFileName);
  1979. NamedOutput = C.getArgs().MakeArgString(TempPath.c_str());
  1980. }
  1981. // If we're saving temps and the temp file conflicts with the input file,
  1982. // then avoid overwriting input file.
  1983. if (!AtTopLevel && isSaveTempsEnabled() && NamedOutput == BaseName) {
  1984. bool SameFile = false;
  1985. SmallString<256> Result;
  1986. llvm::sys::fs::current_path(Result);
  1987. llvm::sys::path::append(Result, BaseName);
  1988. llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
  1989. // Must share the same path to conflict.
  1990. if (SameFile) {
  1991. StringRef Name = llvm::sys::path::filename(BaseInput);
  1992. std::pair<StringRef, StringRef> Split = Name.split('.');
  1993. std::string TmpName = GetTemporaryPath(
  1994. Split.first, types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  1995. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1996. }
  1997. }
  1998. // As an annoying special case, PCH generation doesn't strip the pathname.
  1999. if (JA.getType() == types::TY_PCH && !IsCLMode()) {
  2000. llvm::sys::path::remove_filename(BasePath);
  2001. if (BasePath.empty())
  2002. BasePath = NamedOutput;
  2003. else
  2004. llvm::sys::path::append(BasePath, NamedOutput);
  2005. return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
  2006. } else {
  2007. return C.addResultFile(NamedOutput, &JA);
  2008. }
  2009. }
  2010. std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
  2011. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  2012. // attempting to use this prefix when looking for file paths.
  2013. for (const std::string &Dir : PrefixDirs) {
  2014. if (Dir.empty())
  2015. continue;
  2016. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  2017. llvm::sys::path::append(P, Name);
  2018. if (llvm::sys::fs::exists(Twine(P)))
  2019. return P.str();
  2020. }
  2021. SmallString<128> P(ResourceDir);
  2022. llvm::sys::path::append(P, Name);
  2023. if (llvm::sys::fs::exists(Twine(P)))
  2024. return P.str();
  2025. for (const std::string &Dir : TC.getFilePaths()) {
  2026. if (Dir.empty())
  2027. continue;
  2028. SmallString<128> P(Dir[0] == '=' ? SysRoot + Dir.substr(1) : Dir);
  2029. llvm::sys::path::append(P, Name);
  2030. if (llvm::sys::fs::exists(Twine(P)))
  2031. return P.str();
  2032. }
  2033. return Name;
  2034. }
  2035. void Driver::generatePrefixedToolNames(
  2036. const char *Tool, const ToolChain &TC,
  2037. SmallVectorImpl<std::string> &Names) const {
  2038. // FIXME: Needs a better variable than DefaultTargetTriple
  2039. Names.emplace_back(DefaultTargetTriple + "-" + Tool);
  2040. Names.emplace_back(Tool);
  2041. // Allow the discovery of tools prefixed with LLVM's default target triple.
  2042. std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
  2043. if (LLVMDefaultTargetTriple != DefaultTargetTriple)
  2044. Names.emplace_back(LLVMDefaultTargetTriple + "-" + Tool);
  2045. }
  2046. static bool ScanDirForExecutable(SmallString<128> &Dir,
  2047. ArrayRef<std::string> Names) {
  2048. for (const auto &Name : Names) {
  2049. llvm::sys::path::append(Dir, Name);
  2050. if (llvm::sys::fs::can_execute(Twine(Dir)))
  2051. return true;
  2052. llvm::sys::path::remove_filename(Dir);
  2053. }
  2054. return false;
  2055. }
  2056. std::string Driver::GetProgramPath(const char *Name,
  2057. const ToolChain &TC) const {
  2058. SmallVector<std::string, 2> TargetSpecificExecutables;
  2059. generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
  2060. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  2061. // attempting to use this prefix when looking for program paths.
  2062. for (const auto &PrefixDir : PrefixDirs) {
  2063. if (llvm::sys::fs::is_directory(PrefixDir)) {
  2064. SmallString<128> P(PrefixDir);
  2065. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  2066. return P.str();
  2067. } else {
  2068. SmallString<128> P(PrefixDir + Name);
  2069. if (llvm::sys::fs::can_execute(Twine(P)))
  2070. return P.str();
  2071. }
  2072. }
  2073. const ToolChain::path_list &List = TC.getProgramPaths();
  2074. for (const auto &Path : List) {
  2075. SmallString<128> P(Path);
  2076. if (ScanDirForExecutable(P, TargetSpecificExecutables))
  2077. return P.str();
  2078. }
  2079. // If all else failed, search the path.
  2080. for (const auto &TargetSpecificExecutable : TargetSpecificExecutables)
  2081. if (llvm::ErrorOr<std::string> P =
  2082. llvm::sys::findProgramByName(TargetSpecificExecutable))
  2083. return *P;
  2084. return Name;
  2085. }
  2086. std::string Driver::GetTemporaryPath(StringRef Prefix,
  2087. const char *Suffix) const {
  2088. SmallString<128> Path;
  2089. std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
  2090. if (EC) {
  2091. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  2092. return "";
  2093. }
  2094. return Path.str();
  2095. }
  2096. std::string Driver::GetClPchPath(Compilation &C, StringRef BaseName) const {
  2097. SmallString<128> Output;
  2098. if (Arg *FpArg = C.getArgs().getLastArg(options::OPT__SLASH_Fp)) {
  2099. // FIXME: If anybody needs it, implement this obscure rule:
  2100. // "If you specify a directory without a file name, the default file name
  2101. // is VCx0.pch., where x is the major version of Visual C++ in use."
  2102. Output = FpArg->getValue();
  2103. // "If you do not specify an extension as part of the path name, an
  2104. // extension of .pch is assumed. "
  2105. if (!llvm::sys::path::has_extension(Output))
  2106. Output += ".pch";
  2107. } else {
  2108. Output = BaseName;
  2109. llvm::sys::path::replace_extension(Output, ".pch");
  2110. }
  2111. return Output.str();
  2112. }
  2113. const ToolChain &Driver::getToolChain(const ArgList &Args,
  2114. const llvm::Triple &Target) const {
  2115. ToolChain *&TC = ToolChains[Target.str()];
  2116. if (!TC) {
  2117. switch (Target.getOS()) {
  2118. case llvm::Triple::Haiku:
  2119. TC = new toolchains::Haiku(*this, Target, Args);
  2120. break;
  2121. case llvm::Triple::CloudABI:
  2122. TC = new toolchains::CloudABI(*this, Target, Args);
  2123. break;
  2124. case llvm::Triple::Darwin:
  2125. case llvm::Triple::MacOSX:
  2126. case llvm::Triple::IOS:
  2127. case llvm::Triple::TvOS:
  2128. case llvm::Triple::WatchOS:
  2129. TC = new toolchains::DarwinClang(*this, Target, Args);
  2130. break;
  2131. case llvm::Triple::DragonFly:
  2132. TC = new toolchains::DragonFly(*this, Target, Args);
  2133. break;
  2134. case llvm::Triple::OpenBSD:
  2135. TC = new toolchains::OpenBSD(*this, Target, Args);
  2136. break;
  2137. case llvm::Triple::Bitrig:
  2138. TC = new toolchains::Bitrig(*this, Target, Args);
  2139. break;
  2140. case llvm::Triple::NetBSD:
  2141. TC = new toolchains::NetBSD(*this, Target, Args);
  2142. break;
  2143. case llvm::Triple::FreeBSD:
  2144. TC = new toolchains::FreeBSD(*this, Target, Args);
  2145. break;
  2146. case llvm::Triple::Minix:
  2147. TC = new toolchains::Minix(*this, Target, Args);
  2148. break;
  2149. case llvm::Triple::Linux:
  2150. if (Target.getArch() == llvm::Triple::hexagon)
  2151. TC = new toolchains::HexagonToolChain(*this, Target, Args);
  2152. else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
  2153. !Target.hasEnvironment())
  2154. TC = new toolchains::MipsLLVMToolChain(*this, Target, Args);
  2155. else
  2156. TC = new toolchains::Linux(*this, Target, Args);
  2157. break;
  2158. case llvm::Triple::NaCl:
  2159. TC = new toolchains::NaClToolChain(*this, Target, Args);
  2160. break;
  2161. case llvm::Triple::Solaris:
  2162. TC = new toolchains::Solaris(*this, Target, Args);
  2163. break;
  2164. case llvm::Triple::AMDHSA:
  2165. TC = new toolchains::AMDGPUToolChain(*this, Target, Args);
  2166. break;
  2167. case llvm::Triple::Win32:
  2168. switch (Target.getEnvironment()) {
  2169. default:
  2170. if (Target.isOSBinFormatELF())
  2171. TC = new toolchains::Generic_ELF(*this, Target, Args);
  2172. else if (Target.isOSBinFormatMachO())
  2173. TC = new toolchains::MachO(*this, Target, Args);
  2174. else
  2175. TC = new toolchains::Generic_GCC(*this, Target, Args);
  2176. break;
  2177. case llvm::Triple::GNU:
  2178. TC = new toolchains::MinGW(*this, Target, Args);
  2179. break;
  2180. case llvm::Triple::Itanium:
  2181. TC = new toolchains::CrossWindowsToolChain(*this, Target, Args);
  2182. break;
  2183. case llvm::Triple::MSVC:
  2184. case llvm::Triple::UnknownEnvironment:
  2185. TC = new toolchains::MSVCToolChain(*this, Target, Args);
  2186. break;
  2187. }
  2188. break;
  2189. case llvm::Triple::CUDA:
  2190. TC = new toolchains::CudaToolChain(*this, Target, Args);
  2191. break;
  2192. case llvm::Triple::PS4:
  2193. TC = new toolchains::PS4CPU(*this, Target, Args);
  2194. break;
  2195. default:
  2196. // Of these targets, Hexagon is the only one that might have
  2197. // an OS of Linux, in which case it got handled above already.
  2198. switch (Target.getArch()) {
  2199. case llvm::Triple::tce:
  2200. TC = new toolchains::TCEToolChain(*this, Target, Args);
  2201. break;
  2202. case llvm::Triple::hexagon:
  2203. TC = new toolchains::HexagonToolChain(*this, Target, Args);
  2204. break;
  2205. case llvm::Triple::lanai:
  2206. TC = new toolchains::LanaiToolChain(*this, Target, Args);
  2207. break;
  2208. case llvm::Triple::xcore:
  2209. TC = new toolchains::XCoreToolChain(*this, Target, Args);
  2210. break;
  2211. case llvm::Triple::wasm32:
  2212. case llvm::Triple::wasm64:
  2213. TC = new toolchains::WebAssembly(*this, Target, Args);
  2214. break;
  2215. default:
  2216. if (Target.getVendor() == llvm::Triple::Myriad)
  2217. TC = new toolchains::MyriadToolChain(*this, Target, Args);
  2218. else if (Target.isOSBinFormatELF())
  2219. TC = new toolchains::Generic_ELF(*this, Target, Args);
  2220. else if (Target.isOSBinFormatMachO())
  2221. TC = new toolchains::MachO(*this, Target, Args);
  2222. else
  2223. TC = new toolchains::Generic_GCC(*this, Target, Args);
  2224. }
  2225. }
  2226. }
  2227. return *TC;
  2228. }
  2229. bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
  2230. // Say "no" if there is not exactly one input of a type clang understands.
  2231. if (JA.size() != 1 ||
  2232. !types::isAcceptedByClang((*JA.input_begin())->getType()))
  2233. return false;
  2234. // And say "no" if this is not a kind of action clang understands.
  2235. if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
  2236. !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
  2237. return false;
  2238. return true;
  2239. }
  2240. /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
  2241. /// grouped values as integers. Numbers which are not provided are set to 0.
  2242. ///
  2243. /// \return True if the entire string was parsed (9.2), or all groups were
  2244. /// parsed (10.3.5extrastuff).
  2245. bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
  2246. unsigned &Minor, unsigned &Micro,
  2247. bool &HadExtra) {
  2248. HadExtra = false;
  2249. Major = Minor = Micro = 0;
  2250. if (*Str == '\0')
  2251. return false;
  2252. char *End;
  2253. Major = (unsigned)strtol(Str, &End, 10);
  2254. if (*Str != '\0' && *End == '\0')
  2255. return true;
  2256. if (*End != '.')
  2257. return false;
  2258. Str = End + 1;
  2259. Minor = (unsigned)strtol(Str, &End, 10);
  2260. if (*Str != '\0' && *End == '\0')
  2261. return true;
  2262. if (*End != '.')
  2263. return false;
  2264. Str = End + 1;
  2265. Micro = (unsigned)strtol(Str, &End, 10);
  2266. if (*Str != '\0' && *End == '\0')
  2267. return true;
  2268. if (Str == End)
  2269. return false;
  2270. HadExtra = true;
  2271. return true;
  2272. }
  2273. /// Parse digits from a string \p Str and fulfill \p Digits with
  2274. /// the parsed numbers. This method assumes that the max number of
  2275. /// digits to look for is equal to Digits.size().
  2276. ///
  2277. /// \return True if the entire string was parsed and there are
  2278. /// no extra characters remaining at the end.
  2279. bool Driver::GetReleaseVersion(const char *Str,
  2280. MutableArrayRef<unsigned> Digits) {
  2281. if (*Str == '\0')
  2282. return false;
  2283. char *End;
  2284. unsigned CurDigit = 0;
  2285. while (CurDigit < Digits.size()) {
  2286. unsigned Digit = (unsigned)strtol(Str, &End, 10);
  2287. Digits[CurDigit] = Digit;
  2288. if (*Str != '\0' && *End == '\0')
  2289. return true;
  2290. if (*End != '.' || Str == End)
  2291. return false;
  2292. Str = End + 1;
  2293. CurDigit++;
  2294. }
  2295. // More digits than requested, bail out...
  2296. return false;
  2297. }
  2298. std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
  2299. unsigned IncludedFlagsBitmask = 0;
  2300. unsigned ExcludedFlagsBitmask = options::NoDriverOption;
  2301. if (Mode == CLMode) {
  2302. // Include CL and Core options.
  2303. IncludedFlagsBitmask |= options::CLOption;
  2304. IncludedFlagsBitmask |= options::CoreOption;
  2305. } else {
  2306. ExcludedFlagsBitmask |= options::CLOption;
  2307. }
  2308. return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
  2309. }
  2310. bool clang::driver::isOptimizationLevelFast(const ArgList &Args) {
  2311. return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
  2312. }