xref: /llvm-project/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp (revision df9a14d7bbf1180e4f1474254c9d7ed6bcb4ce55)
1 //===--- CreateInvocationFromCommandLine.cpp - CompilerInvocation from Args ==//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // Construct a compiler invocation object for command line driver arguments
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "clang/Basic/DiagnosticOptions.h"
14 #include "clang/Driver/Action.h"
15 #include "clang/Driver/Compilation.h"
16 #include "clang/Driver/Driver.h"
17 #include "clang/Driver/Options.h"
18 #include "clang/Driver/Tool.h"
19 #include "clang/Frontend/CompilerInstance.h"
20 #include "clang/Frontend/FrontendDiagnostic.h"
21 #include "clang/Frontend/Utils.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/Option/ArgList.h"
25 #include "llvm/Support/VirtualFileSystem.h"
26 #include "llvm/TargetParser/Host.h"
27 using namespace clang;
28 using namespace llvm::opt;
29 
30 std::unique_ptr<CompilerInvocation>
31 clang::createInvocation(ArrayRef<const char *> ArgList,
32                         CreateInvocationOptions Opts) {
33   assert(!ArgList.empty());
34   auto Diags = Opts.Diags
35                    ? std::move(Opts.Diags)
36                    : CompilerInstance::createDiagnostics(
37                          Opts.VFS ? *Opts.VFS : *llvm::vfs::getRealFileSystem(),
38                          new DiagnosticOptions);
39 
40   SmallVector<const char *, 16> Args(ArgList);
41 
42   // FIXME: Find a cleaner way to force the driver into restricted modes.
43   Args.insert(
44       llvm::find_if(
45           Args, [](const char *Elem) { return llvm::StringRef(Elem) == "--"; }),
46       "-fsyntax-only");
47 
48   // FIXME: We shouldn't have to pass in the path info.
49   driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), *Diags,
50                            "clang LLVM compiler", Opts.VFS);
51 
52   // Don't check that inputs exist, they may have been remapped.
53   TheDriver.setCheckInputsExist(false);
54   TheDriver.setProbePrecompiled(Opts.ProbePrecompiled);
55 
56   std::unique_ptr<driver::Compilation> C(TheDriver.BuildCompilation(Args));
57   if (!C)
58     return nullptr;
59 
60   if (C->getArgs().hasArg(driver::options::OPT_fdriver_only))
61     return nullptr;
62 
63   // Just print the cc1 options if -### was present.
64   if (C->getArgs().hasArg(driver::options::OPT__HASH_HASH_HASH)) {
65     C->getJobs().Print(llvm::errs(), "\n", true);
66     return nullptr;
67   }
68 
69   // We expect to get back exactly one command job, if we didn't something
70   // failed. Offload compilation is an exception as it creates multiple jobs. If
71   // that's the case, we proceed with the first job. If caller needs a
72   // particular job, it should be controlled via options (e.g.
73   // --cuda-{host|device}-only for CUDA) passed to the driver.
74   const driver::JobList &Jobs = C->getJobs();
75   bool OffloadCompilation = false;
76   if (Jobs.size() > 1) {
77     for (auto &A : C->getActions()){
78       // On MacOSX real actions may end up being wrapped in BindArchAction
79       if (isa<driver::BindArchAction>(A))
80         A = *A->input_begin();
81       if (isa<driver::OffloadAction>(A)) {
82         OffloadCompilation = true;
83         break;
84       }
85     }
86   }
87 
88   bool PickFirstOfMany = OffloadCompilation || Opts.RecoverOnError;
89   if (Jobs.size() == 0 || (Jobs.size() > 1 && !PickFirstOfMany)) {
90     SmallString<256> Msg;
91     llvm::raw_svector_ostream OS(Msg);
92     Jobs.Print(OS, "; ", true);
93     Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
94     return nullptr;
95   }
96   auto Cmd = llvm::find_if(Jobs, [](const driver::Command &Cmd) {
97     return StringRef(Cmd.getCreator().getName()) == "clang";
98   });
99   if (Cmd == Jobs.end()) {
100     Diags->Report(diag::err_fe_expected_clang_command);
101     return nullptr;
102   }
103 
104   const ArgStringList &CCArgs = Cmd->getArguments();
105   if (Opts.CC1Args)
106     *Opts.CC1Args = {CCArgs.begin(), CCArgs.end()};
107   auto CI = std::make_unique<CompilerInvocation>();
108   if (!CompilerInvocation::CreateFromArgs(*CI, CCArgs, *Diags, Args[0]) &&
109       !Opts.RecoverOnError)
110     return nullptr;
111   return CI;
112 }
113