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 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
225     llvm::ArrayRef<const char *> commandLineArgs,
226     clang::DiagnosticsEngine &diags) {
227 
228   bool success = true;
229 
230   // Parse the arguments
231   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
232   const unsigned includedFlagsBitmask = clang::driver::options::FC1Option;
233   unsigned missingArgIndex, missingArgCount;
234   llvm::opt::InputArgList args = opts.ParseArgs(
235       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
236 
237   // Issue errors on unknown arguments
238   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
239     auto argString = a->getAsString(args);
240     std::string nearest;
241     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
242       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
243     else
244       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
245           << argString << nearest;
246     success = false;
247   }
248 
249   // Parse the frontend args
250   ParseFrontendArgs(res.frontendOpts(), args, diags);
251   // Parse the preprocessor args
252   parsePreprocessorArgs(res.preprocessorOpts(), args);
253 
254   return success;
255 }
256 
257 /// Collect the macro definitions provided by the given preprocessor
258 /// options into the parser options.
259 ///
260 /// \param [in] ppOpts The preprocessor options
261 /// \param [out] opts The fortran options
262 static void collectMacroDefinitions(
263     const PreprocessorOptions &ppOpts, Fortran::parser::Options &opts) {
264   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
265     llvm::StringRef macro = ppOpts.macros[i].first;
266     bool isUndef = ppOpts.macros[i].second;
267 
268     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
269     llvm::StringRef macroName = macroPair.first;
270     llvm::StringRef macroBody = macroPair.second;
271 
272     // For an #undef'd macro, we only care about the name.
273     if (isUndef) {
274       opts.predefinitions.emplace_back(
275           macroName.str(), std::optional<std::string>{});
276       continue;
277     }
278 
279     // For a #define'd macro, figure out the actual definition.
280     if (macroName.size() == macro.size())
281       macroBody = "1";
282     else {
283       // Note: GCC drops anything following an end-of-line character.
284       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
285       macroBody = macroBody.substr(0, End);
286     }
287     opts.predefinitions.emplace_back(
288         macroName, std::optional<std::string>(macroBody.str()));
289   }
290 }
291 
292 void CompilerInvocation::SetDefaultFortranOpts() {
293   auto &fortranOptions = fortranOpts();
294 
295   // These defaults are based on the defaults in f18/f18.cpp.
296   std::vector<std::string> searchDirectories{"."s};
297   fortranOptions.searchDirectories = searchDirectories;
298   fortranOptions.isFixedForm = false;
299 
300   // Populate the macro list with version numbers and other predefinitions.
301   // TODO: When expanding this list of standard predefinitions, consider
302   // creating a dedicated API for this. Also at some point we will need to
303   // differentiate between different targets.
304   fortranOptions.predefinitions.emplace_back("__flang__", "1");
305   fortranOptions.predefinitions.emplace_back(
306       "__flang_major__", FLANG_VERSION_MAJOR_STRING);
307   fortranOptions.predefinitions.emplace_back(
308       "__flang_minor__", FLANG_VERSION_MINOR_STRING);
309   fortranOptions.predefinitions.emplace_back(
310       "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING);
311 }
312 
313 void CompilerInvocation::setFortranOpts() {
314   auto &fortranOptions = fortranOpts();
315   const auto &frontendOptions = frontendOpts();
316   const auto &preprocessorOptions = preprocessorOpts();
317 
318   if (frontendOptions.fortranForm_ != FortranForm::Unknown) {
319     fortranOptions.isFixedForm =
320         frontendOptions.fortranForm_ == FortranForm::FixedForm;
321   }
322   fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns_;
323 
324   collectMacroDefinitions(preprocessorOptions, fortranOptions);
325 
326   fortranOptions.searchDirectories.insert(
327       fortranOptions.searchDirectories.end(),
328       preprocessorOptions.searchDirectoriesFromDashI.begin(),
329       preprocessorOptions.searchDirectoriesFromDashI.end());
330 }
331