xref: /llvm-project/flang/lib/Frontend/CompilerInvocation.cpp (revision 197d9a55f105391f34a0657e6c1d5ef3166dad7d)
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   // Identify the action (i.e. opts.ProgramAction)
88   if (const llvm::opt::Arg *a =
89           args.getLastArg(clang::driver::options::OPT_Action_Group)) {
90     switch (a->getOption().getID()) {
91     default: {
92       llvm_unreachable("Invalid option in group!");
93     }
94     case clang::driver::options::OPT_test_io:
95       opts.programAction_ = InputOutputTest;
96       break;
97     case clang::driver::options::OPT_E:
98       opts.programAction_ = PrintPreprocessedInput;
99       break;
100     case clang::driver::options::OPT_fsyntax_only:
101       opts.programAction_ = ParseSyntaxOnly;
102       break;
103     case clang::driver::options::OPT_emit_obj:
104       opts.programAction_ = EmitObj;
105       break;
106 
107       // TODO:
108       // case calng::driver::options::OPT_emit_llvm:
109       // case clang::driver::options::OPT_emit_llvm_only:
110       // case clang::driver::options::OPT_emit_codegen_only:
111       // case clang::driver::options::OPT_emit_module:
112       // (...)
113     }
114   }
115 
116   opts.outputFile_ = args.getLastArgValue(clang::driver::options::OPT_o);
117   opts.showHelp_ = args.hasArg(clang::driver::options::OPT_help);
118   opts.showVersion_ = args.hasArg(clang::driver::options::OPT_version);
119 
120   // Get the input kind (from the value passed via `-x`)
121   InputKind dashX(Language::Unknown);
122   if (const llvm::opt::Arg *a =
123           args.getLastArg(clang::driver::options::OPT_x)) {
124     llvm::StringRef XValue = a->getValue();
125     // Principal languages.
126     dashX = llvm::StringSwitch<InputKind>(XValue)
127                 .Case("f90", Language::Fortran)
128                 .Default(Language::Unknown);
129 
130     // Some special cases cannot be combined with suffixes.
131     if (dashX.IsUnknown())
132       dashX = llvm::StringSwitch<InputKind>(XValue)
133                   .Case("ir", Language::LLVM_IR)
134                   .Default(Language::Unknown);
135 
136     if (dashX.IsUnknown())
137       diags.Report(clang::diag::err_drv_invalid_value)
138           << a->getAsString(args) << a->getValue();
139   }
140 
141   // Collect the input files and save them in our instance of FrontendOptions.
142   std::vector<std::string> inputs =
143       args.getAllArgValues(clang::driver::options::OPT_INPUT);
144   opts.inputs_.clear();
145   if (inputs.empty())
146     // '-' is the default input if none is given.
147     inputs.push_back("-");
148   for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
149     InputKind ik = dashX;
150     if (ik.IsUnknown()) {
151       ik = FrontendOptions::GetInputKindForExtension(
152           llvm::StringRef(inputs[i]).rsplit('.').second);
153       if (ik.IsUnknown())
154         ik = Language::Unknown;
155       if (i == 0)
156         dashX = ik;
157     }
158 
159     opts.inputs_.emplace_back(std::move(inputs[i]), ik);
160   }
161   return dashX;
162 }
163 
164 /// Parses all preprocessor input arguments and populates the preprocessor
165 /// options accordingly.
166 ///
167 /// \param [in] opts The preprocessor options instance
168 /// \param [out] args The list of input arguments
169 static void parsePreprocessorArgs(
170     Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) {
171   // Add macros from the command line.
172   for (const auto *currentArg : args.filtered(
173            clang::driver::options::OPT_D, clang::driver::options::OPT_U)) {
174     if (currentArg->getOption().matches(clang::driver::options::OPT_D)) {
175       opts.addMacroDef(currentArg->getValue());
176     } else {
177       opts.addMacroUndef(currentArg->getValue());
178     }
179   }
180 
181   // Add the ordered list of -I's.
182   for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I))
183     opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue());
184 }
185 
186 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
187     llvm::ArrayRef<const char *> commandLineArgs,
188     clang::DiagnosticsEngine &diags) {
189 
190   bool success = true;
191 
192   // Parse the arguments
193   const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
194   const unsigned includedFlagsBitmask =
195       clang::driver::options::FC1Option;
196   unsigned missingArgIndex, missingArgCount;
197   llvm::opt::InputArgList args = opts.ParseArgs(
198       commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
199 
200   // Issue errors on unknown arguments
201   for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
202     auto argString = a->getAsString(args);
203     std::string nearest;
204     if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
205       diags.Report(clang::diag::err_drv_unknown_argument) << argString;
206     else
207       diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
208           << argString << nearest;
209     success = false;
210   }
211 
212   // Parse the frontend args
213   ParseFrontendArgs(res.frontendOpts(), args, diags);
214   // Parse the preprocessor args
215   parsePreprocessorArgs(res.preprocessorOpts(), args);
216 
217   return success;
218 }
219 
220 /// Collect the macro definitions provided by the given preprocessor
221 /// options into the parser options.
222 ///
223 /// \param [in] ppOpts The preprocessor options
224 /// \param [out] opts The fortran options
225 static void collectMacroDefinitions(
226     const PreprocessorOptions &ppOpts, Fortran::parser::Options &opts) {
227   for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) {
228     llvm::StringRef macro = ppOpts.macros[i].first;
229     bool isUndef = ppOpts.macros[i].second;
230 
231     std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('=');
232     llvm::StringRef macroName = macroPair.first;
233     llvm::StringRef macroBody = macroPair.second;
234 
235     // For an #undef'd macro, we only care about the name.
236     if (isUndef) {
237       opts.predefinitions.emplace_back(
238           macroName.str(), std::optional<std::string>{});
239       continue;
240     }
241 
242     // For a #define'd macro, figure out the actual definition.
243     if (macroName.size() == macro.size())
244       macroBody = "1";
245     else {
246       // Note: GCC drops anything following an end-of-line character.
247       llvm::StringRef::size_type End = macroBody.find_first_of("\n\r");
248       macroBody = macroBody.substr(0, End);
249     }
250     opts.predefinitions.emplace_back(
251         macroName, std::optional<std::string>(macroBody.str()));
252   }
253 }
254 
255 void CompilerInvocation::SetDefaultFortranOpts() {
256   auto &fortranOptions = fortranOpts();
257 
258   // These defaults are based on the defaults in f18/f18.cpp.
259   std::vector<std::string> searchDirectories{"."s};
260   fortranOptions.searchDirectories = searchDirectories;
261   fortranOptions.isFixedForm = false;
262 
263   // Populate the macro list with version numbers and other predefinitions.
264   // TODO: When expanding this list of standard predefinitions, consider
265   // creating a dedicated API for this. Also at some point we will need to
266   // differentiate between different targets.
267   fortranOptions.predefinitions.emplace_back("__flang__", "1");
268   fortranOptions.predefinitions.emplace_back(
269       "__flang_major__", FLANG_VERSION_MAJOR_STRING);
270   fortranOptions.predefinitions.emplace_back(
271       "__flang_minor__", FLANG_VERSION_MINOR_STRING);
272   fortranOptions.predefinitions.emplace_back(
273       "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING);
274 }
275 
276 void CompilerInvocation::setFortranOpts() {
277   auto &fortranOptions = fortranOpts();
278   const auto &preprocessorOptions = preprocessorOpts();
279 
280   collectMacroDefinitions(preprocessorOptions, fortranOptions);
281 
282   fortranOptions.searchDirectories.insert(
283       fortranOptions.searchDirectories.end(),
284       preprocessorOptions.searchDirectoriesFromDashI.begin(),
285       preprocessorOptions.searchDirectoriesFromDashI.end());
286 }
287