| 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 std::unique_ptr<clang::DiagnosticOptions> |
| 47 | createAndPopulateDiagOpts(llvm::ArrayRef<const char *> argv) { |
| 48 | auto diagOpts = std::make_unique<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 = |
| 92 | clang::driver::ToolChain::getTargetAndModeFromProgramName(ProgName: argv[0]); |
| 93 | std::string driverPath = getExecutablePath(argv0: args[0]); |
| 94 | |
| 95 | llvm::BumpPtrAllocator a; |
| 96 | llvm::StringSaver saver(a); |
| 97 | ExpandResponseFiles(saver, args); |
| 98 | |
| 99 | // Check if flang is in the frontend mode |
| 100 | auto firstArg = std::find_if(first: args.begin() + 1, last: args.end(), |
| 101 | pred: [](const char *a) { return a != nullptr; }); |
| 102 | if (firstArg != args.end()) { |
| 103 | if (llvm::StringRef(args[1]).starts_with(Prefix: "-cc1" )) { |
| 104 | llvm::errs() << "error: unknown integrated tool '" << args[1] << "'. " |
| 105 | << "Valid tools include '-fc1'.\n" ; |
| 106 | return 1; |
| 107 | } |
| 108 | // Call flang frontend |
| 109 | if (llvm::StringRef(args[1]).starts_with(Prefix: "-fc1" )) { |
| 110 | return executeFC1Tool(argV&: args); |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | llvm::StringSet<> savedStrings; |
| 115 | // Handle FCC_OVERRIDE_OPTIONS, used for editing a command line behind the |
| 116 | // scenes. |
| 117 | if (const char *overrideStr = ::getenv(name: "FCC_OVERRIDE_OPTIONS" )) |
| 118 | clang::driver::applyOverrideOptions(Args&: args, OverrideOpts: overrideStr, SavedStrings&: savedStrings, |
| 119 | EnvVar: "FCC_OVERRIDE_OPTIONS" , OS: &llvm::errs()); |
| 120 | |
| 121 | // Not in the frontend mode - continue in the compiler driver mode. |
| 122 | |
| 123 | // Create DiagnosticsEngine for the compiler driver |
| 124 | std::unique_ptr<clang::DiagnosticOptions> diagOpts = |
| 125 | createAndPopulateDiagOpts(argv: args); |
| 126 | llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID( |
| 127 | new clang::DiagnosticIDs()); |
| 128 | Fortran::frontend::TextDiagnosticPrinter *diagClient = |
| 129 | new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), *diagOpts); |
| 130 | |
| 131 | diagClient->setPrefix( |
| 132 | std::string(llvm::sys::path::stem(path: getExecutablePath(argv0: args[0])))); |
| 133 | |
| 134 | clang::DiagnosticsEngine diags(diagID, *diagOpts, diagClient); |
| 135 | |
| 136 | // Prepare the driver |
| 137 | clang::driver::Driver theDriver(driverPath, |
| 138 | llvm::sys::getDefaultTargetTriple(), diags, |
| 139 | "flang LLVM compiler" ); |
| 140 | theDriver.setTargetAndMode(targetandMode); |
| 141 | #ifdef FLANG_RUNTIME_F128_MATH_LIB |
| 142 | theDriver.setFlangF128MathLibrary(FLANG_RUNTIME_F128_MATH_LIB); |
| 143 | #endif |
| 144 | std::unique_ptr<clang::driver::Compilation> c( |
| 145 | theDriver.BuildCompilation(Args: args)); |
| 146 | llvm::SmallVector<std::pair<int, const clang::driver::Command *>, 4> |
| 147 | failingCommands; |
| 148 | |
| 149 | // Set the environment variable, FLANG_COMPILER_OPTIONS_STRING, to contain all |
| 150 | // the compiler options. This is intended for the frontend driver, |
| 151 | // flang -fc1, to enable the implementation of the COMPILER_OPTIONS |
| 152 | // intrinsic. To this end, the frontend driver requires the list of the |
| 153 | // original compiler options, which is not available through other means. |
| 154 | // TODO: This way of passing information between the compiler and frontend |
| 155 | // drivers is discouraged. We should find a better way not involving env |
| 156 | // variables. |
| 157 | std::string compilerOptsGathered; |
| 158 | llvm::raw_string_ostream os(compilerOptsGathered); |
| 159 | for (int i = 0; i < argc; ++i) { |
| 160 | os << argv[i]; |
| 161 | if (i < argc - 1) { |
| 162 | os << ' '; |
| 163 | } |
| 164 | } |
| 165 | #ifdef _WIN32 |
| 166 | _putenv_s("FLANG_COMPILER_OPTIONS_STRING" , compilerOptsGathered.c_str()); |
| 167 | #else |
| 168 | setenv(name: "FLANG_COMPILER_OPTIONS_STRING" , value: compilerOptsGathered.c_str(), replace: 1); |
| 169 | #endif |
| 170 | |
| 171 | // Run the driver |
| 172 | int res = 1; |
| 173 | bool isCrash = false; |
| 174 | res = theDriver.ExecuteCompilation(C&: *c, FailingCommands&: failingCommands); |
| 175 | |
| 176 | for (const auto &p : failingCommands) { |
| 177 | int commandRes = p.first; |
| 178 | const clang::driver::Command *failingCommand = p.second; |
| 179 | if (!res) |
| 180 | res = commandRes; |
| 181 | |
| 182 | // If result status is < 0 (e.g. when sys::ExecuteAndWait returns -1), |
| 183 | // then the driver command signalled an error. On Windows, abort will |
| 184 | // return an exit code of 3. In these cases, generate additional diagnostic |
| 185 | // information if possible. |
| 186 | isCrash = commandRes < 0; |
| 187 | #ifdef _WIN32 |
| 188 | isCrash |= commandRes == 3; |
| 189 | #endif |
| 190 | if (isCrash) { |
| 191 | theDriver.generateCompilationDiagnostics(C&: *c, FailingCommand: *failingCommand); |
| 192 | break; |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | diags.getClient()->finish(); |
| 197 | |
| 198 | // If we have multiple failing commands, we return the result of the first |
| 199 | // failing command. |
| 200 | return res; |
| 201 | } |
| 202 | |