llvm-project/flang/lib/Frontend/CompilerInvocation.cpp
Caroline Concatto 4c5906cffd [Flang][Driver] Add infrastructure for basic frontend actions and file I/O
This patch introduces the dependencies required to read and manage input files
provided by the command line option. It also adds the infrastructure to create
and write to output files. The output is sent to either stdout or a file
(specified with the `-o` flag).

Separately, in order to be able to test the code for file I/O, it adds
infrastructure to create frontend actions. As a basic testable example, it adds
the `InputOutputTest` FrontendAction. The sole purpose of this action is to
read a file from the command line and print it either to stdout or the output
file.  This action is run by using the `-test-io` flag also introduced in this
patch (available for `flang-new` and `flang-new -fc1`). With this patch:
```
flang-new -test-io input-file.f90
```
will read input-file.f90 and print it in the output file.

The `InputOutputTest` frontend action has been introduced primarily to
facilitate testing. It is hidden from users (i.e. it's only displayed with
`--help-hidden`). Currently Clang doesn’t have an equivalent action.

`-test-io` is used to trigger the InputOutputTest action in the Flang frontend
driver. This patch makes sure that “flang-new” forwards it to “flang-new -fc1"
by creating a preprocessor job. However, in Flang.cpp, `-test-io` is passed to
“flang-new -fc1” without `-E`. This way we make sure that the preprocessor is
_not_ run in the frontend driver. This is the desired behaviour: `-test-io`
should only read the input file and print it to the output stream.

co-authored-by: Andrzej Warzynski <andrzej.warzynski@arm.com>

Differential Revision: https://reviews.llvm.org/D87989
2020-10-24 14:58:32 +01:00

183 lines
6.7 KiB
C++

//===- CompilerInvocation.cpp ---------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "flang/Frontend/CompilerInvocation.h"
#include "clang/Basic/AllDiagnostics.h"
#include "clang/Basic/DiagnosticDriver.h"
#include "clang/Basic/DiagnosticOptions.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Option/Arg.h"
#include "llvm/Option/ArgList.h"
#include "llvm/Option/OptTable.h"
#include "llvm/Support/Process.h"
#include "llvm/Support/raw_ostream.h"
using namespace Fortran::frontend;
//===----------------------------------------------------------------------===//
// Initialization.
//===----------------------------------------------------------------------===//
CompilerInvocationBase::CompilerInvocationBase()
: diagnosticOpts_(new clang::DiagnosticOptions()) {}
CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x)
: diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())) {}
CompilerInvocationBase::~CompilerInvocationBase() = default;
//===----------------------------------------------------------------------===//
// Deserialization (from args)
//===----------------------------------------------------------------------===//
static bool parseShowColorsArgs(
const llvm::opt::ArgList &args, bool defaultColor) {
// Color diagnostics default to auto ("on" if terminal supports) in the driver
// but default to off in cc1, needing an explicit OPT_fdiagnostics_color.
// Support both clang's -f[no-]color-diagnostics and gcc's
// -f[no-]diagnostics-colors[=never|always|auto].
enum {
Colors_On,
Colors_Off,
Colors_Auto
} ShowColors = defaultColor ? Colors_Auto : Colors_Off;
for (auto *a : args) {
const llvm::opt::Option &O = a->getOption();
if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) ||
O.matches(clang::driver::options::OPT_fdiagnostics_color)) {
ShowColors = Colors_On;
} else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) ||
O.matches(clang::driver::options::OPT_fno_diagnostics_color)) {
ShowColors = Colors_Off;
} else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) {
llvm::StringRef value(a->getValue());
if (value == "always")
ShowColors = Colors_On;
else if (value == "never")
ShowColors = Colors_Off;
else if (value == "auto")
ShowColors = Colors_Auto;
}
}
return ShowColors == Colors_On ||
(ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors());
}
bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts,
llvm::opt::ArgList &args, bool defaultDiagColor) {
opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor);
return true;
}
static InputKind ParseFrontendArgs(FrontendOptions &opts,
llvm::opt::ArgList &args, clang::DiagnosticsEngine &diags) {
// Identify the action (i.e. opts.ProgramAction)
if (const llvm::opt::Arg *a =
args.getLastArg(clang::driver::options::OPT_Action_Group)) {
switch (a->getOption().getID()) {
default: {
llvm_unreachable("Invalid option in group!");
}
case clang::driver::options::OPT_test_io:
opts.programAction_ = InputOutputTest;
break;
// TODO:
// case clang::driver::options::OPT_E:
// case clang::driver::options::OPT_emit_obj:
// case calng::driver::options::OPT_emit_llvm:
// case clang::driver::options::OPT_emit_llvm_only:
// case clang::driver::options::OPT_emit_codegen_only:
// case clang::driver::options::OPT_emit_module:
// (...)
}
}
opts.outputFile_ = args.getLastArgValue(clang::driver::options::OPT_o);
opts.showHelp_ = args.hasArg(clang::driver::options::OPT_help);
opts.showVersion_ = args.hasArg(clang::driver::options::OPT_version);
// Get the input kind (from the value passed via `-x`)
InputKind dashX(Language::Unknown);
if (const llvm::opt::Arg *a =
args.getLastArg(clang::driver::options::OPT_x)) {
llvm::StringRef XValue = a->getValue();
// Principal languages.
dashX = llvm::StringSwitch<InputKind>(XValue)
.Case("f90", Language::Fortran)
.Default(Language::Unknown);
// Some special cases cannot be combined with suffixes.
if (dashX.IsUnknown())
dashX = llvm::StringSwitch<InputKind>(XValue)
.Case("ir", Language::LLVM_IR)
.Default(Language::Unknown);
if (dashX.IsUnknown())
diags.Report(clang::diag::err_drv_invalid_value)
<< a->getAsString(args) << a->getValue();
}
// Collect the input files and save them in our instance of FrontendOptions.
std::vector<std::string> inputs =
args.getAllArgValues(clang::driver::options::OPT_INPUT);
opts.inputs_.clear();
if (inputs.empty())
// '-' is the default input if none is given.
inputs.push_back("-");
for (unsigned i = 0, e = inputs.size(); i != e; ++i) {
InputKind ik = dashX;
if (ik.IsUnknown()) {
ik = FrontendOptions::GetInputKindForExtension(
llvm::StringRef(inputs[i]).rsplit('.').second);
if (ik.IsUnknown())
ik = Language::Unknown;
if (i == 0)
dashX = ik;
}
opts.inputs_.emplace_back(std::move(inputs[i]), ik);
}
return dashX;
}
bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res,
llvm::ArrayRef<const char *> commandLineArgs,
clang::DiagnosticsEngine &diags) {
bool success = true;
// Parse the arguments
const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable();
const unsigned includedFlagsBitmask =
clang::driver::options::FC1Option;
unsigned missingArgIndex, missingArgCount;
llvm::opt::InputArgList args = opts.ParseArgs(
commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask);
// Issue errors on unknown arguments
for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) {
auto argString = a->getAsString(args);
std::string nearest;
if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1)
diags.Report(clang::diag::err_drv_unknown_argument) << argString;
else
diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion)
<< argString << nearest;
success = false;
}
// Parse the frontend args
ParseFrontendArgs(res.GetFrontendOpts(), args, diags);
return success;
}