Driver.cpp 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  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/Config/config.h"
  14. #include "clang/Driver/Action.h"
  15. #include "clang/Driver/Compilation.h"
  16. #include "clang/Driver/DriverDiagnostic.h"
  17. #include "clang/Driver/Job.h"
  18. #include "clang/Driver/Options.h"
  19. #include "clang/Driver/Tool.h"
  20. #include "clang/Driver/ToolChain.h"
  21. #include "llvm/ADT/ArrayRef.h"
  22. #include "llvm/ADT/STLExtras.h"
  23. #include "llvm/ADT/StringExtras.h"
  24. #include "llvm/ADT/StringSet.h"
  25. #include "llvm/ADT/StringSwitch.h"
  26. #include "llvm/Option/Arg.h"
  27. #include "llvm/Option/ArgList.h"
  28. #include "llvm/Option/OptSpecifier.h"
  29. #include "llvm/Option/OptTable.h"
  30. #include "llvm/Option/Option.h"
  31. #include "llvm/Support/Debug.h"
  32. #include "llvm/Support/ErrorHandling.h"
  33. #include "llvm/Support/FileSystem.h"
  34. #include "llvm/Support/Path.h"
  35. #include "llvm/Support/PrettyStackTrace.h"
  36. #include "llvm/Support/Process.h"
  37. #include "llvm/Support/Program.h"
  38. #include "llvm/Support/raw_ostream.h"
  39. #include <map>
  40. #include <memory>
  41. using namespace clang::driver;
  42. using namespace clang;
  43. using namespace llvm::opt;
  44. Driver::Driver(StringRef ClangExecutable,
  45. StringRef DefaultTargetTriple,
  46. DiagnosticsEngine &Diags)
  47. : Opts(createDriverOptTable()), Diags(Diags), Mode(GCCMode),
  48. ClangExecutable(ClangExecutable), SysRoot(DEFAULT_SYSROOT),
  49. UseStdLib(true), DefaultTargetTriple(DefaultTargetTriple),
  50. DefaultImageName("a.out"),
  51. DriverTitle("clang LLVM compiler"),
  52. CCPrintOptionsFilename(nullptr), CCPrintHeadersFilename(nullptr),
  53. CCLogDiagnosticsFilename(nullptr),
  54. CCCPrintBindings(false),
  55. CCPrintHeaders(false), CCLogDiagnostics(false),
  56. CCGenDiagnostics(false), CCCGenericGCCName(""), CheckInputsExist(true),
  57. CCCUsePCH(true), SuppressMissingInputWarning(false) {
  58. Name = llvm::sys::path::stem(ClangExecutable);
  59. Dir = llvm::sys::path::parent_path(ClangExecutable);
  60. // Compute the path to the resource directory.
  61. StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
  62. SmallString<128> P(Dir);
  63. if (ClangResourceDir != "")
  64. llvm::sys::path::append(P, ClangResourceDir);
  65. else
  66. llvm::sys::path::append(P, "..", "lib", "clang", CLANG_VERSION_STRING);
  67. ResourceDir = P.str();
  68. }
  69. Driver::~Driver() {
  70. delete Opts;
  71. llvm::DeleteContainerSeconds(ToolChains);
  72. }
  73. void Driver::ParseDriverMode(ArrayRef<const char *> Args) {
  74. const std::string OptName =
  75. getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
  76. for (size_t I = 0, E = Args.size(); I != E; ++I) {
  77. // Ingore nullptrs, they are response file's EOL markers
  78. if (Args[I] == nullptr)
  79. continue;
  80. const StringRef Arg = Args[I];
  81. if (!Arg.startswith(OptName))
  82. continue;
  83. const StringRef Value = Arg.drop_front(OptName.size());
  84. const unsigned M = llvm::StringSwitch<unsigned>(Value)
  85. .Case("gcc", GCCMode)
  86. .Case("g++", GXXMode)
  87. .Case("cpp", CPPMode)
  88. .Case("cl", CLMode)
  89. .Default(~0U);
  90. if (M != ~0U)
  91. Mode = static_cast<DriverMode>(M);
  92. else
  93. Diag(diag::err_drv_unsupported_option_argument) << OptName << Value;
  94. }
  95. }
  96. InputArgList *Driver::ParseArgStrings(ArrayRef<const char *> ArgStrings) {
  97. llvm::PrettyStackTraceString CrashInfo("Command line argument parsing");
  98. unsigned IncludedFlagsBitmask;
  99. unsigned ExcludedFlagsBitmask;
  100. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  101. getIncludeExcludeOptionFlagMasks();
  102. unsigned MissingArgIndex, MissingArgCount;
  103. InputArgList *Args = getOpts().ParseArgs(ArgStrings.begin(), ArgStrings.end(),
  104. MissingArgIndex, MissingArgCount,
  105. IncludedFlagsBitmask,
  106. ExcludedFlagsBitmask);
  107. // Check for missing argument error.
  108. if (MissingArgCount)
  109. Diag(clang::diag::err_drv_missing_argument)
  110. << Args->getArgString(MissingArgIndex) << MissingArgCount;
  111. // Check for unsupported options.
  112. for (ArgList::const_iterator it = Args->begin(), ie = Args->end();
  113. it != ie; ++it) {
  114. Arg *A = *it;
  115. if (A->getOption().hasFlag(options::Unsupported)) {
  116. Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(*Args);
  117. continue;
  118. }
  119. // Warn about -mcpu= without an argument.
  120. if (A->getOption().matches(options::OPT_mcpu_EQ) &&
  121. A->containsValue("")) {
  122. Diag(clang::diag::warn_drv_empty_joined_argument) <<
  123. A->getAsString(*Args);
  124. }
  125. }
  126. for (arg_iterator it = Args->filtered_begin(options::OPT_UNKNOWN),
  127. ie = Args->filtered_end(); it != ie; ++it) {
  128. Diags.Report(diag::err_drv_unknown_argument) << (*it) ->getAsString(*Args);
  129. }
  130. return Args;
  131. }
  132. // Determine which compilation mode we are in. We look for options which
  133. // affect the phase, starting with the earliest phases, and record which
  134. // option we used to determine the final phase.
  135. phases::ID Driver::getFinalPhase(const DerivedArgList &DAL, Arg **FinalPhaseArg)
  136. const {
  137. Arg *PhaseArg = nullptr;
  138. phases::ID FinalPhase;
  139. // -{E,EP,P,M,MM} only run the preprocessor.
  140. if (CCCIsCPP() ||
  141. (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
  142. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
  143. (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
  144. (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
  145. FinalPhase = phases::Preprocess;
  146. // -{fsyntax-only,-analyze,emit-ast,S} only run up to the compiler.
  147. } else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
  148. (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
  149. (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
  150. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
  151. (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
  152. (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
  153. (PhaseArg = DAL.getLastArg(options::OPT__analyze,
  154. options::OPT__analyze_auto)) ||
  155. (PhaseArg = DAL.getLastArg(options::OPT_emit_ast)) ||
  156. (PhaseArg = DAL.getLastArg(options::OPT_S))) {
  157. FinalPhase = phases::Compile;
  158. // -c only runs up to the assembler.
  159. } else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
  160. FinalPhase = phases::Assemble;
  161. // Otherwise do everything.
  162. } else
  163. FinalPhase = phases::Link;
  164. if (FinalPhaseArg)
  165. *FinalPhaseArg = PhaseArg;
  166. return FinalPhase;
  167. }
  168. static Arg* MakeInputArg(DerivedArgList &Args, OptTable *Opts,
  169. StringRef Value) {
  170. Arg *A = new Arg(Opts->getOption(options::OPT_INPUT), Value,
  171. Args.getBaseArgs().MakeIndex(Value), Value.data());
  172. Args.AddSynthesizedArg(A);
  173. A->claim();
  174. return A;
  175. }
  176. DerivedArgList *Driver::TranslateInputArgs(const InputArgList &Args) const {
  177. DerivedArgList *DAL = new DerivedArgList(Args);
  178. bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
  179. for (ArgList::const_iterator it = Args.begin(),
  180. ie = Args.end(); it != ie; ++it) {
  181. const Arg *A = *it;
  182. // Unfortunately, we have to parse some forwarding options (-Xassembler,
  183. // -Xlinker, -Xpreprocessor) because we either integrate their functionality
  184. // (assembler and preprocessor), or bypass a previous driver ('collect2').
  185. // Rewrite linker options, to replace --no-demangle with a custom internal
  186. // option.
  187. if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
  188. A->getOption().matches(options::OPT_Xlinker)) &&
  189. A->containsValue("--no-demangle")) {
  190. // Add the rewritten no-demangle argument.
  191. DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
  192. // Add the remaining values as Xlinker arguments.
  193. for (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
  194. if (StringRef(A->getValue(i)) != "--no-demangle")
  195. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker),
  196. A->getValue(i));
  197. continue;
  198. }
  199. // Rewrite preprocessor options, to replace -Wp,-MD,FOO which is used by
  200. // some build systems. We don't try to be complete here because we don't
  201. // care to encourage this usage model.
  202. if (A->getOption().matches(options::OPT_Wp_COMMA) &&
  203. (A->getValue(0) == StringRef("-MD") ||
  204. A->getValue(0) == StringRef("-MMD"))) {
  205. // Rewrite to -MD/-MMD along with -MF.
  206. if (A->getValue(0) == StringRef("-MD"))
  207. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
  208. else
  209. DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
  210. if (A->getNumValues() == 2)
  211. DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
  212. A->getValue(1));
  213. continue;
  214. }
  215. // Rewrite reserved library names.
  216. if (A->getOption().matches(options::OPT_l)) {
  217. StringRef Value = A->getValue();
  218. // Rewrite unless -nostdlib is present.
  219. if (!HasNostdlib && Value == "stdc++") {
  220. DAL->AddFlagArg(A, Opts->getOption(
  221. options::OPT_Z_reserved_lib_stdcxx));
  222. continue;
  223. }
  224. // Rewrite unconditionally.
  225. if (Value == "cc_kext") {
  226. DAL->AddFlagArg(A, Opts->getOption(
  227. 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 (unsigned i = 0, e = A->getNumValues(); i != e; ++i)
  235. DAL->append(MakeInputArg(*DAL, Opts, A->getValue(i)));
  236. continue;
  237. }
  238. DAL->append(*it);
  239. }
  240. // Add a default value of -mlinker-version=, if one was given and the user
  241. // didn't specify one.
  242. #if defined(HOST_LINK_VERSION)
  243. if (!Args.hasArg(options::OPT_mlinker_version_EQ)) {
  244. DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
  245. HOST_LINK_VERSION);
  246. DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
  247. }
  248. #endif
  249. return DAL;
  250. }
  251. Compilation *Driver::BuildCompilation(ArrayRef<const char *> ArgList) {
  252. llvm::PrettyStackTraceString CrashInfo("Compilation construction");
  253. // FIXME: Handle environment options which affect driver behavior, somewhere
  254. // (client?). GCC_EXEC_PREFIX, LPATH, CC_PRINT_OPTIONS.
  255. if (char *env = ::getenv("COMPILER_PATH")) {
  256. StringRef CompilerPath = env;
  257. while (!CompilerPath.empty()) {
  258. std::pair<StringRef, StringRef> Split
  259. = CompilerPath.split(llvm::sys::EnvPathSeparator);
  260. PrefixDirs.push_back(Split.first);
  261. CompilerPath = Split.second;
  262. }
  263. }
  264. // We look for the driver mode option early, because the mode can affect
  265. // how other options are parsed.
  266. ParseDriverMode(ArgList.slice(1));
  267. // FIXME: What are we going to do with -V and -b?
  268. // FIXME: This stuff needs to go into the Compilation, not the driver.
  269. bool CCCPrintActions;
  270. InputArgList *Args = ParseArgStrings(ArgList.slice(1));
  271. // -no-canonical-prefixes is used very early in main.
  272. Args->ClaimAllArgs(options::OPT_no_canonical_prefixes);
  273. // Ignore -pipe.
  274. Args->ClaimAllArgs(options::OPT_pipe);
  275. // Extract -ccc args.
  276. //
  277. // FIXME: We need to figure out where this behavior should live. Most of it
  278. // should be outside in the client; the parts that aren't should have proper
  279. // options, either by introducing new ones or by overloading gcc ones like -V
  280. // or -b.
  281. CCCPrintActions = Args->hasArg(options::OPT_ccc_print_phases);
  282. CCCPrintBindings = Args->hasArg(options::OPT_ccc_print_bindings);
  283. if (const Arg *A = Args->getLastArg(options::OPT_ccc_gcc_name))
  284. CCCGenericGCCName = A->getValue();
  285. CCCUsePCH = Args->hasFlag(options::OPT_ccc_pch_is_pch,
  286. options::OPT_ccc_pch_is_pth);
  287. // FIXME: DefaultTargetTriple is used by the target-prefixed calls to as/ld
  288. // and getToolChain is const.
  289. if (IsCLMode()) {
  290. // clang-cl targets MSVC-style Win32.
  291. llvm::Triple T(DefaultTargetTriple);
  292. T.setOS(llvm::Triple::Win32);
  293. T.setEnvironment(llvm::Triple::MSVC);
  294. DefaultTargetTriple = T.str();
  295. }
  296. if (const Arg *A = Args->getLastArg(options::OPT_target))
  297. DefaultTargetTriple = A->getValue();
  298. if (const Arg *A = Args->getLastArg(options::OPT_ccc_install_dir))
  299. Dir = InstalledDir = A->getValue();
  300. for (arg_iterator it = Args->filtered_begin(options::OPT_B),
  301. ie = Args->filtered_end(); it != ie; ++it) {
  302. const Arg *A = *it;
  303. A->claim();
  304. PrefixDirs.push_back(A->getValue(0));
  305. }
  306. if (const Arg *A = Args->getLastArg(options::OPT__sysroot_EQ))
  307. SysRoot = A->getValue();
  308. if (const Arg *A = Args->getLastArg(options::OPT__dyld_prefix_EQ))
  309. DyldPrefix = A->getValue();
  310. if (Args->hasArg(options::OPT_nostdlib))
  311. UseStdLib = false;
  312. if (const Arg *A = Args->getLastArg(options::OPT_resource_dir))
  313. ResourceDir = A->getValue();
  314. // Perform the default argument translations.
  315. DerivedArgList *TranslatedArgs = TranslateInputArgs(*Args);
  316. // Owned by the host.
  317. const ToolChain &TC = getToolChain(*Args);
  318. // The compilation takes ownership of Args.
  319. Compilation *C = new Compilation(*this, TC, Args, TranslatedArgs);
  320. if (!HandleImmediateArgs(*C))
  321. return C;
  322. // Construct the list of inputs.
  323. InputList Inputs;
  324. BuildInputs(C->getDefaultToolChain(), *TranslatedArgs, Inputs);
  325. // Construct the list of abstract actions to perform for this compilation. On
  326. // MachO targets this uses the driver-driver and universal actions.
  327. if (TC.getTriple().isOSBinFormatMachO())
  328. BuildUniversalActions(C->getDefaultToolChain(), C->getArgs(),
  329. Inputs, C->getActions());
  330. else
  331. BuildActions(C->getDefaultToolChain(), C->getArgs(), Inputs,
  332. C->getActions());
  333. if (CCCPrintActions) {
  334. PrintActions(*C);
  335. return C;
  336. }
  337. BuildJobs(*C);
  338. return C;
  339. }
  340. // When clang crashes, produce diagnostic information including the fully
  341. // preprocessed source file(s). Request that the developer attach the
  342. // diagnostic information to a bug report.
  343. void Driver::generateCompilationDiagnostics(Compilation &C,
  344. const Command *FailingCommand) {
  345. if (C.getArgs().hasArg(options::OPT_fno_crash_diagnostics))
  346. return;
  347. // Don't try to generate diagnostics for link or dsymutil jobs.
  348. if (FailingCommand && (FailingCommand->getCreator().isLinkJob() ||
  349. FailingCommand->getCreator().isDsymutilJob()))
  350. return;
  351. // Print the version of the compiler.
  352. PrintVersion(C, llvm::errs());
  353. Diag(clang::diag::note_drv_command_failed_diag_msg)
  354. << "PLEASE submit a bug report to " BUG_REPORT_URL " and include the "
  355. "crash backtrace, preprocessed source, and associated run script.";
  356. // Suppress driver output and emit preprocessor output to temp file.
  357. Mode = CPPMode;
  358. CCGenDiagnostics = true;
  359. // Save the original job command(s).
  360. std::string Cmd;
  361. llvm::raw_string_ostream OS(Cmd);
  362. if (FailingCommand)
  363. FailingCommand->Print(OS, "\n", /*Quote*/ false, /*CrashReport*/ true);
  364. else
  365. // Crash triggered by FORCE_CLANG_DIAGNOSTICS_CRASH, which doesn't have an
  366. // associated FailingCommand, so just pass all jobs.
  367. C.getJobs().Print(OS, "\n", /*Quote*/ false, /*CrashReport*/ true);
  368. OS.flush();
  369. // Keep track of whether we produce any errors while trying to produce
  370. // preprocessed sources.
  371. DiagnosticErrorTrap Trap(Diags);
  372. // Suppress tool output.
  373. C.initCompilationForDiagnostics();
  374. // Construct the list of inputs.
  375. InputList Inputs;
  376. BuildInputs(C.getDefaultToolChain(), C.getArgs(), Inputs);
  377. for (InputList::iterator it = Inputs.begin(), ie = Inputs.end(); it != ie;) {
  378. bool IgnoreInput = false;
  379. // Ignore input from stdin or any inputs that cannot be preprocessed.
  380. // Check type first as not all linker inputs have a value.
  381. if (types::getPreprocessedType(it->first) == types::TY_INVALID) {
  382. IgnoreInput = true;
  383. } else if (!strcmp(it->second->getValue(), "-")) {
  384. Diag(clang::diag::note_drv_command_failed_diag_msg)
  385. << "Error generating preprocessed source(s) - ignoring input from stdin"
  386. ".";
  387. IgnoreInput = true;
  388. }
  389. if (IgnoreInput) {
  390. it = Inputs.erase(it);
  391. ie = Inputs.end();
  392. } else {
  393. ++it;
  394. }
  395. }
  396. if (Inputs.empty()) {
  397. Diag(clang::diag::note_drv_command_failed_diag_msg)
  398. << "Error generating preprocessed source(s) - no preprocessable inputs.";
  399. return;
  400. }
  401. // Don't attempt to generate preprocessed files if multiple -arch options are
  402. // used, unless they're all duplicates.
  403. llvm::StringSet<> ArchNames;
  404. for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
  405. it != ie; ++it) {
  406. Arg *A = *it;
  407. if (A->getOption().matches(options::OPT_arch)) {
  408. StringRef ArchName = A->getValue();
  409. ArchNames.insert(ArchName);
  410. }
  411. }
  412. if (ArchNames.size() > 1) {
  413. Diag(clang::diag::note_drv_command_failed_diag_msg)
  414. << "Error generating preprocessed source(s) - cannot generate "
  415. "preprocessed source with multiple -arch options.";
  416. return;
  417. }
  418. // Construct the list of abstract actions to perform for this compilation. On
  419. // Darwin OSes this uses the driver-driver and builds universal actions.
  420. const ToolChain &TC = C.getDefaultToolChain();
  421. if (TC.getTriple().isOSBinFormatMachO())
  422. BuildUniversalActions(TC, C.getArgs(), Inputs, C.getActions());
  423. else
  424. BuildActions(TC, C.getArgs(), Inputs, C.getActions());
  425. BuildJobs(C);
  426. // If there were errors building the compilation, quit now.
  427. if (Trap.hasErrorOccurred()) {
  428. Diag(clang::diag::note_drv_command_failed_diag_msg)
  429. << "Error generating preprocessed source(s).";
  430. return;
  431. }
  432. // Generate preprocessed output.
  433. SmallVector<std::pair<int, const Command *>, 4> FailingCommands;
  434. C.ExecuteJob(C.getJobs(), FailingCommands);
  435. // If the command succeeded, we are done.
  436. if (FailingCommands.empty()) {
  437. Diag(clang::diag::note_drv_command_failed_diag_msg)
  438. << "\n********************\n\n"
  439. "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
  440. "Preprocessed source(s) and associated run script(s) are located at:";
  441. ArgStringList Files = C.getTempFiles();
  442. for (ArgStringList::const_iterator it = Files.begin(), ie = Files.end();
  443. it != ie; ++it) {
  444. Diag(clang::diag::note_drv_command_failed_diag_msg) << *it;
  445. std::string Script = StringRef(*it).rsplit('.').first;
  446. // In some cases (modules) we'll dump extra data to help with reproducing
  447. // the crash into a directory next to the output.
  448. SmallString<128> VFS;
  449. if (llvm::sys::fs::exists(Script + ".cache")) {
  450. Diag(clang::diag::note_drv_command_failed_diag_msg)
  451. << Script + ".cache";
  452. VFS = llvm::sys::path::filename(Script + ".cache");
  453. llvm::sys::path::append(VFS, "vfs", "vfs.yaml");
  454. }
  455. std::error_code EC;
  456. Script += ".sh";
  457. llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
  458. if (EC) {
  459. Diag(clang::diag::note_drv_command_failed_diag_msg)
  460. << "Error generating run script: " + Script + " " + EC.message();
  461. } else {
  462. // Replace the original filename with the preprocessed one.
  463. size_t I, E;
  464. I = Cmd.find("-main-file-name ");
  465. assert (I != std::string::npos && "Expected to find -main-file-name");
  466. I += 16;
  467. E = Cmd.find(" ", I);
  468. assert (E != std::string::npos && "-main-file-name missing argument?");
  469. StringRef OldFilename = StringRef(Cmd).slice(I, E);
  470. StringRef NewFilename = llvm::sys::path::filename(*it);
  471. I = StringRef(Cmd).rfind(OldFilename);
  472. E = I + OldFilename.size();
  473. if (E + 1 < Cmd.size() && Cmd[E] == '"')
  474. ++E; // Replace a trailing quote if present.
  475. I = Cmd.rfind(" ", I) + 1;
  476. Cmd.replace(I, E - I, NewFilename.data(), NewFilename.size());
  477. if (!VFS.empty()) {
  478. // Add the VFS overlay to the reproduction script.
  479. I += NewFilename.size();
  480. Cmd.insert(I, std::string(" -ivfsoverlay ") + VFS.c_str());
  481. }
  482. ScriptOS << Cmd;
  483. Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
  484. }
  485. }
  486. Diag(clang::diag::note_drv_command_failed_diag_msg)
  487. << "\n\n********************";
  488. } else {
  489. // Failure, remove preprocessed files.
  490. if (!C.getArgs().hasArg(options::OPT_save_temps))
  491. C.CleanupFileList(C.getTempFiles(), true);
  492. Diag(clang::diag::note_drv_command_failed_diag_msg)
  493. << "Error generating preprocessed source(s).";
  494. }
  495. }
  496. int Driver::ExecuteCompilation(const Compilation &C,
  497. SmallVectorImpl< std::pair<int, const Command *> > &FailingCommands) const {
  498. // Just print if -### was present.
  499. if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  500. C.getJobs().Print(llvm::errs(), "\n", true);
  501. return 0;
  502. }
  503. // If there were errors building the compilation, quit now.
  504. if (Diags.hasErrorOccurred())
  505. return 1;
  506. C.ExecuteJob(C.getJobs(), FailingCommands);
  507. // Remove temp files.
  508. C.CleanupFileList(C.getTempFiles());
  509. // If the command succeeded, we are done.
  510. if (FailingCommands.empty())
  511. return 0;
  512. // Otherwise, remove result files and print extra information about abnormal
  513. // failures.
  514. for (SmallVectorImpl< std::pair<int, const Command *> >::iterator it =
  515. FailingCommands.begin(), ie = FailingCommands.end(); it != ie; ++it) {
  516. int Res = it->first;
  517. const Command *FailingCommand = it->second;
  518. // Remove result files if we're not saving temps.
  519. if (!C.getArgs().hasArg(options::OPT_save_temps)) {
  520. const JobAction *JA = cast<JobAction>(&FailingCommand->getSource());
  521. C.CleanupFileMap(C.getResultFiles(), JA, true);
  522. // Failure result files are valid unless we crashed.
  523. if (Res < 0)
  524. C.CleanupFileMap(C.getFailureResultFiles(), JA, true);
  525. }
  526. // Print extra information about abnormal failures, if possible.
  527. //
  528. // This is ad-hoc, but we don't want to be excessively noisy. If the result
  529. // status was 1, assume the command failed normally. In particular, if it
  530. // was the compiler then assume it gave a reasonable error code. Failures
  531. // in other tools are less common, and they generally have worse
  532. // diagnostics, so always print the diagnostic there.
  533. const Tool &FailingTool = FailingCommand->getCreator();
  534. if (!FailingCommand->getCreator().hasGoodDiagnostics() || Res != 1) {
  535. // FIXME: See FIXME above regarding result code interpretation.
  536. if (Res < 0)
  537. Diag(clang::diag::err_drv_command_signalled)
  538. << FailingTool.getShortName();
  539. else
  540. Diag(clang::diag::err_drv_command_failed)
  541. << FailingTool.getShortName() << Res;
  542. }
  543. }
  544. return 0;
  545. }
  546. void Driver::PrintHelp(bool ShowHidden) const {
  547. unsigned IncludedFlagsBitmask;
  548. unsigned ExcludedFlagsBitmask;
  549. std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
  550. getIncludeExcludeOptionFlagMasks();
  551. ExcludedFlagsBitmask |= options::NoDriverOption;
  552. if (!ShowHidden)
  553. ExcludedFlagsBitmask |= HelpHidden;
  554. getOpts().PrintHelp(llvm::outs(), Name.c_str(), DriverTitle.c_str(),
  555. IncludedFlagsBitmask, ExcludedFlagsBitmask);
  556. }
  557. void Driver::PrintVersion(const Compilation &C, raw_ostream &OS) const {
  558. // FIXME: The following handlers should use a callback mechanism, we don't
  559. // know what the client would like to do.
  560. OS << getClangFullVersion() << '\n';
  561. const ToolChain &TC = C.getDefaultToolChain();
  562. OS << "Target: " << TC.getTripleString() << '\n';
  563. // Print the threading model.
  564. //
  565. // FIXME: Implement correctly.
  566. OS << "Thread model: " << "posix" << '\n';
  567. }
  568. /// PrintDiagnosticCategories - Implement the --print-diagnostic-categories
  569. /// option.
  570. static void PrintDiagnosticCategories(raw_ostream &OS) {
  571. // Skip the empty category.
  572. for (unsigned i = 1, max = DiagnosticIDs::getNumberOfCategories();
  573. i != max; ++i)
  574. OS << i << ',' << DiagnosticIDs::getCategoryNameFromID(i) << '\n';
  575. }
  576. bool Driver::HandleImmediateArgs(const Compilation &C) {
  577. // The order these options are handled in gcc is all over the place, but we
  578. // don't expect inconsistencies w.r.t. that to matter in practice.
  579. if (C.getArgs().hasArg(options::OPT_dumpmachine)) {
  580. llvm::outs() << C.getDefaultToolChain().getTripleString() << '\n';
  581. return false;
  582. }
  583. if (C.getArgs().hasArg(options::OPT_dumpversion)) {
  584. // Since -dumpversion is only implemented for pedantic GCC compatibility, we
  585. // return an answer which matches our definition of __VERSION__.
  586. //
  587. // If we want to return a more correct answer some day, then we should
  588. // introduce a non-pedantically GCC compatible mode to Clang in which we
  589. // provide sensible definitions for -dumpversion, __VERSION__, etc.
  590. llvm::outs() << "4.2.1\n";
  591. return false;
  592. }
  593. if (C.getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
  594. PrintDiagnosticCategories(llvm::outs());
  595. return false;
  596. }
  597. if (C.getArgs().hasArg(options::OPT_help) ||
  598. C.getArgs().hasArg(options::OPT__help_hidden)) {
  599. PrintHelp(C.getArgs().hasArg(options::OPT__help_hidden));
  600. return false;
  601. }
  602. if (C.getArgs().hasArg(options::OPT__version)) {
  603. // Follow gcc behavior and use stdout for --version and stderr for -v.
  604. PrintVersion(C, llvm::outs());
  605. return false;
  606. }
  607. if (C.getArgs().hasArg(options::OPT_v) ||
  608. C.getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
  609. PrintVersion(C, llvm::errs());
  610. SuppressMissingInputWarning = true;
  611. }
  612. const ToolChain &TC = C.getDefaultToolChain();
  613. if (C.getArgs().hasArg(options::OPT_v))
  614. TC.printVerboseInfo(llvm::errs());
  615. if (C.getArgs().hasArg(options::OPT_print_search_dirs)) {
  616. llvm::outs() << "programs: =";
  617. for (ToolChain::path_list::const_iterator it = TC.getProgramPaths().begin(),
  618. ie = TC.getProgramPaths().end(); it != ie; ++it) {
  619. if (it != TC.getProgramPaths().begin())
  620. llvm::outs() << ':';
  621. llvm::outs() << *it;
  622. }
  623. llvm::outs() << "\n";
  624. llvm::outs() << "libraries: =" << ResourceDir;
  625. StringRef sysroot = C.getSysRoot();
  626. for (ToolChain::path_list::const_iterator it = TC.getFilePaths().begin(),
  627. ie = TC.getFilePaths().end(); it != ie; ++it) {
  628. llvm::outs() << ':';
  629. const char *path = it->c_str();
  630. if (path[0] == '=')
  631. llvm::outs() << sysroot << path + 1;
  632. else
  633. llvm::outs() << path;
  634. }
  635. llvm::outs() << "\n";
  636. return false;
  637. }
  638. // FIXME: The following handlers should use a callback mechanism, we don't
  639. // know what the client would like to do.
  640. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
  641. llvm::outs() << GetFilePath(A->getValue(), TC) << "\n";
  642. return false;
  643. }
  644. if (Arg *A = C.getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
  645. llvm::outs() << GetProgramPath(A->getValue(), TC) << "\n";
  646. return false;
  647. }
  648. if (C.getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
  649. llvm::outs() << GetFilePath("libgcc.a", TC) << "\n";
  650. return false;
  651. }
  652. if (C.getArgs().hasArg(options::OPT_print_multi_lib)) {
  653. const MultilibSet &Multilibs = TC.getMultilibs();
  654. for (MultilibSet::const_iterator I = Multilibs.begin(), E = Multilibs.end();
  655. I != E; ++I) {
  656. llvm::outs() << *I << "\n";
  657. }
  658. return false;
  659. }
  660. if (C.getArgs().hasArg(options::OPT_print_multi_directory)) {
  661. const MultilibSet &Multilibs = TC.getMultilibs();
  662. for (MultilibSet::const_iterator I = Multilibs.begin(), E = Multilibs.end();
  663. I != E; ++I) {
  664. if (I->gccSuffix().empty())
  665. llvm::outs() << ".\n";
  666. else {
  667. StringRef Suffix(I->gccSuffix());
  668. assert(Suffix.front() == '/');
  669. llvm::outs() << Suffix.substr(1) << "\n";
  670. }
  671. }
  672. return false;
  673. }
  674. if (C.getArgs().hasArg(options::OPT_print_multi_os_directory)) {
  675. // FIXME: This should print out "lib/../lib", "lib/../lib64", or
  676. // "lib/../lib32" as appropriate for the toolchain. For now, print
  677. // nothing because it's not supported yet.
  678. return false;
  679. }
  680. return true;
  681. }
  682. static unsigned PrintActions1(const Compilation &C, Action *A,
  683. std::map<Action*, unsigned> &Ids) {
  684. if (Ids.count(A))
  685. return Ids[A];
  686. std::string str;
  687. llvm::raw_string_ostream os(str);
  688. os << Action::getClassName(A->getKind()) << ", ";
  689. if (InputAction *IA = dyn_cast<InputAction>(A)) {
  690. os << "\"" << IA->getInputArg().getValue() << "\"";
  691. } else if (BindArchAction *BIA = dyn_cast<BindArchAction>(A)) {
  692. os << '"' << BIA->getArchName() << '"'
  693. << ", {" << PrintActions1(C, *BIA->begin(), Ids) << "}";
  694. } else {
  695. os << "{";
  696. for (Action::iterator it = A->begin(), ie = A->end(); it != ie;) {
  697. os << PrintActions1(C, *it, Ids);
  698. ++it;
  699. if (it != ie)
  700. os << ", ";
  701. }
  702. os << "}";
  703. }
  704. unsigned Id = Ids.size();
  705. Ids[A] = Id;
  706. llvm::errs() << Id << ": " << os.str() << ", "
  707. << types::getTypeName(A->getType()) << "\n";
  708. return Id;
  709. }
  710. void Driver::PrintActions(const Compilation &C) const {
  711. std::map<Action*, unsigned> Ids;
  712. for (ActionList::const_iterator it = C.getActions().begin(),
  713. ie = C.getActions().end(); it != ie; ++it)
  714. PrintActions1(C, *it, Ids);
  715. }
  716. /// \brief Check whether the given input tree contains any compilation or
  717. /// assembly actions.
  718. static bool ContainsCompileOrAssembleAction(const Action *A) {
  719. if (isa<CompileJobAction>(A) || isa<AssembleJobAction>(A))
  720. return true;
  721. for (Action::const_iterator it = A->begin(), ie = A->end(); it != ie; ++it)
  722. if (ContainsCompileOrAssembleAction(*it))
  723. return true;
  724. return false;
  725. }
  726. void Driver::BuildUniversalActions(const ToolChain &TC,
  727. DerivedArgList &Args,
  728. const InputList &BAInputs,
  729. ActionList &Actions) const {
  730. llvm::PrettyStackTraceString CrashInfo("Building universal build actions");
  731. // Collect the list of architectures. Duplicates are allowed, but should only
  732. // be handled once (in the order seen).
  733. llvm::StringSet<> ArchNames;
  734. SmallVector<const char *, 4> Archs;
  735. for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
  736. it != ie; ++it) {
  737. Arg *A = *it;
  738. if (A->getOption().matches(options::OPT_arch)) {
  739. // Validate the option here; we don't save the type here because its
  740. // particular spelling may participate in other driver choices.
  741. llvm::Triple::ArchType Arch =
  742. tools::darwin::getArchTypeForMachOArchName(A->getValue());
  743. if (Arch == llvm::Triple::UnknownArch) {
  744. Diag(clang::diag::err_drv_invalid_arch_name)
  745. << A->getAsString(Args);
  746. continue;
  747. }
  748. A->claim();
  749. if (ArchNames.insert(A->getValue()))
  750. Archs.push_back(A->getValue());
  751. }
  752. }
  753. // When there is no explicit arch for this platform, make sure we still bind
  754. // the architecture (to the default) so that -Xarch_ is handled correctly.
  755. if (!Archs.size())
  756. Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
  757. ActionList SingleActions;
  758. BuildActions(TC, Args, BAInputs, SingleActions);
  759. // Add in arch bindings for every top level action, as well as lipo and
  760. // dsymutil steps if needed.
  761. for (unsigned i = 0, e = SingleActions.size(); i != e; ++i) {
  762. Action *Act = SingleActions[i];
  763. // Make sure we can lipo this kind of output. If not (and it is an actual
  764. // output) then we disallow, since we can't create an output file with the
  765. // right name without overwriting it. We could remove this oddity by just
  766. // changing the output names to include the arch, which would also fix
  767. // -save-temps. Compatibility wins for now.
  768. if (Archs.size() > 1 && !types::canLipoType(Act->getType()))
  769. Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
  770. << types::getTypeName(Act->getType());
  771. ActionList Inputs;
  772. for (unsigned i = 0, e = Archs.size(); i != e; ++i) {
  773. Inputs.push_back(new BindArchAction(Act, Archs[i]));
  774. if (i != 0)
  775. Inputs.back()->setOwnsInputs(false);
  776. }
  777. // Lipo if necessary, we do it this way because we need to set the arch flag
  778. // so that -Xarch_ gets overwritten.
  779. if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
  780. Actions.append(Inputs.begin(), Inputs.end());
  781. else
  782. Actions.push_back(new LipoJobAction(Inputs, Act->getType()));
  783. // Handle debug info queries.
  784. Arg *A = Args.getLastArg(options::OPT_g_Group);
  785. if (A && !A->getOption().matches(options::OPT_g0) &&
  786. !A->getOption().matches(options::OPT_gstabs) &&
  787. ContainsCompileOrAssembleAction(Actions.back())) {
  788. // Add a 'dsymutil' step if necessary, when debug info is enabled and we
  789. // have a compile input. We need to run 'dsymutil' ourselves in such cases
  790. // because the debug info will refer to a temporary object file which
  791. // will be removed at the end of the compilation process.
  792. if (Act->getType() == types::TY_Image) {
  793. ActionList Inputs;
  794. Inputs.push_back(Actions.back());
  795. Actions.pop_back();
  796. Actions.push_back(new DsymutilJobAction(Inputs, types::TY_dSYM));
  797. }
  798. // Verify the debug info output.
  799. if (Args.hasArg(options::OPT_verify_debug_info)) {
  800. Action *VerifyInput = Actions.back();
  801. Actions.pop_back();
  802. Actions.push_back(new VerifyDebugInfoJobAction(VerifyInput,
  803. types::TY_Nothing));
  804. }
  805. }
  806. }
  807. }
  808. /// \brief Check that the file referenced by Value exists. If it doesn't,
  809. /// issue a diagnostic and return false.
  810. static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args,
  811. StringRef Value) {
  812. if (!D.getCheckInputsExist())
  813. return true;
  814. // stdin always exists.
  815. if (Value == "-")
  816. return true;
  817. SmallString<64> Path(Value);
  818. if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
  819. if (!llvm::sys::path::is_absolute(Path.str())) {
  820. SmallString<64> Directory(WorkDir->getValue());
  821. llvm::sys::path::append(Directory, Value);
  822. Path.assign(Directory);
  823. }
  824. }
  825. if (llvm::sys::fs::exists(Twine(Path)))
  826. return true;
  827. if (D.IsCLMode() && llvm::sys::Process::FindInEnvPath("LIB", Value))
  828. return true;
  829. D.Diag(clang::diag::err_drv_no_such_file) << Path.str();
  830. return false;
  831. }
  832. // Construct a the list of inputs and their types.
  833. void Driver::BuildInputs(const ToolChain &TC, DerivedArgList &Args,
  834. InputList &Inputs) const {
  835. // Track the current user specified (-x) input. We also explicitly track the
  836. // argument used to set the type; we only want to claim the type when we
  837. // actually use it, so we warn about unused -x arguments.
  838. types::ID InputType = types::TY_Nothing;
  839. Arg *InputTypeArg = nullptr;
  840. // The last /TC or /TP option sets the input type to C or C++ globally.
  841. if (Arg *TCTP = Args.getLastArg(options::OPT__SLASH_TC,
  842. options::OPT__SLASH_TP)) {
  843. InputTypeArg = TCTP;
  844. InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
  845. ? types::TY_C : types::TY_CXX;
  846. arg_iterator it = Args.filtered_begin(options::OPT__SLASH_TC,
  847. options::OPT__SLASH_TP);
  848. const arg_iterator ie = Args.filtered_end();
  849. Arg *Previous = *it++;
  850. bool ShowNote = false;
  851. while (it != ie) {
  852. Diag(clang::diag::warn_drv_overriding_flag_option)
  853. << Previous->getSpelling() << (*it)->getSpelling();
  854. Previous = *it++;
  855. ShowNote = true;
  856. }
  857. if (ShowNote)
  858. Diag(clang::diag::note_drv_t_option_is_global);
  859. // No driver mode exposes -x and /TC or /TP; we don't support mixing them.
  860. assert(!Args.hasArg(options::OPT_x) && "-x and /TC or /TP is not allowed");
  861. }
  862. for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
  863. it != ie; ++it) {
  864. Arg *A = *it;
  865. if (A->getOption().getKind() == Option::InputClass) {
  866. const char *Value = A->getValue();
  867. types::ID Ty = types::TY_INVALID;
  868. // Infer the input type if necessary.
  869. if (InputType == types::TY_Nothing) {
  870. // If there was an explicit arg for this, claim it.
  871. if (InputTypeArg)
  872. InputTypeArg->claim();
  873. // stdin must be handled specially.
  874. if (memcmp(Value, "-", 2) == 0) {
  875. // If running with -E, treat as a C input (this changes the builtin
  876. // macros, for example). This may be overridden by -ObjC below.
  877. //
  878. // Otherwise emit an error but still use a valid type to avoid
  879. // spurious errors (e.g., no inputs).
  880. if (!Args.hasArgNoClaim(options::OPT_E) && !CCCIsCPP())
  881. Diag(IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
  882. : clang::diag::err_drv_unknown_stdin_type);
  883. Ty = types::TY_C;
  884. } else {
  885. // Otherwise lookup by extension.
  886. // Fallback is C if invoked as C preprocessor or Object otherwise.
  887. // We use a host hook here because Darwin at least has its own
  888. // idea of what .s is.
  889. if (const char *Ext = strrchr(Value, '.'))
  890. Ty = TC.LookupTypeForExtension(Ext + 1);
  891. if (Ty == types::TY_INVALID) {
  892. if (CCCIsCPP())
  893. Ty = types::TY_C;
  894. else
  895. Ty = types::TY_Object;
  896. }
  897. // If the driver is invoked as C++ compiler (like clang++ or c++) it
  898. // should autodetect some input files as C++ for g++ compatibility.
  899. if (CCCIsCXX()) {
  900. types::ID OldTy = Ty;
  901. Ty = types::lookupCXXTypeForCType(Ty);
  902. if (Ty != OldTy)
  903. Diag(clang::diag::warn_drv_treating_input_as_cxx)
  904. << getTypeName(OldTy) << getTypeName(Ty);
  905. }
  906. }
  907. // -ObjC and -ObjC++ override the default language, but only for "source
  908. // files". We just treat everything that isn't a linker input as a
  909. // source file.
  910. //
  911. // FIXME: Clean this up if we move the phase sequence into the type.
  912. if (Ty != types::TY_Object) {
  913. if (Args.hasArg(options::OPT_ObjC))
  914. Ty = types::TY_ObjC;
  915. else if (Args.hasArg(options::OPT_ObjCXX))
  916. Ty = types::TY_ObjCXX;
  917. }
  918. } else {
  919. assert(InputTypeArg && "InputType set w/o InputTypeArg");
  920. InputTypeArg->claim();
  921. Ty = InputType;
  922. }
  923. if (DiagnoseInputExistence(*this, Args, Value))
  924. Inputs.push_back(std::make_pair(Ty, A));
  925. } else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
  926. StringRef Value = A->getValue();
  927. if (DiagnoseInputExistence(*this, Args, Value)) {
  928. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  929. Inputs.push_back(std::make_pair(types::TY_C, InputArg));
  930. }
  931. A->claim();
  932. } else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
  933. StringRef Value = A->getValue();
  934. if (DiagnoseInputExistence(*this, Args, Value)) {
  935. Arg *InputArg = MakeInputArg(Args, Opts, A->getValue());
  936. Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
  937. }
  938. A->claim();
  939. } else if (A->getOption().hasFlag(options::LinkerInput)) {
  940. // Just treat as object type, we could make a special type for this if
  941. // necessary.
  942. Inputs.push_back(std::make_pair(types::TY_Object, A));
  943. } else if (A->getOption().matches(options::OPT_x)) {
  944. InputTypeArg = A;
  945. InputType = types::lookupTypeForTypeSpecifier(A->getValue());
  946. A->claim();
  947. // Follow gcc behavior and treat as linker input for invalid -x
  948. // options. Its not clear why we shouldn't just revert to unknown; but
  949. // this isn't very important, we might as well be bug compatible.
  950. if (!InputType) {
  951. Diag(clang::diag::err_drv_unknown_language) << A->getValue();
  952. InputType = types::TY_Object;
  953. }
  954. }
  955. }
  956. if (CCCIsCPP() && Inputs.empty()) {
  957. // If called as standalone preprocessor, stdin is processed
  958. // if no other input is present.
  959. Arg *A = MakeInputArg(Args, Opts, "-");
  960. Inputs.push_back(std::make_pair(types::TY_C, A));
  961. }
  962. }
  963. void Driver::BuildActions(const ToolChain &TC, DerivedArgList &Args,
  964. const InputList &Inputs, ActionList &Actions) const {
  965. llvm::PrettyStackTraceString CrashInfo("Building compilation actions");
  966. if (!SuppressMissingInputWarning && Inputs.empty()) {
  967. Diag(clang::diag::err_drv_no_input_files);
  968. return;
  969. }
  970. Arg *FinalPhaseArg;
  971. phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
  972. if (FinalPhase == phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
  973. Diag(clang::diag::err_drv_emit_llvm_link);
  974. }
  975. // Reject -Z* at the top level, these options should never have been exposed
  976. // by gcc.
  977. if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
  978. Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
  979. // Diagnose misuse of /Fo.
  980. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
  981. StringRef V = A->getValue();
  982. if (V.empty()) {
  983. // It has to have a value.
  984. Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
  985. Args.eraseArg(options::OPT__SLASH_Fo);
  986. } else if (Inputs.size() > 1 && !llvm::sys::path::is_separator(V.back())) {
  987. // Check whether /Fo tries to name an output file for multiple inputs.
  988. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  989. << A->getSpelling() << V;
  990. Args.eraseArg(options::OPT__SLASH_Fo);
  991. }
  992. }
  993. // Diagnose misuse of /Fa.
  994. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
  995. StringRef V = A->getValue();
  996. if (Inputs.size() > 1 && !llvm::sys::path::is_separator(V.back())) {
  997. // Check whether /Fa tries to name an asm file for multiple inputs.
  998. Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
  999. << A->getSpelling() << V;
  1000. Args.eraseArg(options::OPT__SLASH_Fa);
  1001. }
  1002. }
  1003. // Diagnose misuse of /Fe.
  1004. if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fe)) {
  1005. if (A->getValue()[0] == '\0') {
  1006. // It has to have a value.
  1007. Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
  1008. Args.eraseArg(options::OPT__SLASH_Fe);
  1009. }
  1010. }
  1011. // Construct the actions to perform.
  1012. ActionList LinkerInputs;
  1013. llvm::SmallVector<phases::ID, phases::MaxNumberOfPhases> PL;
  1014. for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
  1015. types::ID InputType = Inputs[i].first;
  1016. const Arg *InputArg = Inputs[i].second;
  1017. PL.clear();
  1018. types::getCompilationPhases(InputType, PL);
  1019. // If the first step comes after the final phase we are doing as part of
  1020. // this compilation, warn the user about it.
  1021. phases::ID InitialPhase = PL[0];
  1022. if (InitialPhase > FinalPhase) {
  1023. // Claim here to avoid the more general unused warning.
  1024. InputArg->claim();
  1025. // Suppress all unused style warnings with -Qunused-arguments
  1026. if (Args.hasArg(options::OPT_Qunused_arguments))
  1027. continue;
  1028. // Special case when final phase determined by binary name, rather than
  1029. // by a command-line argument with a corresponding Arg.
  1030. if (CCCIsCPP())
  1031. Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
  1032. << InputArg->getAsString(Args)
  1033. << getPhaseName(InitialPhase);
  1034. // Special case '-E' warning on a previously preprocessed file to make
  1035. // more sense.
  1036. else if (InitialPhase == phases::Compile &&
  1037. FinalPhase == phases::Preprocess &&
  1038. getPreprocessedType(InputType) == types::TY_INVALID)
  1039. Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
  1040. << InputArg->getAsString(Args)
  1041. << !!FinalPhaseArg
  1042. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  1043. else
  1044. Diag(clang::diag::warn_drv_input_file_unused)
  1045. << InputArg->getAsString(Args)
  1046. << getPhaseName(InitialPhase)
  1047. << !!FinalPhaseArg
  1048. << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() : "");
  1049. continue;
  1050. }
  1051. // Build the pipeline for this file.
  1052. std::unique_ptr<Action> Current(new InputAction(*InputArg, InputType));
  1053. for (SmallVectorImpl<phases::ID>::iterator
  1054. i = PL.begin(), e = PL.end(); i != e; ++i) {
  1055. phases::ID Phase = *i;
  1056. // We are done if this step is past what the user requested.
  1057. if (Phase > FinalPhase)
  1058. break;
  1059. // Queue linker inputs.
  1060. if (Phase == phases::Link) {
  1061. assert((i + 1) == e && "linking must be final compilation step.");
  1062. LinkerInputs.push_back(Current.release());
  1063. break;
  1064. }
  1065. // Some types skip the assembler phase (e.g., llvm-bc), but we can't
  1066. // encode this in the steps because the intermediate type depends on
  1067. // arguments. Just special case here.
  1068. if (Phase == phases::Assemble && Current->getType() != types::TY_PP_Asm)
  1069. continue;
  1070. // Otherwise construct the appropriate action.
  1071. Current.reset(ConstructPhaseAction(Args, Phase, Current.release()));
  1072. if (Current->getType() == types::TY_Nothing)
  1073. break;
  1074. }
  1075. // If we ended with something, add to the output list.
  1076. if (Current)
  1077. Actions.push_back(Current.release());
  1078. }
  1079. // Add a link action if necessary.
  1080. if (!LinkerInputs.empty())
  1081. Actions.push_back(new LinkJobAction(LinkerInputs, types::TY_Image));
  1082. // If we are linking, claim any options which are obviously only used for
  1083. // compilation.
  1084. if (FinalPhase == phases::Link && PL.size() == 1) {
  1085. Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
  1086. Args.ClaimAllArgs(options::OPT_cl_compile_Group);
  1087. }
  1088. // Claim ignored clang-cl options.
  1089. Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
  1090. }
  1091. Action *Driver::ConstructPhaseAction(const ArgList &Args, phases::ID Phase,
  1092. Action *Input) const {
  1093. llvm::PrettyStackTraceString CrashInfo("Constructing phase actions");
  1094. // Build the appropriate action.
  1095. switch (Phase) {
  1096. case phases::Link: llvm_unreachable("link action invalid here.");
  1097. case phases::Preprocess: {
  1098. types::ID OutputTy;
  1099. // -{M, MM} alter the output type.
  1100. if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
  1101. OutputTy = types::TY_Dependencies;
  1102. } else {
  1103. OutputTy = Input->getType();
  1104. if (!Args.hasFlag(options::OPT_frewrite_includes,
  1105. options::OPT_fno_rewrite_includes, false) &&
  1106. !CCGenDiagnostics)
  1107. OutputTy = types::getPreprocessedType(OutputTy);
  1108. assert(OutputTy != types::TY_INVALID &&
  1109. "Cannot preprocess this input type!");
  1110. }
  1111. return new PreprocessJobAction(Input, OutputTy);
  1112. }
  1113. case phases::Precompile: {
  1114. types::ID OutputTy = types::TY_PCH;
  1115. if (Args.hasArg(options::OPT_fsyntax_only)) {
  1116. // Syntax checks should not emit a PCH file
  1117. OutputTy = types::TY_Nothing;
  1118. }
  1119. return new PrecompileJobAction(Input, OutputTy);
  1120. }
  1121. case phases::Compile: {
  1122. if (Args.hasArg(options::OPT_fsyntax_only)) {
  1123. return new CompileJobAction(Input, types::TY_Nothing);
  1124. } else if (Args.hasArg(options::OPT_rewrite_objc)) {
  1125. return new CompileJobAction(Input, types::TY_RewrittenObjC);
  1126. } else if (Args.hasArg(options::OPT_rewrite_legacy_objc)) {
  1127. return new CompileJobAction(Input, types::TY_RewrittenLegacyObjC);
  1128. } else if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto)) {
  1129. return new AnalyzeJobAction(Input, types::TY_Plist);
  1130. } else if (Args.hasArg(options::OPT__migrate)) {
  1131. return new MigrateJobAction(Input, types::TY_Remap);
  1132. } else if (Args.hasArg(options::OPT_emit_ast)) {
  1133. return new CompileJobAction(Input, types::TY_AST);
  1134. } else if (Args.hasArg(options::OPT_module_file_info)) {
  1135. return new CompileJobAction(Input, types::TY_ModuleFile);
  1136. } else if (Args.hasArg(options::OPT_verify_pch)) {
  1137. return new VerifyPCHJobAction(Input, types::TY_Nothing);
  1138. } else if (IsUsingLTO(Args)) {
  1139. types::ID Output =
  1140. Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
  1141. return new CompileJobAction(Input, Output);
  1142. } else if (Args.hasArg(options::OPT_emit_llvm)) {
  1143. types::ID Output =
  1144. Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
  1145. return new CompileJobAction(Input, Output);
  1146. } else {
  1147. return new CompileJobAction(Input, types::TY_PP_Asm);
  1148. }
  1149. }
  1150. case phases::Assemble:
  1151. return new AssembleJobAction(Input, types::TY_Object);
  1152. }
  1153. llvm_unreachable("invalid phase in ConstructPhaseAction");
  1154. }
  1155. bool Driver::IsUsingLTO(const ArgList &Args) const {
  1156. if (Args.hasFlag(options::OPT_flto, options::OPT_fno_lto, false))
  1157. return true;
  1158. return false;
  1159. }
  1160. void Driver::BuildJobs(Compilation &C) const {
  1161. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1162. Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o);
  1163. // It is an error to provide a -o option if we are making multiple output
  1164. // files.
  1165. if (FinalOutput) {
  1166. unsigned NumOutputs = 0;
  1167. for (ActionList::const_iterator it = C.getActions().begin(),
  1168. ie = C.getActions().end(); it != ie; ++it)
  1169. if ((*it)->getType() != types::TY_Nothing)
  1170. ++NumOutputs;
  1171. if (NumOutputs > 1) {
  1172. Diag(clang::diag::err_drv_output_argument_with_multiple_files);
  1173. FinalOutput = nullptr;
  1174. }
  1175. }
  1176. // Collect the list of architectures.
  1177. llvm::StringSet<> ArchNames;
  1178. if (C.getDefaultToolChain().getTriple().isOSBinFormatMachO()) {
  1179. for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
  1180. it != ie; ++it) {
  1181. Arg *A = *it;
  1182. if (A->getOption().matches(options::OPT_arch))
  1183. ArchNames.insert(A->getValue());
  1184. }
  1185. }
  1186. for (ActionList::const_iterator it = C.getActions().begin(),
  1187. ie = C.getActions().end(); it != ie; ++it) {
  1188. Action *A = *it;
  1189. // If we are linking an image for multiple archs then the linker wants
  1190. // -arch_multiple and -final_output <final image name>. Unfortunately, this
  1191. // doesn't fit in cleanly because we have to pass this information down.
  1192. //
  1193. // FIXME: This is a hack; find a cleaner way to integrate this into the
  1194. // process.
  1195. const char *LinkingOutput = nullptr;
  1196. if (isa<LipoJobAction>(A)) {
  1197. if (FinalOutput)
  1198. LinkingOutput = FinalOutput->getValue();
  1199. else
  1200. LinkingOutput = DefaultImageName.c_str();
  1201. }
  1202. InputInfo II;
  1203. BuildJobsForAction(C, A, &C.getDefaultToolChain(),
  1204. /*BoundArch*/nullptr,
  1205. /*AtTopLevel*/ true,
  1206. /*MultipleArchs*/ ArchNames.size() > 1,
  1207. /*LinkingOutput*/ LinkingOutput,
  1208. II);
  1209. }
  1210. // If the user passed -Qunused-arguments or there were errors, don't warn
  1211. // about any unused arguments.
  1212. if (Diags.hasErrorOccurred() ||
  1213. C.getArgs().hasArg(options::OPT_Qunused_arguments))
  1214. return;
  1215. // Claim -### here.
  1216. (void) C.getArgs().hasArg(options::OPT__HASH_HASH_HASH);
  1217. // Claim --driver-mode, it was handled earlier.
  1218. (void) C.getArgs().hasArg(options::OPT_driver_mode);
  1219. for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
  1220. it != ie; ++it) {
  1221. Arg *A = *it;
  1222. // FIXME: It would be nice to be able to send the argument to the
  1223. // DiagnosticsEngine, so that extra values, position, and so on could be
  1224. // printed.
  1225. if (!A->isClaimed()) {
  1226. if (A->getOption().hasFlag(options::NoArgumentUnused))
  1227. continue;
  1228. // Suppress the warning automatically if this is just a flag, and it is an
  1229. // instance of an argument we already claimed.
  1230. const Option &Opt = A->getOption();
  1231. if (Opt.getKind() == Option::FlagClass) {
  1232. bool DuplicateClaimed = false;
  1233. for (arg_iterator it = C.getArgs().filtered_begin(&Opt),
  1234. ie = C.getArgs().filtered_end(); it != ie; ++it) {
  1235. if ((*it)->isClaimed()) {
  1236. DuplicateClaimed = true;
  1237. break;
  1238. }
  1239. }
  1240. if (DuplicateClaimed)
  1241. continue;
  1242. }
  1243. Diag(clang::diag::warn_drv_unused_argument)
  1244. << A->getAsString(C.getArgs());
  1245. }
  1246. }
  1247. }
  1248. static const Tool *SelectToolForJob(Compilation &C, const ToolChain *TC,
  1249. const JobAction *JA,
  1250. const ActionList *&Inputs) {
  1251. const Tool *ToolForJob = nullptr;
  1252. // See if we should look for a compiler with an integrated assembler. We match
  1253. // bottom up, so what we are actually looking for is an assembler job with a
  1254. // compiler input.
  1255. if (TC->useIntegratedAs() &&
  1256. !C.getArgs().hasArg(options::OPT_save_temps) &&
  1257. !C.getArgs().hasArg(options::OPT_via_file_asm) &&
  1258. !C.getArgs().hasArg(options::OPT__SLASH_FA) &&
  1259. !C.getArgs().hasArg(options::OPT__SLASH_Fa) &&
  1260. isa<AssembleJobAction>(JA) &&
  1261. Inputs->size() == 1 && isa<CompileJobAction>(*Inputs->begin())) {
  1262. const Tool *Compiler =
  1263. TC->SelectTool(cast<JobAction>(**Inputs->begin()));
  1264. if (!Compiler)
  1265. return nullptr;
  1266. if (Compiler->hasIntegratedAssembler()) {
  1267. Inputs = &(*Inputs)[0]->getInputs();
  1268. ToolForJob = Compiler;
  1269. }
  1270. }
  1271. // Otherwise use the tool for the current job.
  1272. if (!ToolForJob)
  1273. ToolForJob = TC->SelectTool(*JA);
  1274. // See if we should use an integrated preprocessor. We do so when we have
  1275. // exactly one input, since this is the only use case we care about
  1276. // (irrelevant since we don't support combine yet).
  1277. if (Inputs->size() == 1 && isa<PreprocessJobAction>(*Inputs->begin()) &&
  1278. !C.getArgs().hasArg(options::OPT_no_integrated_cpp) &&
  1279. !C.getArgs().hasArg(options::OPT_traditional_cpp) &&
  1280. !C.getArgs().hasArg(options::OPT_save_temps) &&
  1281. !C.getArgs().hasArg(options::OPT_rewrite_objc) &&
  1282. ToolForJob->hasIntegratedCPP())
  1283. Inputs = &(*Inputs)[0]->getInputs();
  1284. return ToolForJob;
  1285. }
  1286. void Driver::BuildJobsForAction(Compilation &C,
  1287. const Action *A,
  1288. const ToolChain *TC,
  1289. const char *BoundArch,
  1290. bool AtTopLevel,
  1291. bool MultipleArchs,
  1292. const char *LinkingOutput,
  1293. InputInfo &Result) const {
  1294. llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
  1295. if (const InputAction *IA = dyn_cast<InputAction>(A)) {
  1296. // FIXME: It would be nice to not claim this here; maybe the old scheme of
  1297. // just using Args was better?
  1298. const Arg &Input = IA->getInputArg();
  1299. Input.claim();
  1300. if (Input.getOption().matches(options::OPT_INPUT)) {
  1301. const char *Name = Input.getValue();
  1302. Result = InputInfo(Name, A->getType(), Name);
  1303. } else
  1304. Result = InputInfo(&Input, A->getType(), "");
  1305. return;
  1306. }
  1307. if (const BindArchAction *BAA = dyn_cast<BindArchAction>(A)) {
  1308. const ToolChain *TC;
  1309. const char *ArchName = BAA->getArchName();
  1310. if (ArchName)
  1311. TC = &getToolChain(C.getArgs(), ArchName);
  1312. else
  1313. TC = &C.getDefaultToolChain();
  1314. BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
  1315. AtTopLevel, MultipleArchs, LinkingOutput, Result);
  1316. return;
  1317. }
  1318. const ActionList *Inputs = &A->getInputs();
  1319. const JobAction *JA = cast<JobAction>(A);
  1320. const Tool *T = SelectToolForJob(C, TC, JA, Inputs);
  1321. if (!T)
  1322. return;
  1323. // Only use pipes when there is exactly one input.
  1324. InputInfoList InputInfos;
  1325. for (ActionList::const_iterator it = Inputs->begin(), ie = Inputs->end();
  1326. it != ie; ++it) {
  1327. // Treat dsymutil and verify sub-jobs as being at the top-level too, they
  1328. // shouldn't get temporary output names.
  1329. // FIXME: Clean this up.
  1330. bool SubJobAtTopLevel = false;
  1331. if (AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A)))
  1332. SubJobAtTopLevel = true;
  1333. InputInfo II;
  1334. BuildJobsForAction(C, *it, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
  1335. LinkingOutput, II);
  1336. InputInfos.push_back(II);
  1337. }
  1338. // Always use the first input as the base input.
  1339. const char *BaseInput = InputInfos[0].getBaseInput();
  1340. // ... except dsymutil actions, which use their actual input as the base
  1341. // input.
  1342. if (JA->getType() == types::TY_dSYM)
  1343. BaseInput = InputInfos[0].getFilename();
  1344. // Determine the place to write output to, if any.
  1345. if (JA->getType() == types::TY_Nothing)
  1346. Result = InputInfo(A->getType(), BaseInput);
  1347. else
  1348. Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
  1349. AtTopLevel, MultipleArchs),
  1350. A->getType(), BaseInput);
  1351. if (CCCPrintBindings && !CCGenDiagnostics) {
  1352. llvm::errs() << "# \"" << T->getToolChain().getTripleString() << '"'
  1353. << " - \"" << T->getName() << "\", inputs: [";
  1354. for (unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
  1355. llvm::errs() << InputInfos[i].getAsString();
  1356. if (i + 1 != e)
  1357. llvm::errs() << ", ";
  1358. }
  1359. llvm::errs() << "], output: " << Result.getAsString() << "\n";
  1360. } else {
  1361. T->ConstructJob(C, *JA, Result, InputInfos,
  1362. C.getArgsForToolChain(TC, BoundArch), LinkingOutput);
  1363. }
  1364. }
  1365. /// \brief Create output filename based on ArgValue, which could either be a
  1366. /// full filename, filename without extension, or a directory. If ArgValue
  1367. /// does not provide a filename, then use BaseName, and use the extension
  1368. /// suitable for FileType.
  1369. static const char *MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue,
  1370. StringRef BaseName, types::ID FileType) {
  1371. SmallString<128> Filename = ArgValue;
  1372. if (ArgValue.empty()) {
  1373. // If the argument is empty, output to BaseName in the current dir.
  1374. Filename = BaseName;
  1375. } else if (llvm::sys::path::is_separator(Filename.back())) {
  1376. // If the argument is a directory, output to BaseName in that dir.
  1377. llvm::sys::path::append(Filename, BaseName);
  1378. }
  1379. if (!llvm::sys::path::has_extension(ArgValue)) {
  1380. // If the argument didn't provide an extension, then set it.
  1381. const char *Extension = types::getTypeTempSuffix(FileType, true);
  1382. if (FileType == types::TY_Image &&
  1383. Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
  1384. // The output file is a dll.
  1385. Extension = "dll";
  1386. }
  1387. llvm::sys::path::replace_extension(Filename, Extension);
  1388. }
  1389. return Args.MakeArgString(Filename.c_str());
  1390. }
  1391. const char *Driver::GetNamedOutputPath(Compilation &C,
  1392. const JobAction &JA,
  1393. const char *BaseInput,
  1394. const char *BoundArch,
  1395. bool AtTopLevel,
  1396. bool MultipleArchs) const {
  1397. llvm::PrettyStackTraceString CrashInfo("Computing output path");
  1398. // Output to a user requested destination?
  1399. if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
  1400. !isa<VerifyJobAction>(JA)) {
  1401. if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
  1402. return C.addResultFile(FinalOutput->getValue(), &JA);
  1403. }
  1404. // For /P, preprocess to file named after BaseInput.
  1405. if (C.getArgs().hasArg(options::OPT__SLASH_P)) {
  1406. assert(AtTopLevel && isa<PreprocessJobAction>(JA));
  1407. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  1408. StringRef NameArg;
  1409. if (Arg *A = C.getArgs().getLastArg(options::OPT__SLASH_Fi))
  1410. NameArg = A->getValue();
  1411. return C.addResultFile(MakeCLOutputFilename(C.getArgs(), NameArg, BaseName,
  1412. types::TY_PP_C), &JA);
  1413. }
  1414. // Default to writing to stdout?
  1415. if (AtTopLevel && !CCGenDiagnostics &&
  1416. (isa<PreprocessJobAction>(JA) || JA.getType() == types::TY_ModuleFile))
  1417. return "-";
  1418. // Is this the assembly listing for /FA?
  1419. if (JA.getType() == types::TY_PP_Asm &&
  1420. (C.getArgs().hasArg(options::OPT__SLASH_FA) ||
  1421. C.getArgs().hasArg(options::OPT__SLASH_Fa))) {
  1422. // Use /Fa and the input filename to determine the asm file name.
  1423. StringRef BaseName = llvm::sys::path::filename(BaseInput);
  1424. StringRef FaValue = C.getArgs().getLastArgValue(options::OPT__SLASH_Fa);
  1425. return C.addResultFile(MakeCLOutputFilename(C.getArgs(), FaValue, BaseName,
  1426. JA.getType()), &JA);
  1427. }
  1428. // Output to a temporary file?
  1429. if ((!AtTopLevel && !C.getArgs().hasArg(options::OPT_save_temps) &&
  1430. !C.getArgs().hasArg(options::OPT__SLASH_Fo)) ||
  1431. CCGenDiagnostics) {
  1432. StringRef Name = llvm::sys::path::filename(BaseInput);
  1433. std::pair<StringRef, StringRef> Split = Name.split('.');
  1434. std::string TmpName =
  1435. GetTemporaryPath(Split.first,
  1436. types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  1437. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1438. }
  1439. SmallString<128> BasePath(BaseInput);
  1440. StringRef BaseName;
  1441. // Dsymutil actions should use the full path.
  1442. if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
  1443. BaseName = BasePath;
  1444. else
  1445. BaseName = llvm::sys::path::filename(BasePath);
  1446. // Determine what the derived output name should be.
  1447. const char *NamedOutput;
  1448. if (JA.getType() == types::TY_Object &&
  1449. C.getArgs().hasArg(options::OPT__SLASH_Fo)) {
  1450. // The /Fo flag decides the object filename.
  1451. StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_Fo)->getValue();
  1452. NamedOutput = MakeCLOutputFilename(C.getArgs(), Val, BaseName,
  1453. types::TY_Object);
  1454. } else if (JA.getType() == types::TY_Image &&
  1455. C.getArgs().hasArg(options::OPT__SLASH_Fe)) {
  1456. // The /Fe flag names the linked file.
  1457. StringRef Val = C.getArgs().getLastArg(options::OPT__SLASH_Fe)->getValue();
  1458. NamedOutput = MakeCLOutputFilename(C.getArgs(), Val, BaseName,
  1459. types::TY_Image);
  1460. } else if (JA.getType() == types::TY_Image) {
  1461. if (IsCLMode()) {
  1462. // clang-cl uses BaseName for the executable name.
  1463. NamedOutput = MakeCLOutputFilename(C.getArgs(), "", BaseName,
  1464. types::TY_Image);
  1465. } else if (MultipleArchs && BoundArch) {
  1466. SmallString<128> Output(DefaultImageName.c_str());
  1467. Output += "-";
  1468. Output.append(BoundArch);
  1469. NamedOutput = C.getArgs().MakeArgString(Output.c_str());
  1470. } else
  1471. NamedOutput = DefaultImageName.c_str();
  1472. } else {
  1473. const char *Suffix = types::getTypeTempSuffix(JA.getType(), IsCLMode());
  1474. assert(Suffix && "All types used for output should have a suffix.");
  1475. std::string::size_type End = std::string::npos;
  1476. if (!types::appendSuffixForType(JA.getType()))
  1477. End = BaseName.rfind('.');
  1478. SmallString<128> Suffixed(BaseName.substr(0, End));
  1479. if (MultipleArchs && BoundArch) {
  1480. Suffixed += "-";
  1481. Suffixed.append(BoundArch);
  1482. }
  1483. Suffixed += '.';
  1484. Suffixed += Suffix;
  1485. NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
  1486. }
  1487. // If we're saving temps and the temp file conflicts with the input file,
  1488. // then avoid overwriting input file.
  1489. if (!AtTopLevel && C.getArgs().hasArg(options::OPT_save_temps) &&
  1490. NamedOutput == BaseName) {
  1491. bool SameFile = false;
  1492. SmallString<256> Result;
  1493. llvm::sys::fs::current_path(Result);
  1494. llvm::sys::path::append(Result, BaseName);
  1495. llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
  1496. // Must share the same path to conflict.
  1497. if (SameFile) {
  1498. StringRef Name = llvm::sys::path::filename(BaseInput);
  1499. std::pair<StringRef, StringRef> Split = Name.split('.');
  1500. std::string TmpName =
  1501. GetTemporaryPath(Split.first,
  1502. types::getTypeTempSuffix(JA.getType(), IsCLMode()));
  1503. return C.addTempFile(C.getArgs().MakeArgString(TmpName.c_str()));
  1504. }
  1505. }
  1506. // As an annoying special case, PCH generation doesn't strip the pathname.
  1507. if (JA.getType() == types::TY_PCH) {
  1508. llvm::sys::path::remove_filename(BasePath);
  1509. if (BasePath.empty())
  1510. BasePath = NamedOutput;
  1511. else
  1512. llvm::sys::path::append(BasePath, NamedOutput);
  1513. return C.addResultFile(C.getArgs().MakeArgString(BasePath.c_str()), &JA);
  1514. } else {
  1515. return C.addResultFile(NamedOutput, &JA);
  1516. }
  1517. }
  1518. std::string Driver::GetFilePath(const char *Name, const ToolChain &TC) const {
  1519. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  1520. // attempting to use this prefix when looking for file paths.
  1521. for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
  1522. ie = PrefixDirs.end(); it != ie; ++it) {
  1523. std::string Dir(*it);
  1524. if (Dir.empty())
  1525. continue;
  1526. if (Dir[0] == '=')
  1527. Dir = SysRoot + Dir.substr(1);
  1528. SmallString<128> P(Dir);
  1529. llvm::sys::path::append(P, Name);
  1530. if (llvm::sys::fs::exists(Twine(P)))
  1531. return P.str();
  1532. }
  1533. SmallString<128> P(ResourceDir);
  1534. llvm::sys::path::append(P, Name);
  1535. if (llvm::sys::fs::exists(Twine(P)))
  1536. return P.str();
  1537. const ToolChain::path_list &List = TC.getFilePaths();
  1538. for (ToolChain::path_list::const_iterator
  1539. it = List.begin(), ie = List.end(); it != ie; ++it) {
  1540. std::string Dir(*it);
  1541. if (Dir.empty())
  1542. continue;
  1543. if (Dir[0] == '=')
  1544. Dir = SysRoot + Dir.substr(1);
  1545. SmallString<128> P(Dir);
  1546. llvm::sys::path::append(P, Name);
  1547. if (llvm::sys::fs::exists(Twine(P)))
  1548. return P.str();
  1549. }
  1550. return Name;
  1551. }
  1552. std::string Driver::GetProgramPath(const char *Name,
  1553. const ToolChain &TC) const {
  1554. // FIXME: Needs a better variable than DefaultTargetTriple
  1555. std::string TargetSpecificExecutable(DefaultTargetTriple + "-" + Name);
  1556. // Respect a limited subset of the '-Bprefix' functionality in GCC by
  1557. // attempting to use this prefix when looking for program paths.
  1558. for (Driver::prefix_list::const_iterator it = PrefixDirs.begin(),
  1559. ie = PrefixDirs.end(); it != ie; ++it) {
  1560. if (llvm::sys::fs::is_directory(*it)) {
  1561. SmallString<128> P(*it);
  1562. llvm::sys::path::append(P, TargetSpecificExecutable);
  1563. if (llvm::sys::fs::can_execute(Twine(P)))
  1564. return P.str();
  1565. llvm::sys::path::remove_filename(P);
  1566. llvm::sys::path::append(P, Name);
  1567. if (llvm::sys::fs::can_execute(Twine(P)))
  1568. return P.str();
  1569. } else {
  1570. SmallString<128> P(*it + Name);
  1571. if (llvm::sys::fs::can_execute(Twine(P)))
  1572. return P.str();
  1573. }
  1574. }
  1575. const ToolChain::path_list &List = TC.getProgramPaths();
  1576. for (ToolChain::path_list::const_iterator
  1577. it = List.begin(), ie = List.end(); it != ie; ++it) {
  1578. SmallString<128> P(*it);
  1579. llvm::sys::path::append(P, TargetSpecificExecutable);
  1580. if (llvm::sys::fs::can_execute(Twine(P)))
  1581. return P.str();
  1582. llvm::sys::path::remove_filename(P);
  1583. llvm::sys::path::append(P, Name);
  1584. if (llvm::sys::fs::can_execute(Twine(P)))
  1585. return P.str();
  1586. }
  1587. // If all else failed, search the path.
  1588. std::string P(llvm::sys::FindProgramByName(TargetSpecificExecutable));
  1589. if (!P.empty())
  1590. return P;
  1591. P = llvm::sys::FindProgramByName(Name);
  1592. if (!P.empty())
  1593. return P;
  1594. return Name;
  1595. }
  1596. std::string Driver::GetTemporaryPath(StringRef Prefix, const char *Suffix)
  1597. const {
  1598. SmallString<128> Path;
  1599. std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
  1600. if (EC) {
  1601. Diag(clang::diag::err_unable_to_make_temp) << EC.message();
  1602. return "";
  1603. }
  1604. return Path.str();
  1605. }
  1606. /// \brief Compute target triple from args.
  1607. ///
  1608. /// This routine provides the logic to compute a target triple from various
  1609. /// args passed to the driver and the default triple string.
  1610. static llvm::Triple computeTargetTriple(StringRef DefaultTargetTriple,
  1611. const ArgList &Args,
  1612. StringRef DarwinArchName) {
  1613. // FIXME: Already done in Compilation *Driver::BuildCompilation
  1614. if (const Arg *A = Args.getLastArg(options::OPT_target))
  1615. DefaultTargetTriple = A->getValue();
  1616. llvm::Triple Target(llvm::Triple::normalize(DefaultTargetTriple));
  1617. // Handle Apple-specific options available here.
  1618. if (Target.isOSBinFormatMachO()) {
  1619. // If an explict Darwin arch name is given, that trumps all.
  1620. if (!DarwinArchName.empty()) {
  1621. tools::darwin::setTripleTypeForMachOArchName(Target, DarwinArchName);
  1622. return Target;
  1623. }
  1624. // Handle the Darwin '-arch' flag.
  1625. if (Arg *A = Args.getLastArg(options::OPT_arch)) {
  1626. StringRef ArchName = A->getValue();
  1627. tools::darwin::setTripleTypeForMachOArchName(Target, ArchName);
  1628. }
  1629. }
  1630. // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
  1631. // '-mbig-endian'/'-EB'.
  1632. if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
  1633. options::OPT_mbig_endian)) {
  1634. if (A->getOption().matches(options::OPT_mlittle_endian)) {
  1635. if (Target.getArch() == llvm::Triple::mips)
  1636. Target.setArch(llvm::Triple::mipsel);
  1637. else if (Target.getArch() == llvm::Triple::mips64)
  1638. Target.setArch(llvm::Triple::mips64el);
  1639. else if (Target.getArch() == llvm::Triple::aarch64_be)
  1640. Target.setArch(llvm::Triple::aarch64);
  1641. } else {
  1642. if (Target.getArch() == llvm::Triple::mipsel)
  1643. Target.setArch(llvm::Triple::mips);
  1644. else if (Target.getArch() == llvm::Triple::mips64el)
  1645. Target.setArch(llvm::Triple::mips64);
  1646. else if (Target.getArch() == llvm::Triple::aarch64)
  1647. Target.setArch(llvm::Triple::aarch64_be);
  1648. }
  1649. }
  1650. // Skip further flag support on OSes which don't support '-m32' or '-m64'.
  1651. if (Target.getArchName() == "tce" || Target.getOS() == llvm::Triple::Minix)
  1652. return Target;
  1653. // Handle pseudo-target flags '-m64', '-mx32', '-m32' and '-m16'.
  1654. if (Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
  1655. options::OPT_m32, options::OPT_m16)) {
  1656. llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
  1657. if (A->getOption().matches(options::OPT_m64)) {
  1658. AT = Target.get64BitArchVariant().getArch();
  1659. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  1660. Target.setEnvironment(llvm::Triple::GNU);
  1661. } else if (A->getOption().matches(options::OPT_mx32) &&
  1662. Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
  1663. AT = llvm::Triple::x86_64;
  1664. Target.setEnvironment(llvm::Triple::GNUX32);
  1665. } else if (A->getOption().matches(options::OPT_m32)) {
  1666. AT = Target.get32BitArchVariant().getArch();
  1667. if (Target.getEnvironment() == llvm::Triple::GNUX32)
  1668. Target.setEnvironment(llvm::Triple::GNU);
  1669. } else if (A->getOption().matches(options::OPT_m16) &&
  1670. Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
  1671. AT = llvm::Triple::x86;
  1672. Target.setEnvironment(llvm::Triple::CODE16);
  1673. }
  1674. if (AT != llvm::Triple::UnknownArch)
  1675. Target.setArch(AT);
  1676. }
  1677. return Target;
  1678. }
  1679. const ToolChain &Driver::getToolChain(const ArgList &Args,
  1680. StringRef DarwinArchName) const {
  1681. llvm::Triple Target = computeTargetTriple(DefaultTargetTriple, Args,
  1682. DarwinArchName);
  1683. ToolChain *&TC = ToolChains[Target.str()];
  1684. if (!TC) {
  1685. switch (Target.getOS()) {
  1686. case llvm::Triple::Darwin:
  1687. case llvm::Triple::MacOSX:
  1688. case llvm::Triple::IOS:
  1689. TC = new toolchains::DarwinClang(*this, Target, Args);
  1690. break;
  1691. case llvm::Triple::DragonFly:
  1692. TC = new toolchains::DragonFly(*this, Target, Args);
  1693. break;
  1694. case llvm::Triple::OpenBSD:
  1695. TC = new toolchains::OpenBSD(*this, Target, Args);
  1696. break;
  1697. case llvm::Triple::Bitrig:
  1698. TC = new toolchains::Bitrig(*this, Target, Args);
  1699. break;
  1700. case llvm::Triple::NetBSD:
  1701. TC = new toolchains::NetBSD(*this, Target, Args);
  1702. break;
  1703. case llvm::Triple::FreeBSD:
  1704. TC = new toolchains::FreeBSD(*this, Target, Args);
  1705. break;
  1706. case llvm::Triple::Minix:
  1707. TC = new toolchains::Minix(*this, Target, Args);
  1708. break;
  1709. case llvm::Triple::Linux:
  1710. if (Target.getArch() == llvm::Triple::hexagon)
  1711. TC = new toolchains::Hexagon_TC(*this, Target, Args);
  1712. else
  1713. TC = new toolchains::Linux(*this, Target, Args);
  1714. break;
  1715. case llvm::Triple::Solaris:
  1716. TC = new toolchains::Solaris(*this, Target, Args);
  1717. break;
  1718. case llvm::Triple::Win32:
  1719. switch (Target.getEnvironment()) {
  1720. default:
  1721. if (Target.isOSBinFormatELF())
  1722. TC = new toolchains::Generic_ELF(*this, Target, Args);
  1723. else if (Target.isOSBinFormatMachO())
  1724. TC = new toolchains::MachO(*this, Target, Args);
  1725. else
  1726. TC = new toolchains::Generic_GCC(*this, Target, Args);
  1727. break;
  1728. case llvm::Triple::GNU:
  1729. // FIXME: We need a MinGW toolchain. Use the default Generic_GCC
  1730. // toolchain for now as the default case would below otherwise.
  1731. if (Target.isOSBinFormatELF())
  1732. TC = new toolchains::Generic_ELF(*this, Target, Args);
  1733. else
  1734. TC = new toolchains::Generic_GCC(*this, Target, Args);
  1735. break;
  1736. case llvm::Triple::MSVC:
  1737. case llvm::Triple::UnknownEnvironment:
  1738. TC = new toolchains::Windows(*this, Target, Args);
  1739. break;
  1740. }
  1741. break;
  1742. default:
  1743. // TCE is an OSless target
  1744. if (Target.getArchName() == "tce") {
  1745. TC = new toolchains::TCEToolChain(*this, Target, Args);
  1746. break;
  1747. }
  1748. // If Hexagon is configured as an OSless target
  1749. if (Target.getArch() == llvm::Triple::hexagon) {
  1750. TC = new toolchains::Hexagon_TC(*this, Target, Args);
  1751. break;
  1752. }
  1753. if (Target.getArch() == llvm::Triple::xcore) {
  1754. TC = new toolchains::XCore(*this, Target, Args);
  1755. break;
  1756. }
  1757. if (Target.isOSBinFormatELF()) {
  1758. TC = new toolchains::Generic_ELF(*this, Target, Args);
  1759. break;
  1760. }
  1761. if (Target.getObjectFormat() == llvm::Triple::MachO) {
  1762. TC = new toolchains::MachO(*this, Target, Args);
  1763. break;
  1764. }
  1765. TC = new toolchains::Generic_GCC(*this, Target, Args);
  1766. break;
  1767. }
  1768. }
  1769. return *TC;
  1770. }
  1771. bool Driver::ShouldUseClangCompiler(const JobAction &JA) const {
  1772. // Check if user requested no clang, or clang doesn't understand this type (we
  1773. // only handle single inputs for now).
  1774. if (JA.size() != 1 ||
  1775. !types::isAcceptedByClang((*JA.begin())->getType()))
  1776. return false;
  1777. // Otherwise make sure this is an action clang understands.
  1778. if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
  1779. !isa<CompileJobAction>(JA))
  1780. return false;
  1781. return true;
  1782. }
  1783. /// GetReleaseVersion - Parse (([0-9]+)(.([0-9]+)(.([0-9]+)?))?)? and return the
  1784. /// grouped values as integers. Numbers which are not provided are set to 0.
  1785. ///
  1786. /// \return True if the entire string was parsed (9.2), or all groups were
  1787. /// parsed (10.3.5extrastuff).
  1788. bool Driver::GetReleaseVersion(const char *Str, unsigned &Major,
  1789. unsigned &Minor, unsigned &Micro,
  1790. bool &HadExtra) {
  1791. HadExtra = false;
  1792. Major = Minor = Micro = 0;
  1793. if (*Str == '\0')
  1794. return true;
  1795. char *End;
  1796. Major = (unsigned) strtol(Str, &End, 10);
  1797. if (*Str != '\0' && *End == '\0')
  1798. return true;
  1799. if (*End != '.')
  1800. return false;
  1801. Str = End+1;
  1802. Minor = (unsigned) strtol(Str, &End, 10);
  1803. if (*Str != '\0' && *End == '\0')
  1804. return true;
  1805. if (*End != '.')
  1806. return false;
  1807. Str = End+1;
  1808. Micro = (unsigned) strtol(Str, &End, 10);
  1809. if (*Str != '\0' && *End == '\0')
  1810. return true;
  1811. if (Str == End)
  1812. return false;
  1813. HadExtra = true;
  1814. return true;
  1815. }
  1816. std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks() const {
  1817. unsigned IncludedFlagsBitmask = 0;
  1818. unsigned ExcludedFlagsBitmask = options::NoDriverOption;
  1819. if (Mode == CLMode) {
  1820. // Include CL and Core options.
  1821. IncludedFlagsBitmask |= options::CLOption;
  1822. IncludedFlagsBitmask |= options::CoreOption;
  1823. } else {
  1824. ExcludedFlagsBitmask |= options::CLOption;
  1825. }
  1826. return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
  1827. }
  1828. bool clang::driver::isOptimizationLevelFast(const llvm::opt::ArgList &Args) {
  1829. return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group, false);
  1830. }