15 #include "clang/Config/config.h"
24 #include "llvm/ADT/ArrayRef.h"
25 #include "llvm/ADT/STLExtras.h"
26 #include "llvm/ADT/SmallSet.h"
27 #include "llvm/ADT/StringExtras.h"
28 #include "llvm/ADT/StringSet.h"
29 #include "llvm/ADT/StringSwitch.h"
30 #include "llvm/Option/Arg.h"
31 #include "llvm/Option/ArgList.h"
32 #include "llvm/Option/OptSpecifier.h"
33 #include "llvm/Option/OptTable.h"
34 #include "llvm/Option/Option.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/FileSystem.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Process.h"
41 #include "llvm/Support/Program.h"
42 #include "llvm/Support/raw_ostream.h"
47 using namespace clang::driver;
48 using namespace clang;
49 using namespace llvm::opt;
55 Mode(GCCMode), SaveTemps(SaveTempsNone), BitcodeEmbed(EmbedNone),
56 LTOMode(
LTOK_None), ClangExecutable(ClangExecutable),
57 SysRoot(DEFAULT_SYSROOT), UseStdLib(
true),
58 DefaultTargetTriple(DefaultTargetTriple),
59 DriverTitle(
"clang LLVM compiler"), CCPrintOptionsFilename(nullptr),
60 CCPrintHeadersFilename(nullptr), CCLogDiagnosticsFilename(nullptr),
61 CCCPrintBindings(
false), CCPrintHeaders(
false), CCLogDiagnostics(
false),
62 CCGenDiagnostics(
false), CCCGenericGCCName(
""), CheckInputsExist(
true),
63 CCCUsePCH(
true), SuppressMissingInputWarning(
false) {
69 Name = llvm::sys::path::filename(ClangExecutable);
70 Dir = llvm::sys::path::parent_path(ClangExecutable);
74 StringRef ClangResourceDir(CLANG_RESOURCE_DIR);
76 if (ClangResourceDir !=
"") {
77 llvm::sys::path::append(P, ClangResourceDir);
79 StringRef ClangLibdirSuffix(CLANG_LIBDIR_SUFFIX);
80 llvm::sys::path::append(P,
"..", Twine(
"lib") + ClangLibdirSuffix,
"clang",
89 llvm::DeleteContainerSeconds(ToolChains);
93 const std::string OptName =
94 getOpts().getOption(options::OPT_driver_mode).getPrefixedName();
96 for (
const char *ArgPtr : Args) {
98 if (ArgPtr ==
nullptr)
100 const StringRef Arg = ArgPtr;
101 if (!Arg.startswith(OptName))
104 const StringRef
Value = Arg.drop_front(OptName.size());
105 const unsigned M = llvm::StringSwitch<unsigned>(
Value)
106 .Case(
"gcc", GCCMode)
107 .Case(
"g++", GXXMode)
108 .Case(
"cpp", CPPMode)
113 Mode =
static_cast<DriverMode
>(M);
115 Diag(diag::err_drv_unsupported_option_argument) << OptName <<
Value;
120 llvm::PrettyStackTraceString CrashInfo(
"Command line argument parsing");
122 unsigned IncludedFlagsBitmask;
123 unsigned ExcludedFlagsBitmask;
124 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
125 getIncludeExcludeOptionFlagMasks();
127 unsigned MissingArgIndex, MissingArgCount;
129 getOpts().ParseArgs(ArgStrings, MissingArgIndex, MissingArgCount,
130 IncludedFlagsBitmask, ExcludedFlagsBitmask);
134 Diag(clang::diag::err_drv_missing_argument)
135 << Args.getArgString(MissingArgIndex) << MissingArgCount;
138 for (
const Arg *A : Args) {
140 Diag(clang::diag::err_drv_unsupported_opt) << A->getAsString(Args);
145 if (A->getOption().matches(options::OPT_mcpu_EQ) && A->containsValue(
"")) {
146 Diag(clang::diag::warn_drv_empty_joined_argument) << A->getAsString(Args);
150 for (
const Arg *A : Args.filtered(options::OPT_UNKNOWN))
151 Diags.
Report(
IsCLMode() ? diag::warn_drv_unknown_argument_clang_cl :
152 diag::err_drv_unknown_argument)
153 << A->getAsString(Args);
161 phases::ID Driver::getFinalPhase(
const DerivedArgList &DAL,
162 Arg **FinalPhaseArg)
const {
163 Arg *PhaseArg =
nullptr;
167 if (
CCCIsCPP() || (PhaseArg = DAL.getLastArg(options::OPT_E)) ||
168 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_EP)) ||
169 (PhaseArg = DAL.getLastArg(options::OPT_M, options::OPT_MM)) ||
170 (PhaseArg = DAL.getLastArg(options::OPT__SLASH_P))) {
174 }
else if ((PhaseArg = DAL.getLastArg(options::OPT_fsyntax_only)) ||
175 (PhaseArg = DAL.getLastArg(options::OPT_module_file_info)) ||
176 (PhaseArg = DAL.getLastArg(options::OPT_verify_pch)) ||
177 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_objc)) ||
178 (PhaseArg = DAL.getLastArg(options::OPT_rewrite_legacy_objc)) ||
179 (PhaseArg = DAL.getLastArg(options::OPT__migrate)) ||
180 (PhaseArg = DAL.getLastArg(options::OPT__analyze,
181 options::OPT__analyze_auto)) ||
182 (PhaseArg = DAL.getLastArg(options::OPT_emit_ast))) {
186 }
else if ((PhaseArg = DAL.getLastArg(options::OPT_S))) {
190 }
else if ((PhaseArg = DAL.getLastArg(options::OPT_c))) {
198 *FinalPhaseArg = PhaseArg;
205 Arg *A =
new Arg(Opts->getOption(options::OPT_INPUT),
Value,
206 Args.getBaseArgs().MakeIndex(Value), Value.data());
207 Args.AddSynthesizedArg(A);
212 DerivedArgList *Driver::TranslateInputArgs(
const InputArgList &Args)
const {
213 DerivedArgList *DAL =
new DerivedArgList(Args);
215 bool HasNostdlib = Args.hasArg(options::OPT_nostdlib);
216 bool HasNodefaultlib = Args.hasArg(options::OPT_nodefaultlibs);
217 for (Arg *A : Args) {
224 if ((A->getOption().matches(options::OPT_Wl_COMMA) ||
225 A->getOption().matches(options::OPT_Xlinker)) &&
226 A->containsValue(
"--no-demangle")) {
228 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_Xlinker__no_demangle));
231 for (StringRef Val : A->getValues())
232 if (Val !=
"--no-demangle")
233 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_Xlinker), Val);
241 if (A->getOption().matches(options::OPT_Wp_COMMA) &&
242 (A->getValue(0) == StringRef(
"-MD") ||
243 A->getValue(0) == StringRef(
"-MMD"))) {
245 if (A->getValue(0) == StringRef(
"-MD"))
246 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MD));
248 DAL->AddFlagArg(A, Opts->getOption(options::OPT_MMD));
249 if (A->getNumValues() == 2)
250 DAL->AddSeparateArg(A, Opts->getOption(options::OPT_MF),
256 if (A->getOption().matches(options::OPT_l)) {
257 StringRef
Value = A->getValue();
260 if (!HasNostdlib && !HasNodefaultlib && Value ==
"stdc++") {
261 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_stdcxx));
266 if (Value ==
"cc_kext") {
267 DAL->AddFlagArg(A, Opts->getOption(options::OPT_Z_reserved_lib_cckext));
273 if (A->getOption().matches(options::OPT__DASH_DASH)) {
275 for (StringRef Val : A->getValues())
284 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu,
false))
285 DAL->AddFlagArg(0, Opts->getOption(options::OPT_static));
289 #if defined(HOST_LINK_VERSION)
290 if (!Args.hasArg(options::OPT_mlinker_version_EQ) &&
291 strlen(HOST_LINK_VERSION) > 0) {
292 DAL->AddJoinedArg(0, Opts->getOption(options::OPT_mlinker_version_EQ),
294 DAL->getLastArg(options::OPT_mlinker_version_EQ)->claim();
306 StringRef DefaultTargetTriple,
308 StringRef DarwinArchName =
"") {
310 if (
const Arg *A = Args.getLastArg(options::OPT_target))
311 DefaultTargetTriple = A->getValue();
316 if (Target.isOSBinFormatMachO()) {
318 if (!DarwinArchName.empty()) {
324 if (Arg *A = Args.getLastArg(options::OPT_arch)) {
325 StringRef ArchName = A->getValue();
332 if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
333 options::OPT_mbig_endian)) {
334 if (A->getOption().matches(options::OPT_mlittle_endian)) {
335 llvm::Triple LE = Target.getLittleEndianArchVariant();
336 if (LE.getArch() != llvm::Triple::UnknownArch)
337 Target = std::move(LE);
339 llvm::Triple BE = Target.getBigEndianArchVariant();
340 if (BE.getArch() != llvm::Triple::UnknownArch)
341 Target = std::move(BE);
346 if (Target.getArch() == llvm::Triple::tce ||
347 Target.getOS() == llvm::Triple::Minix)
351 Arg *A = Args.getLastArg(options::OPT_m64, options::OPT_mx32,
352 options::OPT_m32, options::OPT_m16);
354 llvm::Triple::ArchType AT = llvm::Triple::UnknownArch;
356 if (A->getOption().matches(options::OPT_m64)) {
357 AT = Target.get64BitArchVariant().getArch();
358 if (Target.getEnvironment() == llvm::Triple::GNUX32)
359 Target.setEnvironment(llvm::Triple::GNU);
360 }
else if (A->getOption().matches(options::OPT_mx32) &&
361 Target.get64BitArchVariant().getArch() == llvm::Triple::x86_64) {
362 AT = llvm::Triple::x86_64;
363 Target.setEnvironment(llvm::Triple::GNUX32);
364 }
else if (A->getOption().matches(options::OPT_m32)) {
365 AT = Target.get32BitArchVariant().getArch();
366 if (Target.getEnvironment() == llvm::Triple::GNUX32)
367 Target.setEnvironment(llvm::Triple::GNU);
368 }
else if (A->getOption().matches(options::OPT_m16) &&
369 Target.get32BitArchVariant().getArch() == llvm::Triple::x86) {
370 AT = llvm::Triple::x86;
371 Target.setEnvironment(llvm::Triple::CODE16);
374 if (AT != llvm::Triple::UnknownArch && AT != Target.getArch())
379 if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu,
false)) {
380 if (Target.get32BitArchVariant().getArch() != llvm::Triple::x86)
381 D.
Diag(diag::err_drv_unsupported_opt_for_target) <<
"-miamcu"
384 if (A && !A->getOption().matches(options::OPT_m32))
385 D.
Diag(diag::err_drv_argument_not_allowed_with)
386 <<
"-miamcu" << A->getBaseArg().getAsString(Args);
388 Target.setArch(llvm::Triple::x86);
389 Target.setArchName(
"i586");
390 Target.setEnvironment(llvm::Triple::UnknownEnvironment);
391 Target.setEnvironmentName(
"");
392 Target.setOS(llvm::Triple::ELFIAMCU);
393 Target.setVendor(llvm::Triple::UnknownVendor);
394 Target.setVendorName(
"intel");
402 void Driver::setLTOMode(
const llvm::opt::ArgList &Args) {
404 if (!Args.hasFlag(options::OPT_flto, options::OPT_flto_EQ,
405 options::OPT_fno_lto,
false))
408 StringRef LTOName(
"full");
410 const Arg *A = Args.getLastArg(options::OPT_flto_EQ);
412 LTOName = A->getValue();
414 LTOMode = llvm::StringSwitch<LTOKind>(LTOName)
421 Diag(diag::err_drv_unsupported_option_argument) << A->getOption().getName()
433 if (llvm::any_of(Inputs, [](std::pair<types::ID, const llvm::opt::Arg *> &
I) {
441 ?
"nvptx64-nvidia-cuda"
442 :
"nvptx-nvidia-cuda"));
454 llvm::PrettyStackTraceString CrashInfo(
"Compilation construction");
459 if (
char *env = ::getenv(
"COMPILER_PATH")) {
460 StringRef CompilerPath = env;
461 while (!CompilerPath.empty()) {
462 std::pair<StringRef, StringRef> Split =
463 CompilerPath.split(llvm::sys::EnvPathSeparator);
465 CompilerPath = Split.second;
484 Args.ClaimAllArgs(options::OPT_no_canonical_prefixes);
487 Args.ClaimAllArgs(options::OPT_pipe);
495 CCCPrintPhases = Args.hasArg(options::OPT_ccc_print_phases);
497 if (
const Arg *A = Args.getLastArg(options::OPT_ccc_gcc_name))
498 CCCGenericGCCName = A->getValue();
500 Args.hasFlag(options::OPT_ccc_pch_is_pch, options::OPT_ccc_pch_is_pth);
506 T.setOS(llvm::Triple::Win32);
507 T.setVendor(llvm::Triple::PC);
508 T.setEnvironment(llvm::Triple::MSVC);
511 if (
const Arg *A = Args.getLastArg(options::OPT_target))
513 if (
const Arg *A = Args.getLastArg(options::OPT_ccc_install_dir))
515 for (
const Arg *A : Args.filtered(options::OPT_B)) {
519 if (
const Arg *A = Args.getLastArg(options::OPT__sysroot_EQ))
521 if (
const Arg *A = Args.getLastArg(options::OPT__dyld_prefix_EQ))
523 if (Args.hasArg(options::OPT_nostdlib))
526 if (
const Arg *A = Args.getLastArg(options::OPT_resource_dir))
529 if (
const Arg *A = Args.getLastArg(options::OPT_save_temps_EQ)) {
530 SaveTemps = llvm::StringSwitch<SaveTempsMode>(A->getValue())
531 .Case(
"cwd", SaveTempsCwd)
532 .Case(
"obj", SaveTempsObj)
533 .Default(SaveTempsCwd);
541 if (Arg *A = Args.getLastArg(options::OPT_fembed_bitcode_EQ)) {
542 StringRef
Name = A->getValue();
543 unsigned Model = llvm::StringSwitch<unsigned>(
Name)
544 .Case(
"off", EmbedNone)
545 .Case(
"all", EmbedBitcode)
546 .Case(
"bitcode", EmbedBitcode)
547 .Case(
"marker", EmbedMarker)
550 Diags.
Report(diag::err_drv_invalid_value) << A->getAsString(Args)
553 BitcodeEmbed =
static_cast<BitcodeEmbedMode
>(Model);
557 Args.ClaimAllArgs(options::OPT_fembed_bitcode_EQ);
560 std::unique_ptr<llvm::opt::InputArgList> UArgs =
561 llvm::make_unique<InputArgList>(std::move(Args));
564 DerivedArgList *TranslatedArgs = TranslateInputArgs(*UArgs);
590 if (CCCPrintPhases) {
600 static void printArgList(raw_ostream &OS,
const llvm::opt::ArgList &Args) {
601 llvm::opt::ArgStringList ASL;
602 for (
const auto *A : Args)
603 A->render(Args, ASL);
605 for (
auto I = ASL.begin(),
E = ASL.end();
I !=
E; ++
I) {
606 if (
I != ASL.begin())
617 const Command &FailingCommand) {
618 if (C.
getArgs().hasArg(options::OPT_fno_crash_diagnostics))
629 Diag(clang::diag::note_drv_command_failed_diag_msg)
630 <<
"PLEASE submit a bug report to " BUG_REPORT_URL
" and include the "
631 "crash backtrace, preprocessed source, and associated run script.";
652 bool IgnoreInput =
false;
658 }
else if (!strcmp(it->second->getValue(),
"-")) {
659 Diag(clang::diag::note_drv_command_failed_diag_msg)
660 <<
"Error generating preprocessed source(s) - "
661 "ignoring input from stdin.";
666 it = Inputs.erase(it);
673 if (Inputs.empty()) {
674 Diag(clang::diag::note_drv_command_failed_diag_msg)
675 <<
"Error generating preprocessed source(s) - "
676 "no preprocessable inputs.";
682 llvm::StringSet<> ArchNames;
683 for (
const Arg *A : C.
getArgs()) {
684 if (A->getOption().matches(options::OPT_arch)) {
685 StringRef ArchName = A->getValue();
686 ArchNames.insert(ArchName);
689 if (ArchNames.size() > 1) {
690 Diag(clang::diag::note_drv_command_failed_diag_msg)
691 <<
"Error generating preprocessed source(s) - cannot generate "
692 "preprocessed source with multiple -arch options.";
708 Diag(clang::diag::note_drv_command_failed_diag_msg)
709 <<
"Error generating preprocessed source(s).";
718 if (!FailingCommands.empty()) {
722 Diag(clang::diag::note_drv_command_failed_diag_msg)
723 <<
"Error generating preprocessed source(s).";
728 if (TempFiles.empty()) {
729 Diag(clang::diag::note_drv_command_failed_diag_msg)
730 <<
"Error generating preprocessed source(s).";
734 Diag(clang::diag::note_drv_command_failed_diag_msg)
735 <<
"\n********************\n\n"
736 "PLEASE ATTACH THE FOLLOWING FILES TO THE BUG REPORT:\n"
737 "Preprocessed source(s) and associated run script(s) are located at:";
740 for (
const char *TempFile : TempFiles) {
741 Diag(clang::diag::note_drv_command_failed_diag_msg) << TempFile;
742 if (StringRef(TempFile).endswith(
".cache")) {
745 VFS = llvm::sys::path::filename(TempFile);
746 llvm::sys::path::append(VFS,
"vfs",
"vfs.yaml");
753 std::string Script = CrashInfo.
Filename.rsplit(
'.').first.str() +
".sh";
755 llvm::raw_fd_ostream ScriptOS(Script, EC, llvm::sys::fs::F_Excl);
757 Diag(clang::diag::note_drv_command_failed_diag_msg)
758 <<
"Error generating run script: " + Script +
" " + EC.message();
761 <<
"# Driver args: ";
763 ScriptOS <<
"# Original command: ";
764 Cmd.
Print(ScriptOS,
"\n",
true);
765 Cmd.
Print(ScriptOS,
"\n",
true, &CrashInfo);
766 Diag(clang::diag::note_drv_command_failed_diag_msg) << Script;
769 for (
const auto &A : C.
getArgs().filtered(options::OPT_frewrite_map_file,
770 options::OPT_frewrite_map_file_EQ))
771 Diag(clang::diag::note_drv_command_failed_diag_msg) << A->getValue();
773 Diag(clang::diag::note_drv_command_failed_diag_msg)
774 <<
"\n\n********************";
794 if (C.
getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
805 setUpResponseFiles(C, Job);
813 if (FailingCommands.empty())
818 for (
const auto &CmdPair : FailingCommands) {
819 int Res = CmdPair.first;
820 const Command *FailingCommand = CmdPair.second;
844 Diag(clang::diag::err_drv_command_signalled)
855 unsigned IncludedFlagsBitmask;
856 unsigned ExcludedFlagsBitmask;
857 std::tie(IncludedFlagsBitmask, ExcludedFlagsBitmask) =
858 getIncludeExcludeOptionFlagMasks();
862 ExcludedFlagsBitmask |= HelpHidden;
865 IncludedFlagsBitmask, ExcludedFlagsBitmask);
876 if (Arg *A = C.
getArgs().getLastArg(options::OPT_mthread_model)) {
879 OS <<
"Thread model: " << A->getValue();
901 if (C.
getArgs().hasArg(options::OPT_dumpmachine)) {
906 if (C.
getArgs().hasArg(options::OPT_dumpversion)) {
913 llvm::outs() <<
"4.2.1\n";
917 if (C.
getArgs().hasArg(options::OPT__print_diagnostic_categories)) {
922 if (C.
getArgs().hasArg(options::OPT_help) ||
923 C.
getArgs().hasArg(options::OPT__help_hidden)) {
928 if (C.
getArgs().hasArg(options::OPT__version)) {
934 if (C.
getArgs().hasArg(options::OPT_v) ||
935 C.
getArgs().hasArg(options::OPT__HASH_HASH_HASH)) {
937 SuppressMissingInputWarning =
true;
942 if (C.
getArgs().hasArg(options::OPT_v))
945 if (C.
getArgs().hasArg(options::OPT_print_search_dirs)) {
946 llvm::outs() <<
"programs: =";
947 bool separator =
false;
951 llvm::outs() << Path;
954 llvm::outs() <<
"\n";
964 llvm::outs() << sysroot << Path.substr(1);
966 llvm::outs() << Path;
968 llvm::outs() <<
"\n";
974 if (Arg *A = C.
getArgs().getLastArg(options::OPT_print_file_name_EQ)) {
975 llvm::outs() <<
GetFilePath(A->getValue(), TC) <<
"\n";
979 if (Arg *A = C.
getArgs().getLastArg(options::OPT_print_prog_name_EQ)) {
984 if (C.
getArgs().hasArg(options::OPT_print_libgcc_file_name)) {
985 llvm::outs() <<
GetFilePath(
"libgcc.a", TC) <<
"\n";
989 if (C.
getArgs().hasArg(options::OPT_print_multi_lib)) {
995 if (C.
getArgs().hasArg(options::OPT_print_multi_directory)) {
998 llvm::outs() <<
".\n";
1001 assert(Suffix.front() ==
'/');
1002 llvm::outs() << Suffix.substr(1) <<
"\n";
1014 std::map<Action *, unsigned> &Ids) {
1019 llvm::raw_string_ostream os(str);
1023 os <<
"\"" << IA->getInputArg().getValue() <<
"\"";
1025 os <<
'"' << BIA->getArchName() <<
'"' <<
", {"
1027 }
else if (
OffloadAction *OA = dyn_cast<OffloadAction>(A)) {
1028 bool IsFirst =
true;
1029 OA->doOnEachDependence(
1046 os <<
":" << BoundArch;
1056 const char *Prefix =
"{";
1057 for (
Action *PreRequisite : *AL) {
1068 std::string offload_str;
1069 llvm::raw_string_ostream offload_os(offload_str);
1070 if (!isa<OffloadAction>(A)) {
1073 offload_os <<
", (" <<
S;
1080 unsigned Id = Ids.size();
1082 llvm::errs() << Id <<
": " << os.str() <<
", "
1091 std::map<Action *, unsigned> Ids;
1099 if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A) ||
1100 isa<AssembleJobAction>(A))
1112 DerivedArgList &Args = C.
getArgs();
1114 llvm::PrettyStackTraceString CrashInfo(
"Building universal build actions");
1117 llvm::StringSet<> ArchNames;
1119 for (Arg *A : Args) {
1120 if (A->getOption().matches(options::OPT_arch)) {
1123 llvm::Triple::ArchType Arch =
1125 if (Arch == llvm::Triple::UnknownArch) {
1126 Diag(clang::diag::err_drv_invalid_arch_name) << A->getAsString(Args);
1131 if (ArchNames.insert(A->getValue()).second)
1132 Archs.push_back(A->getValue());
1146 for (
Action* Act : SingleActions) {
1154 Diag(clang::diag::err_drv_invalid_output_with_multiple_archs)
1158 for (
unsigned i = 0, e = Archs.size(); i != e; ++i)
1163 if (Inputs.size() == 1 || Act->getType() == types::TY_Nothing)
1164 Actions.append(Inputs.begin(), Inputs.end());
1169 Arg *A = Args.getLastArg(options::OPT_g_Group);
1170 if (A && !A->getOption().matches(options::OPT_g0) &&
1171 !A->getOption().matches(options::OPT_gstabs) &&
1178 if (Act->getType() == types::TY_Image) {
1180 Inputs.push_back(Actions.back());
1187 if (Args.hasArg(options::OPT_verify_debug_info)) {
1188 Action* LastAction = Actions.back();
1191 LastAction, types::TY_Nothing));
1209 if (Arg *WorkDir = Args.getLastArg(options::OPT_working_directory)) {
1210 if (!llvm::sys::path::is_absolute(Path)) {
1212 llvm::sys::path::append(Directory, Value);
1213 Path.assign(Directory);
1217 if (llvm::sys::fs::exists(Twine(Path)))
1221 if (!llvm::sys::path::is_absolute(Twine(Path)) &&
1222 llvm::sys::Process::FindInEnvPath(
"LIB", Value))
1225 if (Args.hasArg(options::OPT__SLASH_link) && Ty == types::TY_Object) {
1233 D.
Diag(clang::diag::err_drv_no_such_file) << Path;
1243 types::ID InputType = types::TY_Nothing;
1244 Arg *InputTypeArg =
nullptr;
1247 if (Arg *TCTP = Args.getLastArgNoClaim(options::OPT__SLASH_TC,
1248 options::OPT__SLASH_TP)) {
1249 InputTypeArg = TCTP;
1250 InputType = TCTP->getOption().matches(options::OPT__SLASH_TC)
1255 Args.filtered_begin(options::OPT__SLASH_TC, options::OPT__SLASH_TP);
1256 const arg_iterator ie = Args.filtered_end();
1258 bool ShowNote =
false;
1260 Diag(clang::diag::warn_drv_overriding_flag_option)
1261 << Previous->getSpelling() << (*it)->getSpelling();
1266 Diag(clang::diag::note_drv_t_option_is_global);
1269 assert(!Args.hasArg(options::OPT_x) &&
"-x and /TC or /TP is not allowed");
1272 for (Arg *A : Args) {
1273 if (A->getOption().getKind() == Option::InputClass) {
1274 const char *Value = A->getValue();
1278 if (InputType == types::TY_Nothing) {
1281 InputTypeArg->claim();
1284 if (memcmp(Value,
"-", 2) == 0) {
1290 if (!Args.hasArgNoClaim(options::OPT_E) && !
CCCIsCPP())
1291 Diag(
IsCLMode() ? clang::diag::err_drv_unknown_stdin_type_clang_cl
1292 : clang::diag::err_drv_unknown_stdin_type);
1299 if (
const char *Ext = strrchr(Value,
'.'))
1306 Ty = types::TY_Object;
1316 Diag(clang::diag::warn_drv_treating_input_as_cxx)
1326 if (Ty != types::TY_Object) {
1327 if (Args.hasArg(options::OPT_ObjC))
1328 Ty = types::TY_ObjC;
1329 else if (Args.hasArg(options::OPT_ObjCXX))
1330 Ty = types::TY_ObjCXX;
1333 assert(InputTypeArg &&
"InputType set w/o InputTypeArg");
1334 if (!InputTypeArg->getOption().matches(options::OPT_x)) {
1337 const char *Ext = strrchr(Value,
'.');
1339 Ty = types::TY_Object;
1343 InputTypeArg->claim();
1348 Inputs.push_back(std::make_pair(Ty, A));
1350 }
else if (A->getOption().matches(options::OPT__SLASH_Tc)) {
1351 StringRef Value = A->getValue();
1353 Arg *InputArg =
MakeInputArg(Args, Opts, A->getValue());
1354 Inputs.push_back(std::make_pair(types::TY_C, InputArg));
1357 }
else if (A->getOption().matches(options::OPT__SLASH_Tp)) {
1358 StringRef Value = A->getValue();
1360 Arg *InputArg =
MakeInputArg(Args, Opts, A->getValue());
1361 Inputs.push_back(std::make_pair(types::TY_CXX, InputArg));
1367 Inputs.push_back(std::make_pair(types::TY_Object, A));
1369 }
else if (A->getOption().matches(options::OPT_x)) {
1378 Diag(clang::diag::err_drv_unknown_language) << A->getValue();
1379 InputType = types::TY_Object;
1383 if (
CCCIsCPP() && Inputs.empty()) {
1387 Inputs.push_back(std::make_pair(types::TY_C, A));
1399 const Arg *InputArg,
Action *HostAction,
1401 Arg *PartialCompilationArg = Args.getLastArg(
1402 options::OPT_cuda_host_only, options::OPT_cuda_device_only,
1403 options::OPT_cuda_compile_host_device);
1404 bool CompileHostOnly =
1405 PartialCompilationArg &&
1406 PartialCompilationArg->getOption().matches(options::OPT_cuda_host_only);
1407 bool CompileDeviceOnly =
1408 PartialCompilationArg &&
1409 PartialCompilationArg->getOption().matches(options::OPT_cuda_device_only);
1411 if (CompileHostOnly) {
1420 llvm::SmallSet<CudaArch, 4> GpuArchs;
1421 for (Arg *A : Args) {
1422 if (!A->getOption().matches(options::OPT_cuda_gpu_arch_EQ))
1426 const auto &ArchStr = A->getValue();
1429 C.
getDriver().
Diag(clang::diag::err_drv_cuda_bad_gpu_arch) << ArchStr;
1430 else if (GpuArchs.insert(Arch).second)
1431 GpuArchList.push_back(Arch);
1436 if (GpuArchList.empty())
1441 for (
unsigned I = 0,
E = GpuArchList.size();
I !=
E; ++
I)
1442 CudaDeviceInputs.push_back(std::make_pair(types::TY_CUDA_DEVICE, InputArg));
1447 assert(GpuArchList.size() == CudaDeviceActions.size() &&
1448 "Failed to create actions for all devices");
1451 bool PartialCompilation =
1452 llvm::any_of(CudaDeviceActions, [](
const Action *a) {
1460 if (PartialCompilation || CompileDeviceOnly) {
1466 if (Args.hasArg(options::OPT_o) &&
1467 (!CompileDeviceOnly || GpuArchList.size() > 1)) {
1469 clang::diag::err_drv_output_argument_with_multiple_files);
1473 for (
unsigned I = 0,
E = GpuArchList.size();
I !=
E; ++
I) {
1481 if (CompileDeviceOnly)
1491 for (
unsigned I = 0,
E = GpuArchList.size();
I !=
E; ++
I) {
1492 Action* AssembleAction = CudaDeviceActions[
I];
1493 assert(AssembleAction->
getType() == types::TY_Object);
1494 assert(AssembleAction->
getInputs().size() == 1);
1497 assert(BackendAction->getType() == types::TY_PP_Asm);
1499 for (
auto &A : {AssembleAction, BackendAction}) {
1520 llvm::PrettyStackTraceString CrashInfo(
"Building compilation actions");
1522 if (!SuppressMissingInputWarning && Inputs.empty()) {
1523 Diag(clang::diag::err_drv_no_input_files);
1528 phases::ID FinalPhase = getFinalPhase(Args, &FinalPhaseArg);
1530 if (FinalPhase ==
phases::Link && Args.hasArg(options::OPT_emit_llvm)) {
1531 Diag(clang::diag::err_drv_emit_llvm_link);
1536 if (Arg *A = Args.getLastArg(options::OPT_Z_Joined))
1537 Diag(clang::diag::err_drv_use_of_Z_option) << A->getAsString(Args);
1540 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fo)) {
1541 StringRef V = A->getValue();
1542 if (Inputs.size() > 1 && !V.empty() &&
1543 !llvm::sys::path::is_separator(V.back())) {
1545 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1546 << A->getSpelling() << V;
1547 Args.eraseArg(options::OPT__SLASH_Fo);
1552 if (Arg *A = Args.getLastArg(options::OPT__SLASH_Fa)) {
1553 StringRef V = A->getValue();
1554 if (Inputs.size() > 1 && !V.empty() &&
1555 !llvm::sys::path::is_separator(V.back())) {
1557 Diag(clang::diag::err_drv_out_file_argument_with_multiple_sources)
1558 << A->getSpelling() << V;
1559 Args.eraseArg(options::OPT__SLASH_Fa);
1564 if (Arg *A = Args.getLastArg(options::OPT__SLASH_o)) {
1565 if (A->getValue()[0] ==
'\0') {
1567 Diag(clang::diag::err_drv_missing_argument) << A->getSpelling() << 1;
1568 Args.eraseArg(options::OPT__SLASH_o);
1576 Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1577 Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1578 if (YcArg && YcArg->getValue()[0] ==
'\0') {
1579 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YcArg->getSpelling();
1580 Args.eraseArg(options::OPT__SLASH_Yc);
1583 if (YuArg && YuArg->getValue()[0] ==
'\0') {
1584 Diag(clang::diag::warn_drv_ycyu_no_arg_clang_cl) << YuArg->getSpelling();
1585 Args.eraseArg(options::OPT__SLASH_Yu);
1588 if (YcArg && YuArg && strcmp(YcArg->getValue(), YuArg->getValue()) != 0) {
1589 Diag(clang::diag::warn_drv_ycyu_different_arg_clang_cl);
1590 Args.eraseArg(options::OPT__SLASH_Yc);
1591 Args.eraseArg(options::OPT__SLASH_Yu);
1592 YcArg = YuArg =
nullptr;
1594 if (YcArg || YuArg) {
1595 StringRef Val = YcArg ? YcArg->getValue() : YuArg->getValue();
1596 bool FoundMatchingInclude =
false;
1597 for (
const Arg *Inc : Args.filtered(options::OPT_include)) {
1599 if (Inc->getValue() == Val)
1600 FoundMatchingInclude =
true;
1602 if (!FoundMatchingInclude) {
1603 Diag(clang::diag::warn_drv_ycyu_no_fi_arg_clang_cl)
1604 << (YcArg ? YcArg : YuArg)->getSpelling();
1605 Args.eraseArg(options::OPT__SLASH_Yc);
1606 Args.eraseArg(options::OPT__SLASH_Yu);
1607 YcArg = YuArg =
nullptr;
1610 if (YcArg && Inputs.size() > 1) {
1611 Diag(clang::diag::warn_drv_yc_multiple_inputs_clang_cl);
1612 Args.eraseArg(options::OPT__SLASH_Yc);
1615 if (Args.hasArg(options::OPT__SLASH_Y_)) {
1618 Args.eraseArg(options::OPT__SLASH_Fp);
1619 Args.eraseArg(options::OPT__SLASH_Yc);
1620 Args.eraseArg(options::OPT__SLASH_Yu);
1621 YcArg = YuArg =
nullptr;
1625 unsigned CompilationActiveOffloadHostKinds = 0u;
1631 for (
auto &
I : Inputs) {
1633 const Arg *InputArg =
I.second;
1641 if (InitialPhase > FinalPhase) {
1646 if (Args.hasArg(options::OPT_Qunused_arguments))
1652 Diag(clang::diag::warn_drv_input_file_unused_by_cpp)
1653 << InputArg->getAsString(Args) <<
getPhaseName(InitialPhase);
1659 Diag(clang::diag::warn_drv_preprocessed_input_file_unused)
1660 << InputArg->getAsString(Args) << !!FinalPhaseArg
1661 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() :
"");
1663 Diag(clang::diag::warn_drv_input_file_unused)
1664 << InputArg->getAsString(Args) <<
getPhaseName(InitialPhase)
1666 << (FinalPhaseArg ? FinalPhaseArg->getOption().getName() :
"");
1675 Arg *PchInputArg =
MakeInputArg(Args, Opts, YcArg->getValue());
1682 Actions.push_back(ClangClPch);
1696 unsigned InputActiveOffloadHostKinds = 0u;
1705 if (Phase > FinalPhase)
1710 assert((i + 1) == e &&
"linking must be final compilation step.");
1711 LinkerInputs.push_back(Current);
1725 if (InputType == types::TY_CUDA && Phase == CudaInjectionPhase) {
1736 if (Current->
getType() == types::TY_Nothing)
1744 if (InputActiveOffloadHostKinds)
1747 Actions.push_back(Current);
1753 if (!LinkerInputs.empty()) {
1756 Actions.back()->propagateHostOffloadInfo(CompilationActiveOffloadHostKinds,
1763 Args.ClaimAllArgs(options::OPT_CompileOnly_Group);
1764 Args.ClaimAllArgs(options::OPT_cl_compile_Group);
1768 Args.ClaimAllArgs(options::OPT_cl_ignored_Group);
1772 Args.ClaimAllArgs(options::OPT_cuda_host_only);
1773 Args.ClaimAllArgs(options::OPT_cuda_compile_host_device);
1778 llvm::PrettyStackTraceString CrashInfo(
"Constructing phase actions");
1782 llvm_unreachable(
"link action invalid here.");
1786 if (Args.hasArg(options::OPT_M, options::OPT_MM)) {
1787 OutputTy = types::TY_Dependencies;
1790 if (!Args.hasFlag(options::OPT_frewrite_includes,
1791 options::OPT_fno_rewrite_includes,
false) &&
1795 "Cannot preprocess this input type!");
1801 if (Args.hasArg(options::OPT_fsyntax_only)) {
1803 OutputTy = types::TY_Nothing;
1808 if (Args.hasArg(options::OPT_fsyntax_only))
1810 if (Args.hasArg(options::OPT_rewrite_objc))
1812 if (Args.hasArg(options::OPT_rewrite_legacy_objc))
1814 types::TY_RewrittenLegacyObjC);
1815 if (Args.hasArg(options::OPT__analyze, options::OPT__analyze_auto))
1817 if (Args.hasArg(options::OPT__migrate))
1819 if (Args.hasArg(options::OPT_emit_ast))
1821 if (Args.hasArg(options::OPT_module_file_info))
1823 if (Args.hasArg(options::OPT_verify_pch))
1830 Args.hasArg(options::OPT_S) ? types::TY_LTO_IR : types::TY_LTO_BC;
1833 if (Args.hasArg(options::OPT_emit_llvm)) {
1835 Args.hasArg(options::OPT_S) ? types::TY_LLVM_IR : types::TY_LLVM_BC;
1844 llvm_unreachable(
"invalid phase in ConstructPhaseAction");
1848 llvm::PrettyStackTraceString CrashInfo(
"Building compilation jobs");
1850 Arg *FinalOutput = C.
getArgs().getLastArg(options::OPT_o);
1855 unsigned NumOutputs = 0;
1857 if (A->getType() != types::TY_Nothing)
1860 if (NumOutputs > 1) {
1861 Diag(clang::diag::err_drv_output_argument_with_multiple_files);
1862 FinalOutput =
nullptr;
1867 llvm::StringSet<> ArchNames;
1869 for (
const Arg *A : C.
getArgs())
1870 if (A->getOption().matches(options::OPT_arch))
1871 ArchNames.insert(A->getValue());
1874 std::map<std::pair<const Action *, std::string>,
InputInfo> CachedResults;
1882 const char *LinkingOutput =
nullptr;
1883 if (isa<LipoJobAction>(A)) {
1885 LinkingOutput = FinalOutput->getValue();
1893 ArchNames.size() > 1,
1894 LinkingOutput, CachedResults,
1901 C.
getArgs().hasArg(options::OPT_Qunused_arguments))
1905 (void)C.
getArgs().hasArg(options::OPT__HASH_HASH_HASH);
1908 (void)C.
getArgs().hasArg(options::OPT_driver_mode);
1909 (void)C.
getArgs().hasArg(options::OPT_rsp_quoting);
1915 if (!A->isClaimed()) {
1921 const Option &Opt = A->getOption();
1922 if (Opt.getKind() == Option::FlagClass) {
1923 bool DuplicateClaimed =
false;
1925 for (
const Arg *AA : C.
getArgs().filtered(&Opt)) {
1926 if (AA->isClaimed()) {
1927 DuplicateClaimed =
true;
1932 if (DuplicateClaimed)
1938 if (!
IsCLMode() || !A->getOption().matches(options::OPT_UNKNOWN))
1939 Diag(clang::diag::warn_drv_unused_argument)
1940 << A->getAsString(C.
getArgs());
1948 template <
typename T>
1952 if (
auto *OA = dyn_cast<OffloadAction>(CurAction)) {
1953 if (OA->hasHostDependence())
1954 if (
auto *HDep = dyn_cast<T>(OA->getHostDependence())) {
1958 if (OA->hasSingleDeviceDependence())
1959 if (
auto *DDep = dyn_cast<T>(OA->getSingleDeviceDependence())) {
1976 const Tool *ToolForJob =
nullptr;
1977 CollapsedOffloadAction.clear();
1984 Action *BackendJA = (isa<AssembleJobAction>(JA) && Inputs->size() == 1)
1987 auto *BackendOA = collapseOffloadingAction<BackendJobAction>(BackendJA);
1990 !C.
getArgs().hasArg(options::OPT_via_file_asm) &&
1991 !C.
getArgs().hasArg(options::OPT__SLASH_FA) &&
1992 !C.
getArgs().hasArg(options::OPT__SLASH_Fa) && BackendJA &&
1993 isa<BackendJobAction>(BackendJA)) {
2003 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2005 assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2006 "Backend job is not preceeded by compile job.");
2007 const Tool *Compiler = TC->
SelectTool(*cast<CompileJobAction>(CompileJA));
2013 JobAction *InputJA = cast<JobAction>(*Inputs->begin());
2015 if (BackendTool == Compiler)
2016 CompileJA = InputJA;
2020 ToolForJob = Compiler;
2024 CollapsedOffloadAction.push_back(CompileOA);
2026 CollapsedOffloadAction.push_back(BackendOA);
2033 if (isa<BackendJobAction>(JA)) {
2035 assert(Inputs->size() == 1);
2039 auto *CompileOA = collapseOffloadingAction<CompileJobAction>(CompileJA);
2041 assert(CompileJA && isa<CompileJobAction>(CompileJA) &&
2042 "Backend job is not preceeded by compile job.");
2043 const Tool *Compiler = TC->
SelectTool(*cast<CompileJobAction>(CompileJA));
2048 Inputs = &CompileJA->getInputs();
2049 ToolForJob = Compiler;
2052 CollapsedOffloadAction.push_back(CompileOA);
2065 Action *PreprocessJA = (Inputs->size() == 1) ? *Inputs->begin() :
nullptr;
2066 auto *PreprocessOA =
2067 collapseOffloadingAction<PreprocessJobAction>(PreprocessJA);
2069 if (PreprocessJA && isa<PreprocessJobAction>(PreprocessJA) &&
2070 !C.
getArgs().hasArg(options::OPT_no_integrated_cpp) &&
2071 !C.
getArgs().hasArg(options::OPT_traditional_cpp) && !SaveTemps &&
2072 !C.
getArgs().hasArg(options::OPT_rewrite_objc) &&
2076 CollapsedOffloadAction.push_back(PreprocessOA);
2084 bool AtTopLevel,
bool MultipleArchs,
const char *LinkingOutput,
2085 std::map<std::pair<const Action *, std::string>,
InputInfo> &CachedResults,
2086 bool BuildForOffloadDevice)
const {
2090 std::string TriplePlusArch = TC->
getTriple().normalize();
2092 TriplePlusArch +=
"-";
2093 TriplePlusArch += BoundArch;
2095 std::pair<const Action *, std::string> ActionTC = {A, TriplePlusArch};
2096 auto CachedResult = CachedResults.find(ActionTC);
2097 if (CachedResult != CachedResults.end()) {
2098 return CachedResult->second;
2101 C, A, TC, BoundArch, AtTopLevel, MultipleArchs, LinkingOutput,
2102 CachedResults, BuildForOffloadDevice);
2103 CachedResults[ActionTC] = Result;
2107 InputInfo Driver::BuildJobsForActionNoCache(
2109 bool AtTopLevel,
bool MultipleArchs,
const char *LinkingOutput,
2110 std::map<std::pair<const Action *, std::string>,
InputInfo> &CachedResults,
2111 bool BuildForOffloadDevice)
const {
2112 llvm::PrettyStackTraceString CrashInfo(
"Building compilation jobs");
2140 if (OA->hasSingleDeviceDependence()) {
2142 OA->doOnEachDeviceDependence([&](
Action *DepA,
const ToolChain *DepTC,
2143 const char *DepBoundArch) {
2146 !!DepBoundArch, LinkingOutput,
2147 CachedResults,
true);
2156 OA->doOnEachDependence(
2157 BuildForOffloadDevice,
2160 C, DepA, DepTC, DepBoundArch,
false,
2161 !!DepBoundArch, LinkingOutput, CachedResults,
2166 A = BuildForOffloadDevice
2167 ? OA->getSingleDeviceDependence(
true)
2168 : OA->getHostDependence();
2171 if (
const InputAction *IA = dyn_cast<InputAction>(A)) {
2174 const Arg &
Input = IA->getInputArg();
2176 if (Input.getOption().matches(options::OPT_INPUT)) {
2177 const char *
Name = Input.getValue();
2188 TC = &getToolChain(C.
getArgs(),
2195 MultipleArchs, LinkingOutput, CachedResults,
2196 BuildForOffloadDevice);
2202 const JobAction *JA = cast<JobAction>(A);
2207 Inputs, CollapsedOffloadActions);
2213 for (
const auto *OA : CollapsedOffloadActions)
2214 cast<OffloadAction>(OA)->doOnEachDependence(
2215 BuildForOffloadDevice,
2218 C, DepA, DepTC, DepBoundArch, AtTopLevel,
2219 !!DepBoundArch, LinkingOutput, CachedResults,
2226 for (
const Action *Input : *Inputs) {
2230 bool SubJobAtTopLevel =
2231 AtTopLevel && (isa<DsymutilJobAction>(A) || isa<VerifyJobAction>(A));
2233 C, Input, TC, BoundArch, SubJobAtTopLevel, MultipleArchs, LinkingOutput,
2234 CachedResults, BuildForOffloadDevice));
2238 const char *BaseInput = InputInfos[0].getBaseInput();
2242 if (JA->
getType() == types::TY_dSYM)
2243 BaseInput = InputInfos[0].getFilename();
2246 if (!OffloadDependencesInputInfo.empty())
2247 InputInfos.append(OffloadDependencesInputInfo.begin(),
2248 OffloadDependencesInputInfo.end());
2252 if (JA->
getType() == types::TY_Nothing)
2256 AtTopLevel, MultipleArchs,
2262 <<
" - \"" << T->
getName() <<
"\", inputs: [";
2263 for (
unsigned i = 0, e = InputInfos.size(); i != e; ++i) {
2264 llvm::errs() << InputInfos[i].getAsString();
2266 llvm::errs() <<
", ";
2268 llvm::errs() <<
"], output: " << Result.
getAsString() <<
"\n";
2278 return Target.isOSWindows() ?
"a.exe" :
"a.out";
2290 if (ArgValue.empty()) {
2292 Filename = BaseName;
2293 }
else if (llvm::sys::path::is_separator(Filename.back())) {
2295 llvm::sys::path::append(Filename, BaseName);
2298 if (!llvm::sys::path::has_extension(ArgValue)) {
2302 if (FileType == types::TY_Image &&
2303 Args.hasArg(options::OPT__SLASH_LD, options::OPT__SLASH_LDd)) {
2308 llvm::sys::path::replace_extension(Filename, Extension);
2311 return Args.MakeArgString(Filename.c_str());
2315 const char *BaseInput,
2316 const char *BoundArch,
bool AtTopLevel,
2318 StringRef NormalizedTriple)
const {
2319 llvm::PrettyStackTraceString CrashInfo(
"Computing output path");
2321 if (AtTopLevel && !isa<DsymutilJobAction>(JA) && !isa<VerifyJobAction>(JA)) {
2322 if (Arg *FinalOutput = C.
getArgs().getLastArg(options::OPT_o))
2327 if (C.
getArgs().hasArg(options::OPT__SLASH_P)) {
2328 assert(AtTopLevel && isa<PreprocessJobAction>(JA));
2329 StringRef BaseName = llvm::sys::path::filename(BaseInput);
2331 if (Arg *A = C.
getArgs().getLastArg(options::OPT__SLASH_Fi))
2332 NameArg = A->getValue();
2340 (isa<PreprocessJobAction>(JA) || JA.
getType() == types::TY_ModuleFile))
2344 if (JA.
getType() == types::TY_PP_Asm &&
2345 (C.
getArgs().hasArg(options::OPT__SLASH_FA) ||
2346 C.
getArgs().hasArg(options::OPT__SLASH_Fa))) {
2348 StringRef BaseName = llvm::sys::path::filename(BaseInput);
2349 StringRef FaValue = C.
getArgs().getLastArgValue(options::OPT__SLASH_Fa);
2357 !C.
getArgs().hasArg(options::OPT__SLASH_Fo)) ||
2359 StringRef
Name = llvm::sys::path::filename(BaseInput);
2360 std::pair<StringRef, StringRef> Split = Name.split(
'.');
2370 if (isa<DsymutilJobAction>(JA) || isa<VerifyJobAction>(JA))
2371 BaseName = BasePath;
2373 BaseName = llvm::sys::path::filename(BasePath);
2376 const char *NamedOutput;
2378 if (JA.
getType() == types::TY_Object &&
2379 C.
getArgs().hasArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)) {
2383 .getLastArg(options::OPT__SLASH_Fo, options::OPT__SLASH_o)
2387 }
else if (JA.
getType() == types::TY_Image &&
2388 C.
getArgs().hasArg(options::OPT__SLASH_Fe,
2389 options::OPT__SLASH_o)) {
2393 .getLastArg(options::OPT__SLASH_Fe, options::OPT__SLASH_o)
2397 }
else if (JA.
getType() == types::TY_Image) {
2402 }
else if (MultipleArchs && BoundArch) {
2406 Output.append(BoundArch);
2407 NamedOutput = C.
getArgs().MakeArgString(Output.c_str());
2415 assert(Suffix &&
"All types used for output should have a suffix.");
2417 std::string::size_type
End = std::string::npos;
2419 End = BaseName.rfind(
'.');
2422 if (MultipleArchs && BoundArch) {
2424 Suffixed.append(BoundArch);
2429 if (!AtTopLevel && C.
getArgs().hasArg(options::OPT_emit_llvm) &&
2430 JA.
getType() == types::TY_LLVM_BC)
2434 NamedOutput = C.
getArgs().MakeArgString(Suffixed.c_str());
2439 JA.
getType() != types::TY_PCH) {
2440 Arg *FinalOutput = C.
getArgs().getLastArg(options::OPT_o);
2442 llvm::sys::path::remove_filename(TempPath);
2443 StringRef OutputFileName = llvm::sys::path::filename(NamedOutput);
2444 llvm::sys::path::append(TempPath, OutputFileName);
2445 NamedOutput = C.
getArgs().MakeArgString(TempPath.c_str());
2451 bool SameFile =
false;
2453 llvm::sys::fs::current_path(Result);
2454 llvm::sys::path::append(Result, BaseName);
2455 llvm::sys::fs::equivalent(BaseInput, Result.c_str(), SameFile);
2458 StringRef
Name = llvm::sys::path::filename(BaseInput);
2459 std::pair<StringRef, StringRef> Split = Name.split(
'.');
2468 llvm::sys::path::remove_filename(BasePath);
2469 if (BasePath.empty())
2470 BasePath = NamedOutput;
2472 llvm::sys::path::append(BasePath, NamedOutput);
2486 llvm::sys::path::append(
P, Name);
2487 if (llvm::sys::fs::exists(Twine(
P)))
2492 llvm::sys::path::append(P, Name);
2493 if (llvm::sys::fs::exists(Twine(P)))
2500 llvm::sys::path::append(P, Name);
2501 if (llvm::sys::fs::exists(Twine(P)))
2508 void Driver::generatePrefixedToolNames(
2513 Names.emplace_back(Tool);
2516 std::string LLVMDefaultTargetTriple = llvm::sys::getDefaultTargetTriple();
2518 Names.emplace_back(LLVMDefaultTargetTriple +
"-" + Tool);
2523 for (
const auto &
Name : Names) {
2524 llvm::sys::path::append(Dir,
Name);
2525 if (llvm::sys::fs::can_execute(Twine(Dir)))
2527 llvm::sys::path::remove_filename(Dir);
2535 generatePrefixedToolNames(Name, TC, TargetSpecificExecutables);
2540 if (llvm::sys::fs::is_directory(PrefixDir)) {
2546 if (llvm::sys::fs::can_execute(Twine(P)))
2552 for (
const auto &Path : List) {
2559 for (
const auto &TargetSpecificExecutable : TargetSpecificExecutables)
2560 if (llvm::ErrorOr<std::string>
P =
2561 llvm::sys::findProgramByName(TargetSpecificExecutable))
2568 const char *Suffix)
const {
2570 std::error_code EC = llvm::sys::fs::createTemporaryFile(Prefix, Suffix, Path);
2572 Diag(clang::diag::err_unable_to_make_temp) << EC.message();
2581 if (Arg *FpArg = C.
getArgs().getLastArg(options::OPT__SLASH_Fp)) {
2585 Output = FpArg->getValue();
2589 if (!llvm::sys::path::has_extension(Output))
2593 llvm::sys::path::replace_extension(Output,
".pch");
2595 return Output.str();
2598 const ToolChain &Driver::getToolChain(
const ArgList &Args,
2599 const llvm::Triple &Target)
const {
2601 ToolChain *&TC = ToolChains[Target.str()];
2603 switch (Target.getOS()) {
2604 case llvm::Triple::Haiku:
2607 case llvm::Triple::CloudABI:
2610 case llvm::Triple::Darwin:
2611 case llvm::Triple::MacOSX:
2612 case llvm::Triple::IOS:
2613 case llvm::Triple::TvOS:
2614 case llvm::Triple::WatchOS:
2617 case llvm::Triple::DragonFly:
2620 case llvm::Triple::OpenBSD:
2623 case llvm::Triple::Bitrig:
2626 case llvm::Triple::NetBSD:
2629 case llvm::Triple::FreeBSD:
2632 case llvm::Triple::Minix:
2635 case llvm::Triple::Linux:
2636 case llvm::Triple::ELFIAMCU:
2637 if (Target.getArch() == llvm::Triple::hexagon)
2639 else if ((Target.getVendor() == llvm::Triple::MipsTechnologies) &&
2640 !Target.hasEnvironment())
2645 case llvm::Triple::NaCl:
2648 case llvm::Triple::Solaris:
2651 case llvm::Triple::AMDHSA:
2654 case llvm::Triple::Win32:
2655 switch (Target.getEnvironment()) {
2657 if (Target.isOSBinFormatELF())
2659 else if (Target.isOSBinFormatMachO())
2664 case llvm::Triple::GNU:
2667 case llvm::Triple::Itanium:
2670 case llvm::Triple::MSVC:
2671 case llvm::Triple::UnknownEnvironment:
2676 case llvm::Triple::CUDA:
2679 case llvm::Triple::PS4:
2685 switch (Target.getArch()) {
2686 case llvm::Triple::tce:
2689 case llvm::Triple::hexagon:
2692 case llvm::Triple::lanai:
2695 case llvm::Triple::xcore:
2698 case llvm::Triple::wasm32:
2699 case llvm::Triple::wasm64:
2703 if (Target.getVendor() == llvm::Triple::Myriad)
2705 else if (Target.isOSBinFormatELF())
2707 else if (Target.isOSBinFormatMachO())
2719 if (JA.
size() != 1 ||
2724 if (!isa<PreprocessJobAction>(JA) && !isa<PrecompileJobAction>(JA) &&
2725 !isa<CompileJobAction>(JA) && !isa<BackendJobAction>(JA))
2737 unsigned &Minor,
unsigned &Micro,
2741 Major = Minor = Micro = 0;
2746 Major = (
unsigned)strtol(Str, &End, 10);
2747 if (*Str !=
'\0' && *End ==
'\0')
2753 Minor = (
unsigned)strtol(Str, &End, 10);
2754 if (*Str !=
'\0' && *End ==
'\0')
2760 Micro = (
unsigned)strtol(Str, &End, 10);
2761 if (*Str !=
'\0' && *End ==
'\0')
2781 unsigned CurDigit = 0;
2782 while (CurDigit < Digits.size()) {
2783 unsigned Digit = (
unsigned)strtol(Str, &End, 10);
2784 Digits[CurDigit] = Digit;
2785 if (*Str !=
'\0' && *End ==
'\0')
2787 if (*End !=
'.' || Str == End)
2797 std::pair<unsigned, unsigned> Driver::getIncludeExcludeOptionFlagMasks()
const {
2798 unsigned IncludedFlagsBitmask = 0;
2801 if (Mode == CLMode) {
2809 return std::make_pair(IncludedFlagsBitmask, ExcludedFlagsBitmask);
2813 return Args.hasFlag(options::OPT_Ofast, options::OPT_O_Group,
false);
static bool DiagnoseInputExistence(const Driver &D, const DerivedArgList &Args, StringRef Value, types::ID Ty)
Check that the file referenced by Value exists.
ID
ID - Ordered values for successive stages in the compilation process which interact with user options...
const Driver & getDriver() const
Driver(StringRef ClangExecutable, StringRef DefaultTargetTriple, DiagnosticsEngine &Diags, IntrusiveRefCntPtr< vfs::FileSystem > VFS=nullptr)
static bool ContainsCompileOrAssembleAction(const Action *A)
Check whether the given input tree contains any compilation or assembly actions.
void ParseDriverMode(ArrayRef< const char * > Args)
ParseDriverMode - Look for and handle the driver mode option in Args.
const char * CudaArchToString(CudaArch A)
const ArgStringMap & getResultFiles() const
std::string getClangFullVersion()
Retrieves a string representing the complete clang version, which includes the clang version number...
bool canLipoType(ID Id)
canLipoType - Is this type acceptable as the output of a universal build (currently, just the Nothing, Image, and Object types).
IntrusiveRefCntPtr< FileSystem > getRealFileSystem()
Gets an vfs::FileSystem for the 'real' file system, as seen by the operating system.
const char * getExecutable() const
const char * getTypeTempSuffix(ID Id, bool CLMode=false)
getTypeTempSuffix - Return the suffix to use when creating a temp file of this type, or null if unspecified.
static Arg * MakeInputArg(DerivedArgList &Args, OptTable *Opts, StringRef Value)
unsigned CCCUsePCH
Use lazy precompiled headers for PCH support.
void setResponseFile(const char *FileName)
Set to pass arguments via a response file when launching the command.
const char * GetNamedOutputPath(Compilation &C, const JobAction &JA, const char *BaseInput, const char *BoundArch, bool AtTopLevel, bool MultipleArchs, StringRef NormalizedTriple) const
GetNamedOutputPath - Return the name to use for the output of the action JA.
bool hasErrorOccurred() const
std::string GetTemporaryPath(StringRef Prefix, const char *Suffix) const
GetTemporaryPath - Return the pathname of a temporary file to use as part of compilation; the file wi...
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
const llvm::opt::OptTable & getOpts() const
std::string DyldPrefix
Dynamic loader prefix, if present.
static StringRef getCategoryNameFromID(unsigned CategoryID)
Given a category ID, return the name of the category.
bool hasErrorOccurred() const
Determine whether any errors have occurred since this object instance was created.
DiagnosticBuilder Diag(unsigned DiagID) const
CudaArch StringToCudaArch(llvm::StringRef S)
static bool GetReleaseVersion(const char *Str, unsigned &Major, unsigned &Minor, unsigned &Micro, bool &HadExtra)
GetReleaseVersion - Parse (([0-9]+)(.
Compilation * BuildCompilation(ArrayRef< const char * > Args)
BuildCompilation - Construct a compilation object for a command line argument vector.
Type used to communicate device actions.
void BuildUniversalActions(Compilation &C, const ToolChain &TC, const InputList &BAInputs) const
BuildUniversalActions - Construct the list of actions to perform for the given arguments, which may require a universal build.
const Tool & getCreator() const
getCreator - Return the Tool which caused the creation of this job.
RAII class that determines when any errors have occurred between the time the instance was created an...
types::ID getType() const
bool ShouldUseClangCompiler(const JobAction &JA) const
ShouldUseClangCompiler - Should the clang compiler be used to handle this action. ...
T * MakeAction(Args &&...Arg)
Creates a new Action owned by this Compilation.
float __ovld __cnfn normalize(float p)
Returns a vector in the same direction as p but with a length of 1.
bool CCCIsCXX() const
Whether the driver should follow g++ like behavior.
void addOffloadDeviceToolChain(const ToolChain *DeviceToolChain, Action::OffloadKind OffloadKind)
class LLVM_ALIGNAS(8) DependentTemplateSpecializationType const IdentifierInfo * Name
Represents a template specialization type whose template cannot be resolved, e.g. ...
static bool ScanDirForExecutable(SmallString< 128 > &Dir, ArrayRef< std::string > Names)
void PrintHelp(bool ShowHidden) const
PrintHelp - Print the help text.
OffloadKind getOffloadingDeviceKind() const
void PrintActions(const Compilation &C) const
PrintActions - Print the list of actions.
std::string Dir
The path the driver executable was in, as invoked from the command line.
const std::string & gccSuffix() const
Get the detected GCC installation path suffix for the multi-arch target variant.
ID lookupCXXTypeForCType(ID Id)
lookupCXXTypeForCType - Lookup CXX input type that corresponds to given C type (used for clang++ emul...
Type used to communicate host actions.
ActionClass getKind() const
virtual void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const
static unsigned getNumberOfCategories()
Return the number of diagnostic categories.
static Action * buildCudaActions(Compilation &C, DerivedArgList &Args, const Arg *InputArg, Action *HostAction, ActionList &Actions)
Action - Represent an abstract compilation step to perform.
InputInfo BuildJobsForAction(Compilation &C, const Action *A, const ToolChain *TC, const char *BoundArch, bool AtTopLevel, bool MultipleArchs, const char *LinkingOutput, std::map< std::pair< const Action *, std::string >, InputInfo > &CachedResults, bool BuildForOffloadDevice) const
BuildJobsForAction - Construct the jobs to perform for the action A and return an InputInfo for the r...
bool HandleImmediateArgs(const Compilation &C)
HandleImmediateArgs - Handle any arguments which should be treated before building actions or binding...
std::string getOffloadingKindPrefix() const
Return a string containing the offload kind of the action.
Concrete class used by the front-end to report problems and issues.
const llvm::opt::DerivedArgList & getArgs() const
bool embedBitcodeEnabled() const
void BuildActions(Compilation &C, llvm::opt::DerivedArgList &Args, const InputList &Inputs, ActionList &Actions) const
BuildActions - Construct the list of actions to perform for the given arguments, which are only done ...
std::string GetFilePath(const char *Name, const ToolChain &TC) const
GetFilePath - Lookup Name in the list of file search paths.
llvm::opt::InputArgList ParseArgStrings(ArrayRef< const char * > Args)
ParseArgStrings - Parse the given list of strings into an ArgList.
bool isOptimizationLevelFast(const llvm::opt::ArgList &Args)
bool IsCLMode() const
Whether the driver should follow cl.exe like behavior.
void generateCompilationDiagnostics(Compilation &C, const Command &FailingCommand)
generateCompilationDiagnostics - Generate diagnostics information including preprocessed source file(...
Driver - Encapsulate logic for constructing compilation processes from a set of gcc-driver-like comma...
const Action & getSource() const
getSource - Return the Action which caused the creation of this job.
detail::InMemoryDirectory::const_iterator I
void PrintVersion(const Compilation &C, raw_ostream &OS) const
PrintVersion - Print the driver version.
input_iterator input_begin()
bool isSaveTempsEnabled() const
ID getPreprocessedType(ID Id)
getPreprocessedType - Get the ID of the type for this input when it has been preprocessed, or INVALID if this input is not preprocessed.
void add(Action &A, const ToolChain &TC, const char *BoundArch, OffloadKind OKind)
Add a action along with the associated toolchain, bound arch, and offload kind.
bool getCheckInputsExist() const
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
const char * getPhaseName(ID Id)
const ToolChain * getSingleOffloadToolChain() const
Return an offload toolchain of the provided kind.
Defines version macros and version-related utility functions for Clang.
bool CleanupFileList(const llvm::opt::ArgStringList &Files, bool IssueErrors=false) const
CleanupFileList - Remove the files in the given list.
static OffloadAction * collapseOffloadingAction(Action *&CurAction)
Collapse an offloading action looking for a job of the given type.
This corresponds to a single GCC Multilib, or a segment of one controlled by a command line flag...
const char * getOffloadingArch() const
void getCompilationPhases(ID Id, llvm::SmallVectorImpl< phases::ID > &Phases)
getCompilationPhases - Get the list of compilation phases ('Phases') to be done for type 'Id'...
Action * ConstructPhaseAction(Compilation &C, const llvm::opt::ArgList &Args, phases::ID Phase, Action *Input) const
ConstructAction - Construct the appropriate action to do for Phase on the Input, taking in to account...
The result type of a method or function.
static void PrintDiagnosticCategories(raw_ostream &OS)
PrintDiagnosticCategories - Implement the –print-diagnostic-categories option.
int ExecuteCompilation(Compilation &C, SmallVectorImpl< std::pair< int, const Command * > > &FailingCommands)
ExecuteCompilation - Execute the compilation according to the command line arguments and return an ap...
std::string GetClPchPath(Compilation &C, StringRef BaseName) const
Return the pathname of the pch file in clang-cl mode.
bool UseStdLib
If the standard library is used.
bool CleanupFileMap(const ArgStringMap &Files, const JobAction *JA, bool IssueErrors=false) const
CleanupFileMap - Remove the files in the given map.
std::string GetProgramPath(const char *Name, const ToolChain &TC) const
GetProgramPath - Lookup Name in the list of program search paths.
static unsigned PrintActions1(const Compilation &C, Action *A, std::map< Action *, unsigned > &Ids)
void BuildJobs(Compilation &C) const
BuildJobs - Bind actions to concrete tools and translate arguments to form the list of jobs to run...
const TemplateArgument * iterator
Command - An executable path/name and argument vector to execute.
bool isCuda(ID Id)
isCuda - Is this a CUDA input.
std::string InstalledDir
The path to the installed clang directory, if any.
bool isSaveTempsObj() const
const char * addResultFile(const char *Name, const JobAction *JA)
addResultFile - Add a file to remove on failure, and returns its argument.
LTOKind getLTOMode() const
Get the specific kind of LTO being performed.
bool isAcceptedByClang(ID Id)
isAcceptedByClang - Can clang handle this input type.
const llvm::opt::DerivedArgList & getArgsForToolChain(const ToolChain *TC, const char *BoundArch)
getArgsForToolChain - Return the derived argument list for the tool chain TC (or the default tool cha...
An offload action combines host or/and device actions according to the programming model implementati...
static const Tool * selectToolForJob(Compilation &C, bool SaveTemps, bool EmbedBitcode, const ToolChain *TC, const JobAction *JA, const ActionList *&Inputs, ActionList &CollapsedOffloadAction)
const llvm::opt::ArgStringList & getArguments() const
const ToolChain & getDefaultToolChain() const
void setIgnoreAllWarnings(bool Val)
When set to true, any unmapped warnings are ignored.
const char * getDefaultImageName() const
Returns the default name for linked images (e.g., "a.out").
bool CCCIsCPP() const
Whether the driver is just the preprocessor.
void EmbedBitcode(llvm::Module *M, const CodeGenOptions &CGOpts, llvm::MemoryBufferRef Buf)
unsigned CCCPrintBindings
Only print tool bindings, don't build any jobs.
const ArgStringMap & getFailureResultFiles() const
const char * getClassName() const
std::string SysRoot
sysroot, if present
std::string Name
The name the driver was invoked as.
Defines the virtual file system interface vfs::FileSystem.
detail::InMemoryDirectory::const_iterator E
ActionList & getActions()
std::string getOffloadingFileNamePrefix(llvm::StringRef NormalizedTriple) const
Return a string that can be used as prefix in order to generate unique files for each offloading kind...
void ExecuteJobs(const JobList &Jobs, SmallVectorImpl< std::pair< int, const Command * >> &FailingCommands) const
ExecuteJob - Execute a single job.
void BuildInputs(const ToolChain &TC, llvm::opt::DerivedArgList &Args, InputList &Inputs) const
BuildInputs - Construct the list of inputs and their types from the given arguments.
Compilation - A set of tasks to perform for a single driver invocation.
static void printArg(llvm::raw_ostream &OS, const char *Arg, bool Quote)
Print a command argument, and optionally quote it.
static void printArgList(raw_ostream &OS, const llvm::opt::ArgList &Args)
static llvm::Triple computeTargetTriple(const Driver &D, StringRef DefaultTargetTriple, const ArgList &Args, StringRef DarwinArchName="")
Compute target triple from args.
const llvm::opt::InputArgList & getInputArgs() const
void Print(llvm::raw_ostream &OS, const char *Terminator, bool Quote, CrashReportInfo *CrashInfo=nullptr) const
llvm::opt::OptTable * createDriverOptTable()
char __ovld __cnfn max(char x, char y)
Returns y if x < y, otherwise it returns x.
StringRef getSysRoot() const
Returns the sysroot path.
bool isUsingLTO() const
Returns true if we are performing any kind of LTO.
std::string DefaultTargetTriple
Default target triple.
void propagateHostOffloadInfo(unsigned OKinds, const char *OArch)
Append the host offload info of this action and propagate it to its dependences.
const llvm::opt::ArgStringList & getTempFiles() const
const char * addTempFile(const char *Name)
addTempFile - Add a file to remove on exit, and returns its argument.
std::string DriverTitle
Driver title to use with help.
static const char * MakeCLOutputFilename(const ArgList &Args, StringRef ArgValue, StringRef BaseName, types::ID FileType)
Create output filename based on ArgValue, which could either be a full filename, filename without ext...
#define CLANG_VERSION_STRING
A string that describes the Clang version number, e.g., "1.0".
void CreateOffloadingDeviceToolChains(Compilation &C, InputList &Inputs)
CreateOffloadingDeviceToolChains - create all the toolchains required to support offloading devices g...
bool appendSuffixForType(ID Id)
appendSuffixForType - When generating outputs of this type, should the suffix be appended (instead of...
ID lookupTypeForTypeSpecifier(const char *Name)
lookupTypeForTypSpecifier - Lookup the type to use for a user specified type name.
void initCompilationForDiagnostics()
initCompilationForDiagnostics - Remove stale state and suppress output so compilation can be reexecut...
unsigned CCGenDiagnostics
Whether the driver is generating diagnostics for debugging purposes.
std::string ResourceDir
The path to the compiler resource directory.