xref: /llvm-project/clang/lib/Frontend/CreateInvocationFromCommandLine.cpp (revision 2ff7ca98a99bbfc4f44b8ba1e2e4e594f8ee253e)
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/Host.h"
26 using namespace clang;
27 using namespace llvm::opt;
28 
29 std::unique_ptr<CompilerInvocation> clang::createInvocationFromCommandLine(
30     ArrayRef<const char *> ArgList, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
31     IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS, bool ShouldRecoverOnErorrs,
32     std::vector<std::string> *CC1Args) {
33   if (!Diags.get()) {
34     // No diagnostics engine was provided, so create our own diagnostics object
35     // with the default options.
36     Diags = CompilerInstance::createDiagnostics(new DiagnosticOptions);
37   }
38 
39   SmallVector<const char *, 16> Args(ArgList.begin(), ArgList.end());
40 
41   // FIXME: Find a cleaner way to force the driver into restricted modes.
42   Args.insert(
43       llvm::find_if(
44           Args, [](const char *Elem) { return llvm::StringRef(Elem) == "--"; }),
45       "-fsyntax-only");
46 
47   // FIXME: We shouldn't have to pass in the path info.
48   driver::Driver TheDriver(Args[0], llvm::sys::getDefaultTargetTriple(), *Diags,
49                            "clang LLVM compiler", VFS);
50 
51   // Don't check that inputs exist, they may have been remapped.
52   TheDriver.setCheckInputsExist(false);
53 
54   std::unique_ptr<driver::Compilation> C(TheDriver.BuildCompilation(Args));
55   if (!C)
56     return nullptr;
57 
58   // Just print the cc1 options if -### was present.
59   if (C->getArgs().hasArg(driver::options::OPT__HASH_HASH_HASH)) {
60     C->getJobs().Print(llvm::errs(), "\n", true);
61     return nullptr;
62   }
63 
64   // We expect to get back exactly one command job, if we didn't something
65   // failed. Offload compilation is an exception as it creates multiple jobs. If
66   // that's the case, we proceed with the first job. If caller needs a
67   // particular job, it should be controlled via options (e.g.
68   // --cuda-{host|device}-only for CUDA) passed to the driver.
69   const driver::JobList &Jobs = C->getJobs();
70   bool OffloadCompilation = false;
71   if (Jobs.size() > 1) {
72     for (auto &A : C->getActions()){
73       // On MacOSX real actions may end up being wrapped in BindArchAction
74       if (isa<driver::BindArchAction>(A))
75         A = *A->input_begin();
76       if (isa<driver::OffloadAction>(A)) {
77         OffloadCompilation = true;
78         break;
79       }
80     }
81   }
82 
83   bool PickFirstOfMany = OffloadCompilation || ShouldRecoverOnErorrs;
84   if (Jobs.size() == 0 || (Jobs.size() > 1 && !PickFirstOfMany)) {
85     SmallString<256> Msg;
86     llvm::raw_svector_ostream OS(Msg);
87     Jobs.Print(OS, "; ", true);
88     Diags->Report(diag::err_fe_expected_compiler_job) << OS.str();
89     return nullptr;
90   }
91   auto Cmd = llvm::find_if(Jobs, [](const driver::Command &Cmd) {
92     return StringRef(Cmd.getCreator().getName()) == "clang";
93   });
94   if (Cmd == Jobs.end()) {
95     Diags->Report(diag::err_fe_expected_clang_command);
96     return nullptr;
97   }
98 
99   const ArgStringList &CCArgs = Cmd->getArguments();
100   if (CC1Args)
101     *CC1Args = {CCArgs.begin(), CCArgs.end()};
102   auto CI = std::make_unique<CompilerInvocation>();
103   if (!CompilerInvocation::CreateFromArgs(*CI, CCArgs, *Diags, Args[0]) &&
104       !ShouldRecoverOnErorrs)
105     return nullptr;
106   return CI;
107 }
108