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 "flang/Version.inc"
12 #include "clang/Basic/AllDiagnostics.h"
13 #include "clang/Basic/DiagnosticDriver.h"
14 #include "clang/Basic/DiagnosticOptions.h"
15 #include "clang/Driver/DriverDiagnostic.h"
16 #include "clang/Driver/Options.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/Option/Arg.h"
20 #include "llvm/Option/ArgList.h"
21 #include "llvm/Option/OptTable.h"
22 #include "llvm/Support/Process.h"
23 #include "llvm/Support/raw_ostream.h"
24 
25 using namespace Fortran::frontend;
26 
27 //===----------------------------------------------------------------------===//
28 // Initialization.
29 //===----------------------------------------------------------------------===//
30 CompilerInvocationBase::CompilerInvocationBase()
31     : diagnosticOpts_(new clang::DiagnosticOptions()),
32       preprocessorOpts_(new PreprocessorOptions()) {}
33 
34 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
35     : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())),
36       preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {}
37 
38 CompilerInvocationBase::~CompilerInvocationBase() = default;
39 
40 //===----------------------------------------------------------------------===//
41 // Deserialization (from args)
42 //===----------------------------------------------------------------------===//
43 static bool parseShowColorsArgs(
44     const llvm::opt::ArgList &args, bool defaultColor) {
45   // Color diagnostics default to auto ("on" if terminal supports) in the driver
46   // but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
47   // Support both clang's -f[no-]color-diagnostics and gcc's
48   // -f[no-]diagnostics-colors[=never|always|auto].
49   enum {
50     Colors_On,
51     Colors_Off,
52     Colors_Auto
53   } ShowColors = defaultColor ? Colors_Auto : Colors_Off;
54 
55   for (auto *a : args) {
56     const llvm::opt::Option &O = a->getOption();
57     if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) ||
58         O.matches(clang::driver::options::OPT_fdiagnostics_color)) {
59       ShowColors = Colors_On;
60     } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) ||
61         O.matches(clang::driver::options::OPT_fno_diagnostics_color)) {
62       ShowColors = Colors_Off;
63     } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
64       llvm::StringRef value(a->getValue());
65       if (value == "always")
66         ShowColors = Colors_On;
67       else if (value == "never")
68         ShowColors = Colors_Off;
69       else if (value == "auto")
70         ShowColors = Colors_Auto;
71     }
72   }
73 
74   return ShowColors == Colors_On ||
75       (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors());
76 }
77 
78 bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts,
79     llvm::opt::ArgList &args, bool defaultDiagColor) {
80   opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor);
81 
82   return true;
83 }
84 
85 static InputKind ParseFrontendArgs(FrontendOptions &opts,
86     llvm::opt::ArgList &args, clang::DiagnosticsEngine &diags) {
87 
88   // By default the frontend driver creates a ParseSyntaxOnly action.
89   opts.programAction_ = ParseSyntaxOnly;
90 
91   // Identify the action (i.e. opts.ProgramAction)
92   if (const llvm::opt::Arg *a =
93           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
94     switch (a->getOption().getID()) {
95     default: {
96       llvm_unreachable("Invalid option in group!");
97     }
98     case clang::driver::options::OPT_test_io:
99       opts.programAction_ = InputOutputTest;
100       break;
101     case clang::driver::options::OPT_E:
102       opts.programAction_ = PrintPreprocessedInput;
103       break;
104     case clang::driver::options::OPT_fsyntax_only:
105       opts.programAction_ = ParseSyntaxOnly;
106       break;
107     case clang::driver::options::OPT_emit_obj:
108       opts.programAction_ = EmitObj;
109       break;
110 
111       // TODO:
112       // case calng::driver::options::OPT_emit_llvm:
113       // case clang::driver::options::OPT_emit_llvm_only:
114       // case clang::driver::options::OPT_emit_codegen_only:
115       // case clang::driver::options::OPT_emit_module:
116       // (...)
117     }
118   }
119 
120   opts.outputFile_ = args.getLastArgValue(clang::driver::options::OPT_o);
121   opts.showHelp_ = args.hasArg(clang::driver::options::OPT_help);
122   opts.showVersion_ = args.hasArg(clang::driver::options::OPT_version);
123 
124   // Get the input kind (from the value passed via `-x`)
125   InputKind dashX(Language::Unknown);
126   if (const llvm::opt::Arg *a =
127           args.getLastArg(clang::driver::options::OPT_x)) {
128     llvm::StringRef XValue = a->getValue();
129     // Principal languages.
130     dashX = llvm::StringSwitch<InputKind>(XValue)
131                 .Case("f90", Language::Fortran)
132                 .Default(Language::Unknown);
133 
134     // Some special cases cannot be combined with suffixes.
135     if (dashX.IsUnknown())
136       dashX = llvm::StringSwitch<InputKind>(XValue)
137                   .Case("ir", Language::LLVM_IR)
138                   .Default(Language::Unknown);
139 
140     if (dashX.IsUnknown())
141       diags.Report(clang::diag::err_drv_invalid_value)
142           << a->getAsString(args) << a->getValue();
143   }
144 
145   // Collect the input files and save them in our instance of FrontendOptions.
146   std::vector<std::string> inputs =
147       args.getAllArgValues(clang::driver::options::OPT_INPUT);
148   opts.inputs_.clear();
149   if (inputs.empty())
150     // '-' is the default input if none is given.
151     inputs.push_back("-");
152   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
153     InputKind ik = dashX;
154     if (ik.IsUnknown()) {
155       ik = FrontendOptions::GetInputKindForExtension(
156           llvm::StringRef(inputs[i]).rsplit('.').second);
157       if (ik.IsUnknown())
158         ik = Language::Unknown;
159       if (i == 0)
160         dashX = ik;
161     }
162 
163     opts.inputs_.emplace_back(std::move(inputs[i]), ik);
164   }
165 
166   // Set fortranForm_ based on options -ffree-form and -ffixed-form.
167   if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form,
168           clang::driver::options::OPT_ffree_form)) {
169     opts.fortranForm_ =
170         arg->getOption().matches(clang::driver::options::OPT_ffixed_form)
171         ? FortranForm::FixedForm
172         : FortranForm::FreeForm;
173   }
174 
175   // Set fixedFormColumns_ based on -ffixed-line-length=<value>
176   if (const auto *arg =
177           args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) {
178     llvm::StringRef argValue = llvm::StringRef(arg->getValue());
179     std::int64_t columns = -1;
180     if (argValue == "none") {
181       columns = 0;
182     } else if (argValue.getAsInteger(/*Radix=*/10, columns)) {
183       columns = -1;
184     }
185     if (columns < 0) {
186       diags.Report(clang::diag::err_drv_invalid_value_with_suggestion)
187           << arg->getOption().getName() << arg->getValue()
188           << "value must be 'none' or a non-negative integer";
189     } else if (columns == 0) {
190       opts.fixedFormColumns_ = 1000000;
191     } else if (columns < 7) {
192       diags.Report(clang::diag::err_drv_invalid_value_with_suggestion)
193           << arg->getOption().getName() << arg->getValue()
194           << "value must be at least seven";
195     } else {
196       opts.fixedFormColumns_ = columns;
197     }
198   }
199   return dashX;
200 }
201 
202 /// Parses all preprocessor input arguments and populates the preprocessor
203 /// options accordingly.
204 ///
205 /// \param [in] opts The preprocessor options instance
206 /// \param [out] args The list of input arguments
207 static void parsePreprocessorArgs(
208     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
209   // Add macros from the command line.
210   for (const auto *currentArg : args.filtered(
211            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
212     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
213       opts.addMacroDef(currentArg->getValue());
214     } else {
215       opts.addMacroUndef(currentArg->getValue());
216     }
217   }
218 
219   // Add the ordered list of -I's.
220   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
221     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
222 }
223 
224 /// Parses all semantic related arguments and populates the variables
225 /// options accordingly.
226 static void parseSemaArgs(std::string &moduleDir, llvm::opt::ArgList &args,
227     clang::DiagnosticsEngine &diags) {
228 
229   auto moduleDirList =
230       args.getAllArgValues(clang::driver::options::OPT_module_dir);
231   // User can only specify -J/-module-dir once
232   // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html
233   if (moduleDirList.size() > 1) {
234     const unsigned diagID =
235         diags.getCustomDiagID(clang::DiagnosticsEngine::Error,
236             "Only one '-module-dir/-J' option allowed");
237     diags.Report(diagID);
238   }
239   if (moduleDirList.size() == 1)
240     moduleDir = moduleDirList[0];
241 }
242 
243 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
244     llvm::ArrayRef<const char *> commandLineArgs,
245     clang::DiagnosticsEngine &diags) {
246 
247   bool success = true;
248 
249   // Parse the arguments
250   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
251   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
252   unsigned missingArgIndex, missingArgCount;
253   llvm::opt::InputArgList args = opts.ParseArgs(
254       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
255 
256   // Issue errors on unknown arguments
257   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
258     auto argString = a->getAsString(args);
259     std::string nearest;
260     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
261       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
262     else
263       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
264           << argString << nearest;
265     success = false;
266   }
267 
268   // Parse the frontend args
269   ParseFrontendArgs(res.frontendOpts(), args, diags);
270   // Parse the preprocessor args
271   parsePreprocessorArgs(res.preprocessorOpts(), args);
272   // Parse semantic args
273   parseSemaArgs(res.moduleDir(), args, diags);
274 
275   return success;
276 }
277 
278 /// Collect the macro definitions provided by the given preprocessor
279 /// options into the parser options.
280 ///
281 /// \param [in] ppOpts The preprocessor options
282 /// \param [out] opts The fortran options
283 static void collectMacroDefinitions(
284     const PreprocessorOptions &ppOpts, Fortran::parser::Options &opts) {
285   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
286     llvm::StringRef macro = ppOpts.macros[i].first;
287     bool isUndef = ppOpts.macros[i].second;
288 
289     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
290     llvm::StringRef macroName = macroPair.first;
291     llvm::StringRef macroBody = macroPair.second;
292 
293     // For an #undef'd macro, we only care about the name.
294     if (isUndef) {
295       opts.predefinitions.emplace_back(
296           macroName.str(), std::optional<std::string>{});
297       continue;
298     }
299 
300     // For a #define'd macro, figure out the actual definition.
301     if (macroName.size() == macro.size())
302       macroBody = "1";
303     else {
304       // Note: GCC drops anything following an end-of-line character.
305       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
306       macroBody = macroBody.substr(0, End);
307     }
308     opts.predefinitions.emplace_back(
309         macroName, std::optional<std::string>(macroBody.str()));
310   }
311 }
312 
313 void CompilerInvocation::SetDefaultFortranOpts() {
314   auto &fortranOptions = fortranOpts();
315 
316   // These defaults are based on the defaults in f18/f18.cpp.
317   std::vector<std::string> searchDirectories{"."s};
318   fortranOptions.searchDirectories = searchDirectories;
319   fortranOptions.isFixedForm = false;
320 
321   // Populate the macro list with version numbers and other predefinitions.
322   // TODO: When expanding this list of standard predefinitions, consider
323   // creating a dedicated API for this. Also at some point we will need to
324   // differentiate between different targets.
325   fortranOptions.predefinitions.emplace_back("__flang__", "1");
326   fortranOptions.predefinitions.emplace_back(
327       "__flang_major__", FLANG_VERSION_MAJOR_STRING);
328   fortranOptions.predefinitions.emplace_back(
329       "__flang_minor__", FLANG_VERSION_MINOR_STRING);
330   fortranOptions.predefinitions.emplace_back(
331       "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING);
332 }
333 
334 void CompilerInvocation::setFortranOpts() {
335   auto &fortranOptions = fortranOpts();
336   const auto &frontendOptions = frontendOpts();
337   const auto &preprocessorOptions = preprocessorOpts();
338   auto &moduleDirJ = moduleDir();
339 
340   if (frontendOptions.fortranForm_ != FortranForm::Unknown) {
341     fortranOptions.isFixedForm =
342         frontendOptions.fortranForm_ == FortranForm::FixedForm;
343   }
344   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns_;
345 
346   collectMacroDefinitions(preprocessorOptions, fortranOptions);
347 
348   fortranOptions.searchDirectories.insert(
349       fortranOptions.searchDirectories.end(),
350       preprocessorOptions.searchDirectoriesFromDashI.begin(),
351       preprocessorOptions.searchDirectoriesFromDashI.end());
352 
353   // Add the directory supplied through -J/-module-dir to the list of search
354   // directories
355   if (moduleDirJ.compare(".") != 0)
356     fortranOptions.searchDirectories.emplace_back(moduleDirJ);
357 }
358 
359 void CompilerInvocation::setSemanticsOpts(
360     Fortran::semantics::SemanticsContext &semaCtxt) {
361   auto &fortranOptions = fortranOpts();
362   auto &moduleDirJ = moduleDir();
363   semaCtxt.set_moduleDirectory(moduleDirJ)
364       .set_searchDirectories(fortranOptions.searchDirectories);
365   return;
366 }
367