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