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, 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 argv.slice(1), missingArgIndex, missingArgCount, 56 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(llvm::ArrayRef(argV).slice(2), 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(args)) { 81 llvm::errs() << toString(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(argv[0]); 93 std::string driverPath = getExecutablePath(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(args.begin() + 1, args.end(), 101 [](const char *a) { return a != nullptr; }); 102 if (firstArg != args.end()) { 103 if (llvm::StringRef(args[1]).starts_with("-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("-fc1")) { 110 return executeFC1Tool(args); 111 } 112 } 113 114 // Not in the frontend mode - continue in the compiler driver mode. 115 116 // Create DiagnosticsEngine for the compiler driver 117 llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagOpts = 118 createAndPopulateDiagOpts(args); 119 llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID( 120 new clang::DiagnosticIDs()); 121 Fortran::frontend::TextDiagnosticPrinter *diagClient = 122 new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), &*diagOpts); 123 124 diagClient->setPrefix( 125 std::string(llvm::sys::path::stem(getExecutablePath(args[0])))); 126 127 clang::DiagnosticsEngine diags(diagID, &*diagOpts, diagClient); 128 129 // Prepare the driver 130 clang::driver::Driver theDriver(driverPath, 131 llvm::sys::getDefaultTargetTriple(), diags, 132 "flang LLVM compiler"); 133 theDriver.setTargetAndMode(targetandMode); 134 #ifdef FLANG_RUNTIME_F128_MATH_LIB 135 theDriver.setFlangF128MathLibrary(FLANG_RUNTIME_F128_MATH_LIB); 136 #endif 137 std::unique_ptr<clang::driver::Compilation> c( 138 theDriver.BuildCompilation(args)); 139 llvm::SmallVector<std::pair<int, const clang::driver::Command *>, 4> 140 failingCommands; 141 142 // Set the environment variable, FLANG_COMPILER_OPTIONS_STRING, to contain all 143 // the compiler options. This is intended for the frontend driver, 144 // flang -fc1, to enable the implementation of the COMPILER_OPTIONS 145 // intrinsic. To this end, the frontend driver requires the list of the 146 // original compiler options, which is not available through other means. 147 // TODO: This way of passing information between the compiler and frontend 148 // drivers is discouraged. We should find a better way not involving env 149 // variables. 150 std::string compilerOptsGathered; 151 llvm::raw_string_ostream os(compilerOptsGathered); 152 for (int i = 0; i < argc; ++i) { 153 os << argv[i]; 154 if (i < argc - 1) { 155 os << ' '; 156 } 157 } 158 #ifdef _WIN32 159 _putenv_s("FLANG_COMPILER_OPTIONS_STRING", compilerOptsGathered.c_str()); 160 #else 161 setenv("FLANG_COMPILER_OPTIONS_STRING", compilerOptsGathered.c_str(), 1); 162 #endif 163 164 // Run the driver 165 int res = 1; 166 bool isCrash = false; 167 res = theDriver.ExecuteCompilation(*c, failingCommands); 168 169 for (const auto &p : failingCommands) { 170 int commandRes = p.first; 171 const clang::driver::Command *failingCommand = p.second; 172 if (!res) 173 res = commandRes; 174 175 // If result status is < 0 (e.g. when sys::ExecuteAndWait returns -1), 176 // then the driver command signalled an error. On Windows, abort will 177 // return an exit code of 3. In these cases, generate additional diagnostic 178 // information if possible. 179 isCrash = commandRes < 0; 180 #ifdef _WIN32 181 isCrash |= commandRes == 3; 182 #endif 183 if (isCrash) { 184 theDriver.generateCompilationDiagnostics(*c, *failingCommand); 185 break; 186 } 187 } 188 189 diags.getClient()->finish(); 190 191 // If we have multiple failing commands, we return the result of the first 192 // failing command. 193 return res; 194 } 195