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