1 //===- CompilerInvocation.cpp ---------------------------------------------===//
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 #include "flang/Frontend/CompilerInvocation.h"
10 #include "flang/Frontend/PreprocessorOptions.h"
11 #include "clang/Basic/AllDiagnostics.h"
12 #include "clang/Basic/DiagnosticDriver.h"
13 #include "clang/Basic/DiagnosticOptions.h"
14 #include "clang/Driver/DriverDiagnostic.h"
15 #include "clang/Driver/Options.h"
16 #include "llvm/ADT/StringRef.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/Option/Arg.h"
19 #include "llvm/Option/ArgList.h"
20 #include "llvm/Option/OptTable.h"
21 #include "llvm/Support/Process.h"
22 #include "llvm/Support/raw_ostream.h"
23 
24 using namespace Fortran::frontend;
25 
26 //===----------------------------------------------------------------------===//
27 // Initialization.
28 //===----------------------------------------------------------------------===//
29 CompilerInvocationBase::CompilerInvocationBase()
30     : diagnosticOpts_(new clang::DiagnosticOptions()),
31       preprocessorOpts_(new PreprocessorOptions()) {}
32 
33 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
34     : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())),
35       preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {}
36 
37 CompilerInvocationBase::~CompilerInvocationBase() = default;
38 
39 //===----------------------------------------------------------------------===//
40 // Deserialization (from args)
41 //===----------------------------------------------------------------------===//
42 static bool parseShowColorsArgs(
43     const llvm::opt::ArgList &args, bool defaultColor) {
44   // Color diagnostics default to auto ("on" if terminal supports) in the driver
45   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
46   // Support both clang's -f[no-]color-diagnostics and gcc's
47   // -f[no-]diagnostics-colors[=never|always|auto].
48   enum {
49     Colors_On,
50     Colors_Off,
51     Colors_Auto
52   } ShowColors = defaultColor ? Colors_Auto : Colors_Off;
53 
54   for (auto *a : args) {
55     const llvm::opt::Option &O = a->getOption();
56     if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) ||
57         O.matches(clang::driver::options::OPT_fdiagnostics_color)) {
58       ShowColors = Colors_On;
59     } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) ||
60         O.matches(clang::driver::options::OPT_fno_diagnostics_color)) {
61       ShowColors = Colors_Off;
62     } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
63       llvm::StringRef value(a->getValue());
64       if (value == "always")
65         ShowColors = Colors_On;
66       else if (value == "never")
67         ShowColors = Colors_Off;
68       else if (value == "auto")
69         ShowColors = Colors_Auto;
70     }
71   }
72 
73   return ShowColors == Colors_On ||
74       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors());
75 }
76 
77 bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts,
78     llvm::opt::ArgList &args, bool defaultDiagColor) {
79   opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor);
80 
81   return true;
82 }
83 
84 static InputKind ParseFrontendArgs(FrontendOptions &opts,
85     llvm::opt::ArgList &args, clang::DiagnosticsEngine &diags) {
86   // Identify the action (i.e. opts.ProgramAction)
87   if (const llvm::opt::Arg *a =
88           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
89     switch (a->getOption().getID()) {
90     default: {
91       llvm_unreachable("Invalid option in group!");
92     }
93     case clang::driver::options::OPT_test_io:
94       opts.programAction_ = InputOutputTest;
95       break;
96     case clang::driver::options::OPT_E:
97       opts.programAction_ = PrintPreprocessedInput;
98       break;
99     case clang::driver::options::OPT_fsyntax_only:
100       opts.programAction_ = ParseSyntaxOnly;
101       break;
102 
103       // TODO:
104       // case clang::driver::options::OPT_emit_obj:
105       // case calng::driver::options::OPT_emit_llvm:
106       // case clang::driver::options::OPT_emit_llvm_only:
107       // case clang::driver::options::OPT_emit_codegen_only:
108       // case clang::driver::options::OPT_emit_module:
109       // (...)
110     }
111   }
112 
113   opts.outputFile_ = args.getLastArgValue(clang::driver::options::OPT_o);
114   opts.showHelp_ = args.hasArg(clang::driver::options::OPT_help);
115   opts.showVersion_ = args.hasArg(clang::driver::options::OPT_version);
116 
117   // Get the input kind (from the value passed via `-x`)
118   InputKind dashX(Language::Unknown);
119   if (const llvm::opt::Arg *a =
120           args.getLastArg(clang::driver::options::OPT_x)) {
121     llvm::StringRef XValue = a->getValue();
122     // Principal languages.
123     dashX = llvm::StringSwitch<InputKind>(XValue)
124                 .Case("f90", Language::Fortran)
125                 .Default(Language::Unknown);
126 
127     // Some special cases cannot be combined with suffixes.
128     if (dashX.IsUnknown())
129       dashX = llvm::StringSwitch<InputKind>(XValue)
130                   .Case("ir", Language::LLVM_IR)
131                   .Default(Language::Unknown);
132 
133     if (dashX.IsUnknown())
134       diags.Report(clang::diag::err_drv_invalid_value)
135           << a->getAsString(args) << a->getValue();
136   }
137 
138   // Collect the input files and save them in our instance of FrontendOptions.
139   std::vector<std::string> inputs =
140       args.getAllArgValues(clang::driver::options::OPT_INPUT);
141   opts.inputs_.clear();
142   if (inputs.empty())
143     // '-' is the default input if none is given.
144     inputs.push_back("-");
145   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
146     InputKind ik = dashX;
147     if (ik.IsUnknown()) {
148       ik = FrontendOptions::GetInputKindForExtension(
149           llvm::StringRef(inputs[i]).rsplit('.').second);
150       if (ik.IsUnknown())
151         ik = Language::Unknown;
152       if (i == 0)
153         dashX = ik;
154     }
155 
156     opts.inputs_.emplace_back(std::move(inputs[i]), ik);
157   }
158   return dashX;
159 }
160 
161 /// Parses all preprocessor input arguments and populates the preprocessor
162 /// options accordingly.
163 ///
164 /// \param [in] opts The preprocessor options instance
165 /// \param [out] args The list of input arguments
166 static void parsePreprocessorArgs(
167     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
168   // Add macros from the command line.
169   for (const auto *currentArg : args.filtered(
170            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
171     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
172       opts.addMacroDef(currentArg->getValue());
173     } else {
174       opts.addMacroUndef(currentArg->getValue());
175     }
176   }
177 }
178 
179 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
180     llvm::ArrayRef<const char *> commandLineArgs,
181     clang::DiagnosticsEngine &diags) {
182 
183   bool success = true;
184 
185   // Parse the arguments
186   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
187   const unsigned includedFlagsBitmask =
188       clang::driver::options::FC1Option;
189   unsigned missingArgIndex, missingArgCount;
190   llvm::opt::InputArgList args = opts.ParseArgs(
191       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
192 
193   // Issue errors on unknown arguments
194   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
195     auto argString = a->getAsString(args);
196     std::string nearest;
197     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
198       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
199     else
200       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
201           << argString << nearest;
202     success = false;
203   }
204 
205   // Parse the frontend args
206   ParseFrontendArgs(res.frontendOpts(), args, diags);
207   // Parse the preprocessor args
208   parsePreprocessorArgs(res.preprocessorOpts(), args);
209 
210   return success;
211 }
212 
213 /// Collect the macro definitions provided by the given preprocessor
214 /// options into the parser options.
215 ///
216 /// \param [in] ppOpts The preprocessor options
217 /// \param [out] opts The fortran options
218 static void collectMacroDefinitions(
219     const PreprocessorOptions &ppOpts, Fortran::parser::Options &opts) {
220   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
221     llvm::StringRef macro = ppOpts.macros[i].first;
222     bool isUndef = ppOpts.macros[i].second;
223 
224     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
225     llvm::StringRef macroName = macroPair.first;
226     llvm::StringRef macroBody = macroPair.second;
227 
228     // For an #undef'd macro, we only care about the name.
229     if (isUndef) {
230       opts.predefinitions.emplace_back(
231           macroName.str(), std::optional<std::string>{});
232       continue;
233     }
234 
235     // For a #define'd macro, figure out the actual definition.
236     if (macroName.size() == macro.size())
237       macroBody = "1";
238     else {
239       // Note: GCC drops anything following an end-of-line character.
240       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
241       macroBody = macroBody.substr(0, End);
242     }
243     opts.predefinitions.emplace_back(
244         macroName, std::optional<std::string>(macroBody.str()));
245   }
246 }
247 
248 void CompilerInvocation::SetDefaultFortranOpts() {
249   auto &fortranOptions = fortranOpts();
250 
251   // These defaults are based on the defaults in f18/f18.cpp.
252   std::vector<std::string> searchDirectories{"."s};
253   fortranOptions.searchDirectories = searchDirectories;
254   fortranOptions.isFixedForm = false;
255 }
256 
257 void CompilerInvocation::setFortranOpts() {
258   auto &fortranOptions = fortranOpts();
259   const auto &preprocessorOptions = preprocessorOpts();
260 
261   collectMacroDefinitions(preprocessorOptions, fortranOptions);
262 }
263