1 | //===-- driver.cpp - Flang Driver -----------------------------------------===// |
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 | // This is the entry point to the flang driver; it is a thin wrapper |
10 | // for functionality in the Driver flang library. |
11 | // |
12 | //===----------------------------------------------------------------------===// |
13 | // |
14 | // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/ |
15 | // |
16 | //===----------------------------------------------------------------------===// |
17 | |
18 | #include "clang/Driver/Driver.h" |
19 | #include "flang/Frontend/CompilerInvocation.h" |
20 | #include "flang/Frontend/TextDiagnosticPrinter.h" |
21 | #include "clang/Basic/Diagnostic.h" |
22 | #include "clang/Basic/DiagnosticIDs.h" |
23 | #include "clang/Basic/DiagnosticOptions.h" |
24 | #include "clang/Driver/Compilation.h" |
25 | #include "llvm/ADT/ArrayRef.h" |
26 | #include "llvm/ADT/IntrusiveRefCntPtr.h" |
27 | #include "llvm/Option/ArgList.h" |
28 | #include "llvm/Support/CommandLine.h" |
29 | #include "llvm/Support/InitLLVM.h" |
30 | #include "llvm/Support/VirtualFileSystem.h" |
31 | #include "llvm/Support/raw_ostream.h" |
32 | #include "llvm/TargetParser/Host.h" |
33 | #include <stdlib.h> |
34 | |
35 | // main frontend method. Lives inside fc1_main.cpp |
36 | extern int fc1_main(llvm::ArrayRef<const char *> argv, const char *argv0); |
37 | |
38 | std::string getExecutablePath(const char *argv0) { |
39 | // This just needs to be some symbol in the binary |
40 | void *p = (void *)(intptr_t)getExecutablePath; |
41 | return llvm::sys::fs::getMainExecutable(argv0, MainExecAddr: p); |
42 | } |
43 | |
44 | // This lets us create the DiagnosticsEngine with a properly-filled-out |
45 | // DiagnosticOptions instance |
46 | static clang::DiagnosticOptions * |
47 | createAndPopulateDiagOpts(llvm::ArrayRef<const char *> argv) { |
48 | auto *diagOpts = new clang::DiagnosticOptions; |
49 | |
50 | // Ignore missingArgCount and the return value of ParseDiagnosticArgs. |
51 | // Any errors that would be diagnosed here will also be diagnosed later, |
52 | // when the DiagnosticsEngine actually exists. |
53 | unsigned missingArgIndex, missingArgCount; |
54 | llvm::opt::InputArgList args = clang::driver::getDriverOptTable().ParseArgs( |
55 | Args: argv.slice(N: 1), MissingArgIndex&: missingArgIndex, MissingArgCount&: missingArgCount, |
56 | VisibilityMask: llvm::opt::Visibility(clang::driver::options::FlangOption)); |
57 | |
58 | (void)Fortran::frontend::parseDiagnosticArgs(*diagOpts, args); |
59 | |
60 | return diagOpts; |
61 | } |
62 | |
63 | static int executeFC1Tool(llvm::SmallVectorImpl<const char *> &argV) { |
64 | llvm::StringRef tool = argV[1]; |
65 | if (tool == "-fc1" ) |
66 | return fc1_main(argv: llvm::ArrayRef(argV).slice(N: 2), argv0: argV[0]); |
67 | |
68 | // Reject unknown tools. |
69 | // ATM it only supports fc1. Any fc1[*] is rejected. |
70 | llvm::errs() << "error: unknown integrated tool '" << tool << "'. " |
71 | << "Valid tools include '-fc1'.\n" ; |
72 | return 1; |
73 | } |
74 | |
75 | static void ExpandResponseFiles(llvm::StringSaver &saver, |
76 | llvm::SmallVectorImpl<const char *> &args) { |
77 | // We're defaulting to the GNU syntax, since we don't have a CL mode. |
78 | llvm::cl::TokenizerCallback tokenizer = &llvm::cl::TokenizeGNUCommandLine; |
79 | llvm::cl::ExpansionContext ExpCtx(saver.getAllocator(), tokenizer); |
80 | if (llvm::Error Err = ExpCtx.expandResponseFiles(Argv&: args)) { |
81 | llvm::errs() << toString(E: std::move(Err)) << '\n'; |
82 | } |
83 | } |
84 | |
85 | int main(int argc, const char **argv) { |
86 | |
87 | // Initialize variables to call the driver |
88 | llvm::InitLLVM x(argc, argv); |
89 | llvm::SmallVector<const char *, 256> args(argv, argv + argc); |
90 | |
91 | clang::driver::ParsedClangName targetandMode("flang" , "--driver-mode=flang" ); |
92 | std::string driverPath = getExecutablePath(argv0: args[0]); |
93 | |
94 | llvm::BumpPtrAllocator a; |
95 | llvm::StringSaver saver(a); |
96 | ExpandResponseFiles(saver, args); |
97 | |
98 | // Check if flang-new is in the frontend mode |
99 | auto firstArg = std::find_if(first: args.begin() + 1, last: args.end(), |
100 | pred: [](const char *a) { return a != nullptr; }); |
101 | if (firstArg != args.end()) { |
102 | if (llvm::StringRef(args[1]).starts_with(Prefix: "-cc1" )) { |
103 | llvm::errs() << "error: unknown integrated tool '" << args[1] << "'. " |
104 | << "Valid tools include '-fc1'.\n" ; |
105 | return 1; |
106 | } |
107 | // Call flang-new frontend |
108 | if (llvm::StringRef(args[1]).starts_with(Prefix: "-fc1" )) { |
109 | return executeFC1Tool(argV&: args); |
110 | } |
111 | } |
112 | |
113 | // Not in the frontend mode - continue in the compiler driver mode. |
114 | |
115 | // Create DiagnosticsEngine for the compiler driver |
116 | llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagOpts = |
117 | createAndPopulateDiagOpts(argv: args); |
118 | llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID( |
119 | new clang::DiagnosticIDs()); |
120 | Fortran::frontend::TextDiagnosticPrinter *diagClient = |
121 | new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), &*diagOpts); |
122 | |
123 | diagClient->setPrefix( |
124 | std::string(llvm::sys::path::stem(path: getExecutablePath(argv0: args[0])))); |
125 | |
126 | clang::DiagnosticsEngine diags(diagID, &*diagOpts, diagClient); |
127 | |
128 | // Prepare the driver |
129 | clang::driver::Driver theDriver(driverPath, |
130 | llvm::sys::getDefaultTargetTriple(), diags, |
131 | "flang LLVM compiler" ); |
132 | theDriver.setTargetAndMode(targetandMode); |
133 | #ifdef FLANG_RUNTIME_F128_MATH_LIB |
134 | theDriver.setFlangF128MathLibrary(FLANG_RUNTIME_F128_MATH_LIB); |
135 | #endif |
136 | std::unique_ptr<clang::driver::Compilation> c( |
137 | theDriver.BuildCompilation(Args: args)); |
138 | llvm::SmallVector<std::pair<int, const clang::driver::Command *>, 4> |
139 | failingCommands; |
140 | |
141 | // Set the environment variable, FLANG_COMPILER_OPTIONS_STRING, to contain all |
142 | // the compiler options. This is intended for the frontend driver, |
143 | // flang-new -fc1, to enable the implementation of the COMPILER_OPTIONS |
144 | // intrinsic. To this end, the frontend driver requires the list of the |
145 | // original compiler options, which is not available through other means. |
146 | // TODO: This way of passing information between the compiler and frontend |
147 | // drivers is discouraged. We should find a better way not involving env |
148 | // variables. |
149 | std::string compilerOptsGathered; |
150 | llvm::raw_string_ostream os(compilerOptsGathered); |
151 | for (int i = 0; i < argc; ++i) { |
152 | os << argv[i]; |
153 | if (i < argc - 1) { |
154 | os << ' '; |
155 | } |
156 | } |
157 | #ifdef _WIN32 |
158 | _putenv_s("FLANG_COMPILER_OPTIONS_STRING" , compilerOptsGathered.c_str()); |
159 | #else |
160 | setenv(name: "FLANG_COMPILER_OPTIONS_STRING" , value: compilerOptsGathered.c_str(), replace: 1); |
161 | #endif |
162 | |
163 | // Run the driver |
164 | int res = 1; |
165 | bool isCrash = false; |
166 | res = theDriver.ExecuteCompilation(C&: *c, FailingCommands&: failingCommands); |
167 | |
168 | for (const auto &p : failingCommands) { |
169 | int commandRes = p.first; |
170 | const clang::driver::Command *failingCommand = p.second; |
171 | if (!res) |
172 | res = commandRes; |
173 | |
174 | // If result status is < 0 (e.g. when sys::ExecuteAndWait returns -1), |
175 | // then the driver command signalled an error. On Windows, abort will |
176 | // return an exit code of 3. In these cases, generate additional diagnostic |
177 | // information if possible. |
178 | isCrash = commandRes < 0; |
179 | #ifdef _WIN32 |
180 | isCrash |= commandRes == 3; |
181 | #endif |
182 | if (isCrash) { |
183 | theDriver.generateCompilationDiagnostics(C&: *c, FailingCommand: *failingCommand); |
184 | break; |
185 | } |
186 | } |
187 | |
188 | diags.getClient()->finish(); |
189 | |
190 | // If we have multiple failing commands, we return the result of the first |
191 | // failing command. |
192 | return res; |
193 | } |
194 | |