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/Host.h"
30 #include "llvm/Support/InitLLVM.h"
31 #include "llvm/Support/VirtualFileSystem.h"
32 
33 using llvm::StringRef;
34 
35 // main frontend method. Lives inside fc1_main.cpp
36 extern int fc1_main(llvm::ArrayRef<const char *> argv, const char *argv0);
37 
getExecutablePath(const char * argv0)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 *
createAndPopulateDiagOpts(llvm::ArrayRef<const char * > argv)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       /*FlagsToInclude=*/clang::driver::options::FlangOption);
57 
58   (void)Fortran::frontend::parseDiagnosticArgs(*diagOpts, args);
59 
60   return diagOpts;
61 }
62 
executeFC1Tool(llvm::SmallVectorImpl<const char * > & argV)63 static int executeFC1Tool(llvm::SmallVectorImpl<const char *> &argV) {
64   llvm::StringRef tool = argV[1];
65   if (tool == "-fc1")
66     return fc1_main(makeArrayRef(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 
ExpandResponseFiles(llvm::StringSaver & saver,llvm::SmallVectorImpl<const char * > & args)75 static void ExpandResponseFiles(
76     llvm::StringSaver &saver, 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::ExpandResponseFiles(saver, tokenizer, args, /* MarkEOLs=*/false);
80 }
81 
main(int argc,const char ** argv)82 int main(int argc, const char **argv) {
83 
84   // Initialize variables to call the driver
85   llvm::InitLLVM x(argc, argv);
86   llvm::SmallVector<const char *, 256> args(argv, argv + argc);
87 
88   clang::driver::ParsedClangName targetandMode("flang", "--driver-mode=flang");
89   std::string driverPath = getExecutablePath(args[0]);
90 
91   llvm::BumpPtrAllocator a;
92   llvm::StringSaver saver(a);
93   ExpandResponseFiles(saver, args);
94 
95   // Check if flang-new is in the frontend mode
96   auto firstArg = std::find_if(
97       args.begin() + 1, args.end(), [](const char *a) { return a != nullptr; });
98   if (firstArg != args.end()) {
99     if (llvm::StringRef(args[1]).startswith("-cc1")) {
100       llvm::errs() << "error: unknown integrated tool '" << args[1] << "'. "
101                    << "Valid tools include '-fc1'.\n";
102       return 1;
103     }
104     // Call flang-new frontend
105     if (llvm::StringRef(args[1]).startswith("-fc1")) {
106       return executeFC1Tool(args);
107     }
108   }
109 
110   // Not in the frontend mode - continue in the compiler driver mode.
111 
112   // Create DiagnosticsEngine for the compiler driver
113   llvm::IntrusiveRefCntPtr<clang::DiagnosticOptions> diagOpts =
114       createAndPopulateDiagOpts(args);
115   llvm::IntrusiveRefCntPtr<clang::DiagnosticIDs> diagID(
116       new clang::DiagnosticIDs());
117   Fortran::frontend::TextDiagnosticPrinter *diagClient =
118       new Fortran::frontend::TextDiagnosticPrinter(llvm::errs(), &*diagOpts);
119 
120   diagClient->setPrefix(
121       std::string(llvm::sys::path::stem(getExecutablePath(args[0]))));
122 
123   clang::DiagnosticsEngine diags(diagID, &*diagOpts, diagClient);
124 
125   // Prepare the driver
126   clang::driver::Driver theDriver(driverPath,
127       llvm::sys::getDefaultTargetTriple(), diags, "flang LLVM compiler");
128   theDriver.setTargetAndMode(targetandMode);
129   std::unique_ptr<clang::driver::Compilation> c(
130       theDriver.BuildCompilation(args));
131   llvm::SmallVector<std::pair<int, const clang::driver::Command *>, 4>
132       failingCommands;
133 
134   // Run the driver
135   int res = 1;
136   bool isCrash = false;
137   res = theDriver.ExecuteCompilation(*c, failingCommands);
138 
139   for (const auto &p : failingCommands) {
140     int commandRes = p.first;
141     const clang::driver::Command *failingCommand = p.second;
142     if (!res)
143       res = commandRes;
144 
145     // If result status is < 0 (e.g. when sys::ExecuteAndWait returns -1),
146     // then the driver command signalled an error. On Windows, abort will
147     // return an exit code of 3. In these cases, generate additional diagnostic
148     // information if possible.
149     isCrash = commandRes < 0;
150 #ifdef _WIN32
151     isCrash |= commandRes == 3;
152 #endif
153     if (isCrash) {
154       theDriver.generateCompilationDiagnostics(*c, *failingCommand);
155       break;
156     }
157   }
158 
159   diags.getClient()->finish();
160 
161   // If we have multiple failing commands, we return the result of the first
162   // failing command.
163   return res;
164 }
165