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/Frontend/TargetOptions.h" 13 #include "flang/Semantics/semantics.h" 14 #include "flang/Version.inc" 15 #include "clang/Basic/AllDiagnostics.h" 16 #include "clang/Basic/DiagnosticDriver.h" 17 #include "clang/Basic/DiagnosticOptions.h" 18 #include "clang/Driver/DriverDiagnostic.h" 19 #include "clang/Driver/Options.h" 20 #include "llvm/ADT/StringRef.h" 21 #include "llvm/ADT/StringSwitch.h" 22 #include "llvm/Option/Arg.h" 23 #include "llvm/Option/ArgList.h" 24 #include "llvm/Option/OptTable.h" 25 #include "llvm/Support/FileSystem.h" 26 #include "llvm/Support/FileUtilities.h" 27 #include "llvm/Support/Path.h" 28 #include "llvm/Support/Process.h" 29 #include "llvm/Support/raw_ostream.h" 30 #include <memory> 31 32 using namespace Fortran::frontend; 33 34 //===----------------------------------------------------------------------===// 35 // Initialization. 36 //===----------------------------------------------------------------------===// 37 CompilerInvocationBase::CompilerInvocationBase() 38 : diagnosticOpts_(new clang::DiagnosticOptions()), 39 preprocessorOpts_(new PreprocessorOptions()) {} 40 41 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 42 : diagnosticOpts_(new clang::DiagnosticOptions(x.GetDiagnosticOpts())), 43 preprocessorOpts_(new PreprocessorOptions(x.preprocessorOpts())) {} 44 45 CompilerInvocationBase::~CompilerInvocationBase() = default; 46 47 //===----------------------------------------------------------------------===// 48 // Deserialization (from args) 49 //===----------------------------------------------------------------------===// 50 static bool parseShowColorsArgs( 51 const llvm::opt::ArgList &args, bool defaultColor) { 52 // Color diagnostics default to auto ("on" if terminal supports) in the driver 53 // but default to off in cc1, needing an explicit OPT_fdiagnostics_color. 54 // Support both clang's -f[no-]color-diagnostics and gcc's 55 // -f[no-]diagnostics-colors[=never|always|auto]. 56 enum { 57 Colors_On, 58 Colors_Off, 59 Colors_Auto 60 } ShowColors = defaultColor ? Colors_Auto : Colors_Off; 61 62 for (auto *a : args) { 63 const llvm::opt::Option &O = a->getOption(); 64 if (O.matches(clang::driver::options::OPT_fcolor_diagnostics) || 65 O.matches(clang::driver::options::OPT_fdiagnostics_color)) { 66 ShowColors = Colors_On; 67 } else if (O.matches(clang::driver::options::OPT_fno_color_diagnostics) || 68 O.matches(clang::driver::options::OPT_fno_diagnostics_color)) { 69 ShowColors = Colors_Off; 70 } else if (O.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 71 llvm::StringRef value(a->getValue()); 72 if (value == "always") 73 ShowColors = Colors_On; 74 else if (value == "never") 75 ShowColors = Colors_Off; 76 else if (value == "auto") 77 ShowColors = Colors_Auto; 78 } 79 } 80 81 return ShowColors == Colors_On || 82 (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()); 83 } 84 85 bool Fortran::frontend::ParseDiagnosticArgs(clang::DiagnosticOptions &opts, 86 llvm::opt::ArgList &args, bool defaultDiagColor) { 87 opts.ShowColors = parseShowColorsArgs(args, defaultDiagColor); 88 89 return true; 90 } 91 92 /// Parses all target input arguments and populates the target 93 /// options accordingly. 94 /// 95 /// \param [in] opts The target options instance to update 96 /// \param [in] args The list of input arguments (from the compiler invocation) 97 static void ParseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { 98 opts.triple = args.getLastArgValue(clang::driver::options::OPT_triple); 99 } 100 101 // Tweak the frontend configuration based on the frontend action 102 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 103 assert(opts.programAction != Fortran::frontend::InvalidAction && 104 "Fortran frontend action not set!"); 105 106 if (opts.programAction == DebugDumpParsingLog) 107 opts.instrumentedParse = true; 108 109 if (opts.programAction == DebugDumpProvenance || 110 opts.programAction == Fortran::frontend::GetDefinition) 111 opts.needProvenanceRangeToCharBlockMappings = true; 112 } 113 114 static bool ParseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 115 clang::DiagnosticsEngine &diags) { 116 unsigned numErrorsBefore = diags.getNumErrors(); 117 118 // By default the frontend driver creates a ParseSyntaxOnly action. 119 opts.programAction = ParseSyntaxOnly; 120 121 // Treat multiple action options as an invocation error. Note that `clang 122 // -cc1` does accept multiple action options, but will only consider the 123 // rightmost one. 124 if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) { 125 const unsigned diagID = diags.getCustomDiagID( 126 clang::DiagnosticsEngine::Error, "Only one action option is allowed"); 127 diags.Report(diagID); 128 return false; 129 } 130 131 // Identify the action (i.e. opts.ProgramAction) 132 if (const llvm::opt::Arg *a = 133 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 134 switch (a->getOption().getID()) { 135 default: { 136 llvm_unreachable("Invalid option in group!"); 137 } 138 case clang::driver::options::OPT_test_io: 139 opts.programAction = InputOutputTest; 140 break; 141 case clang::driver::options::OPT_E: 142 opts.programAction = PrintPreprocessedInput; 143 break; 144 case clang::driver::options::OPT_fsyntax_only: 145 opts.programAction = ParseSyntaxOnly; 146 break; 147 case clang::driver::options::OPT_emit_mlir: 148 opts.programAction = EmitMLIR; 149 break; 150 case clang::driver::options::OPT_emit_llvm: 151 opts.programAction = EmitLLVM; 152 break; 153 case clang::driver::options::OPT_emit_obj: 154 opts.programAction = EmitObj; 155 break; 156 case clang::driver::options::OPT_S: 157 opts.programAction = EmitAssembly; 158 break; 159 case clang::driver::options::OPT_fdebug_unparse: 160 opts.programAction = DebugUnparse; 161 break; 162 case clang::driver::options::OPT_fdebug_unparse_no_sema: 163 opts.programAction = DebugUnparseNoSema; 164 break; 165 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 166 opts.programAction = DebugUnparseWithSymbols; 167 break; 168 case clang::driver::options::OPT_fdebug_dump_symbols: 169 opts.programAction = DebugDumpSymbols; 170 break; 171 case clang::driver::options::OPT_fdebug_dump_parse_tree: 172 opts.programAction = DebugDumpParseTree; 173 break; 174 case clang::driver::options::OPT_fdebug_dump_pft: 175 opts.programAction = DebugDumpPFT; 176 break; 177 case clang::driver::options::OPT_fdebug_dump_all: 178 opts.programAction = DebugDumpAll; 179 break; 180 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 181 opts.programAction = DebugDumpParseTreeNoSema; 182 break; 183 case clang::driver::options::OPT_fdebug_dump_provenance: 184 opts.programAction = DebugDumpProvenance; 185 break; 186 case clang::driver::options::OPT_fdebug_dump_parsing_log: 187 opts.programAction = DebugDumpParsingLog; 188 break; 189 case clang::driver::options::OPT_fdebug_measure_parse_tree: 190 opts.programAction = DebugMeasureParseTree; 191 break; 192 case clang::driver::options::OPT_fdebug_pre_fir_tree: 193 opts.programAction = DebugPreFIRTree; 194 break; 195 case clang::driver::options::OPT_fget_symbols_sources: 196 opts.programAction = GetSymbolsSources; 197 break; 198 case clang::driver::options::OPT_fget_definition: 199 opts.programAction = GetDefinition; 200 break; 201 case clang::driver::options::OPT_init_only: 202 opts.programAction = InitOnly; 203 break; 204 205 // TODO: 206 // case clang::driver::options::OPT_emit_llvm: 207 // case clang::driver::options::OPT_emit_llvm_only: 208 // case clang::driver::options::OPT_emit_codegen_only: 209 // case clang::driver::options::OPT_emit_module: 210 // (...) 211 } 212 213 // Parse the values provided with `-fget-definition` (there should be 3 214 // integers) 215 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 216 clang::driver::options::OPT_fget_definition) { 217 unsigned optVals[3] = {0, 0, 0}; 218 219 for (unsigned i = 0; i < 3; i++) { 220 llvm::StringRef val = a->getValue(i); 221 222 if (val.getAsInteger(10, optVals[i])) { 223 // A non-integer was encountered - that's an error. 224 diags.Report(clang::diag::err_drv_invalid_value) 225 << a->getOption().getName() << val; 226 break; 227 } 228 } 229 opts.getDefVals.line = optVals[0]; 230 opts.getDefVals.startColumn = optVals[1]; 231 opts.getDefVals.endColumn = optVals[2]; 232 } 233 } 234 235 // Parsing -load <dsopath> option and storing shared object path 236 if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) { 237 opts.plugins.push_back(a->getValue()); 238 } 239 240 // Parsing -plugin <name> option and storing plugin name and setting action 241 if (const llvm::opt::Arg *a = 242 args.getLastArg(clang::driver::options::OPT_plugin)) { 243 opts.programAction = PluginAction; 244 opts.ActionName = a->getValue(); 245 } 246 247 opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); 248 opts.showHelp = args.hasArg(clang::driver::options::OPT_help); 249 opts.showVersion = args.hasArg(clang::driver::options::OPT_version); 250 251 // Get the input kind (from the value passed via `-x`) 252 InputKind dashX(Language::Unknown); 253 if (const llvm::opt::Arg *a = 254 args.getLastArg(clang::driver::options::OPT_x)) { 255 llvm::StringRef XValue = a->getValue(); 256 // Principal languages. 257 dashX = llvm::StringSwitch<InputKind>(XValue) 258 .Case("f90", Language::Fortran) 259 .Default(Language::Unknown); 260 261 // Some special cases cannot be combined with suffixes. 262 if (dashX.IsUnknown()) 263 dashX = llvm::StringSwitch<InputKind>(XValue) 264 .Case("ir", Language::LLVM_IR) 265 .Default(Language::Unknown); 266 267 if (dashX.IsUnknown()) 268 diags.Report(clang::diag::err_drv_invalid_value) 269 << a->getAsString(args) << a->getValue(); 270 } 271 272 // Collect the input files and save them in our instance of FrontendOptions. 273 std::vector<std::string> inputs = 274 args.getAllArgValues(clang::driver::options::OPT_INPUT); 275 opts.inputs.clear(); 276 if (inputs.empty()) 277 // '-' is the default input if none is given. 278 inputs.push_back("-"); 279 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 280 InputKind ik = dashX; 281 if (ik.IsUnknown()) { 282 ik = FrontendOptions::GetInputKindForExtension( 283 llvm::StringRef(inputs[i]).rsplit('.').second); 284 if (ik.IsUnknown()) 285 ik = Language::Unknown; 286 if (i == 0) 287 dashX = ik; 288 } 289 290 opts.inputs.emplace_back(std::move(inputs[i]), ik); 291 } 292 293 // Set fortranForm based on options -ffree-form and -ffixed-form. 294 if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form, 295 clang::driver::options::OPT_ffree_form)) { 296 opts.fortranForm = 297 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 298 ? FortranForm::FixedForm 299 : FortranForm::FreeForm; 300 } 301 302 // Set fixedFormColumns based on -ffixed-line-length=<value> 303 if (const auto *arg = 304 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 305 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 306 std::int64_t columns = -1; 307 if (argValue == "none") { 308 columns = 0; 309 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 310 columns = -1; 311 } 312 if (columns < 0) { 313 diags.Report(clang::diag::err_drv_negative_columns) 314 << arg->getOption().getName() << arg->getValue(); 315 } else if (columns == 0) { 316 opts.fixedFormColumns = 1000000; 317 } else if (columns < 7) { 318 diags.Report(clang::diag::err_drv_small_columns) 319 << arg->getOption().getName() << arg->getValue() << "7"; 320 } else { 321 opts.fixedFormColumns = columns; 322 } 323 } 324 325 // -f{no-}implicit-none 326 opts.features.Enable( 327 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 328 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 329 clang::driver::options::OPT_fno_implicit_none, false)); 330 331 // -f{no-}backslash 332 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 333 args.hasFlag(clang::driver::options::OPT_fbackslash, 334 clang::driver::options::OPT_fno_backslash, false)); 335 336 // -f{no-}logical-abbreviations 337 opts.features.Enable(Fortran::common::LanguageFeature::LogicalAbbreviations, 338 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 339 clang::driver::options::OPT_fno_logical_abbreviations, false)); 340 341 // -f{no-}xor-operator 342 opts.features.Enable(Fortran::common::LanguageFeature::XOROperator, 343 args.hasFlag(clang::driver::options::OPT_fxor_operator, 344 clang::driver::options::OPT_fno_xor_operator, false)); 345 346 // -fno-automatic 347 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 348 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 349 } 350 351 if (args.hasArg( 352 clang::driver::options::OPT_falternative_parameter_statement)) { 353 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 354 } 355 if (const llvm::opt::Arg *arg = 356 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 357 llvm::StringRef argValue = arg->getValue(); 358 if (argValue == "utf-8") { 359 opts.encoding = Fortran::parser::Encoding::UTF_8; 360 } else if (argValue == "latin-1") { 361 opts.encoding = Fortran::parser::Encoding::LATIN_1; 362 } else { 363 diags.Report(clang::diag::err_drv_invalid_value) 364 << arg->getAsString(args) << argValue; 365 } 366 } 367 368 setUpFrontendBasedOnAction(opts); 369 opts.dashX = dashX; 370 371 return diags.getNumErrors() == numErrorsBefore; 372 } 373 374 // Generate the path to look for intrinsic modules 375 static std::string getIntrinsicDir() { 376 // TODO: Find a system independent API 377 llvm::SmallString<128> driverPath; 378 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 379 llvm::sys::path::remove_filename(driverPath); 380 driverPath.append("/../include/flang/"); 381 return std::string(driverPath); 382 } 383 384 // Generate the path to look for OpenMP headers 385 static std::string getOpenMPHeadersDir() { 386 llvm::SmallString<128> includePath; 387 includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 388 llvm::sys::path::remove_filename(includePath); 389 includePath.append("/../include/flang/OpenMP/"); 390 return std::string(includePath); 391 } 392 393 /// Parses all preprocessor input arguments and populates the preprocessor 394 /// options accordingly. 395 /// 396 /// \param [in] opts The preprocessor options instance 397 /// \param [out] args The list of input arguments 398 static void parsePreprocessorArgs( 399 Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) { 400 // Add macros from the command line. 401 for (const auto *currentArg : args.filtered( 402 clang::driver::options::OPT_D, clang::driver::options::OPT_U)) { 403 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 404 opts.addMacroDef(currentArg->getValue()); 405 } else { 406 opts.addMacroUndef(currentArg->getValue()); 407 } 408 } 409 410 // Add the ordered list of -I's. 411 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 412 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 413 414 // Prepend the ordered list of -intrinsic-modules-path 415 // to the default location to search. 416 for (const auto *currentArg : 417 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 418 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 419 420 // -cpp/-nocpp 421 if (const auto *currentArg = args.getLastArg( 422 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 423 opts.macrosFlag = 424 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 425 ? PPMacrosFlag::Include 426 : PPMacrosFlag::Exclude; 427 428 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 429 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 430 } 431 432 /// Parses all semantic related arguments and populates the variables 433 /// options accordingly. Returns false if new errors are generated. 434 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 435 clang::DiagnosticsEngine &diags) { 436 unsigned numErrorsBefore = diags.getNumErrors(); 437 438 // -J/module-dir option 439 auto moduleDirList = 440 args.getAllArgValues(clang::driver::options::OPT_module_dir); 441 // User can only specify -J/-module-dir once 442 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 443 if (moduleDirList.size() > 1) { 444 const unsigned diagID = 445 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 446 "Only one '-module-dir/-J' option allowed"); 447 diags.Report(diagID); 448 } 449 if (moduleDirList.size() == 1) 450 res.SetModuleDir(moduleDirList[0]); 451 452 // -fdebug-module-writer option 453 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 454 res.SetDebugModuleDir(true); 455 } 456 457 // -module-suffix 458 if (const auto *moduleSuffix = 459 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 460 res.SetModuleFileSuffix(moduleSuffix->getValue()); 461 } 462 463 // -f{no-}analyzed-objects-for-unparse 464 res.SetUseAnalyzedObjectsForUnparse( 465 args.hasFlag(clang::driver::options::OPT_fanalyzed_objects_for_unparse, 466 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 467 468 return diags.getNumErrors() == numErrorsBefore; 469 } 470 471 /// Parses all diagnostics related arguments and populates the variables 472 /// options accordingly. Returns false if new errors are generated. 473 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 474 clang::DiagnosticsEngine &diags) { 475 unsigned numErrorsBefore = diags.getNumErrors(); 476 477 // -Werror option 478 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 479 // this has to change when other -W<opt>'s are supported. 480 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 481 if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) 482 .equals("error")) { 483 res.SetWarnAsErr(true); 484 } else { 485 const unsigned diagID = 486 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 487 "Only `-Werror` is supported currently."); 488 diags.Report(diagID); 489 } 490 } 491 492 return diags.getNumErrors() == numErrorsBefore; 493 } 494 495 /// Parses all Dialect related arguments and populates the variables 496 /// options accordingly. Returns false if new errors are generated. 497 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 498 clang::DiagnosticsEngine &diags) { 499 unsigned numErrorsBefore = diags.getNumErrors(); 500 501 // -fdefault* family 502 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 503 res.defaultKinds().set_defaultRealKind(8); 504 res.defaultKinds().set_doublePrecisionKind(16); 505 } 506 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 507 res.defaultKinds().set_defaultIntegerKind(8); 508 res.defaultKinds().set_subscriptIntegerKind(8); 509 res.defaultKinds().set_sizeIntegerKind(8); 510 } 511 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 512 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 513 // -fdefault-double-8 has to be used with -fdefault-real-8 514 // to be compatible with gfortran 515 const unsigned diagID = 516 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 517 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 518 diags.Report(diagID); 519 } 520 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 521 res.defaultKinds().set_doublePrecisionKind(8); 522 } 523 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 524 res.defaultKinds().set_sizeIntegerKind(8); 525 526 // -fopenmp and -fopenacc 527 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 528 res.frontendOpts().features.Enable( 529 Fortran::common::LanguageFeature::OpenACC); 530 } 531 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 532 res.frontendOpts().features.Enable( 533 Fortran::common::LanguageFeature::OpenMP); 534 } 535 536 // -pedantic 537 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 538 res.set_EnableConformanceChecks(); 539 } 540 // -std=f2018 (currently this implies -pedantic) 541 // TODO: Set proper options when more fortran standards 542 // are supported. 543 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 544 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 545 // We only allow f2018 as the given standard 546 if (standard.equals("f2018")) { 547 res.set_EnableConformanceChecks(); 548 } else { 549 const unsigned diagID = 550 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 551 "Only -std=f2018 is allowed currently."); 552 diags.Report(diagID); 553 } 554 } 555 return diags.getNumErrors() == numErrorsBefore; 556 } 557 558 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res, 559 llvm::ArrayRef<const char *> commandLineArgs, 560 clang::DiagnosticsEngine &diags) { 561 562 bool success = true; 563 564 // Parse the arguments 565 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 566 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 567 unsigned missingArgIndex, missingArgCount; 568 llvm::opt::InputArgList args = opts.ParseArgs( 569 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 570 571 // Check for missing argument error. 572 if (missingArgCount) { 573 diags.Report(clang::diag::err_drv_missing_argument) 574 << args.getArgString(missingArgIndex) << missingArgCount; 575 success = false; 576 } 577 578 // Issue errors on unknown arguments 579 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 580 auto argString = a->getAsString(args); 581 std::string nearest; 582 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 583 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 584 else 585 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 586 << argString << nearest; 587 success = false; 588 } 589 590 success &= ParseFrontendArgs(res.frontendOpts(), args, diags); 591 ParseTargetArgs(res.targetOpts(), args); 592 parsePreprocessorArgs(res.preprocessorOpts(), args); 593 success &= parseSemaArgs(res, args, diags); 594 success &= parseDialectArgs(res, args, diags); 595 success &= parseDiagArgs(res, args, diags); 596 res.frontendOpts_.llvmArgs = 597 args.getAllArgValues(clang::driver::options::OPT_mllvm); 598 599 return success; 600 } 601 602 void CompilerInvocation::CollectMacroDefinitions() { 603 auto &ppOpts = this->preprocessorOpts(); 604 605 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 606 llvm::StringRef macro = ppOpts.macros[i].first; 607 bool isUndef = ppOpts.macros[i].second; 608 609 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 610 llvm::StringRef macroName = macroPair.first; 611 llvm::StringRef macroBody = macroPair.second; 612 613 // For an #undef'd macro, we only care about the name. 614 if (isUndef) { 615 parserOpts_.predefinitions.emplace_back( 616 macroName.str(), std::optional<std::string>{}); 617 continue; 618 } 619 620 // For a #define'd macro, figure out the actual definition. 621 if (macroName.size() == macro.size()) 622 macroBody = "1"; 623 else { 624 // Note: GCC drops anything following an end-of-line character. 625 llvm::StringRef::size_type End = macroBody.find_first_of("\n\r"); 626 macroBody = macroBody.substr(0, End); 627 } 628 parserOpts_.predefinitions.emplace_back( 629 macroName, std::optional<std::string>(macroBody.str())); 630 } 631 } 632 633 void CompilerInvocation::SetDefaultFortranOpts() { 634 auto &fortranOptions = fortranOpts(); 635 636 std::vector<std::string> searchDirectories{"."s}; 637 fortranOptions.searchDirectories = searchDirectories; 638 639 // Add the location of omp_lib.h to the search directories. Currently this is 640 // identical to the modules' directory. 641 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 642 643 fortranOptions.isFixedForm = false; 644 } 645 646 // TODO: When expanding this method, consider creating a dedicated API for 647 // this. Also at some point we will need to differentiate between different 648 // targets and add dedicated predefines for each. 649 void CompilerInvocation::SetDefaultPredefinitions() { 650 auto &fortranOptions = fortranOpts(); 651 const auto &frontendOptions = frontendOpts(); 652 653 // Populate the macro list with version numbers and other predefinitions. 654 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 655 fortranOptions.predefinitions.emplace_back( 656 "__flang_major__", FLANG_VERSION_MAJOR_STRING); 657 fortranOptions.predefinitions.emplace_back( 658 "__flang_minor__", FLANG_VERSION_MINOR_STRING); 659 fortranOptions.predefinitions.emplace_back( 660 "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING); 661 662 // Add predefinitions based on extensions enabled 663 if (frontendOptions.features.IsEnabled( 664 Fortran::common::LanguageFeature::OpenACC)) { 665 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 666 } 667 if (frontendOptions.features.IsEnabled( 668 Fortran::common::LanguageFeature::OpenMP)) { 669 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 670 } 671 } 672 673 void CompilerInvocation::SetFortranOpts() { 674 auto &fortranOptions = fortranOpts(); 675 const auto &frontendOptions = frontendOpts(); 676 const auto &preprocessorOptions = preprocessorOpts(); 677 auto &moduleDirJ = moduleDir(); 678 679 if (frontendOptions.fortranForm != FortranForm::Unknown) { 680 fortranOptions.isFixedForm = 681 frontendOptions.fortranForm == FortranForm::FixedForm; 682 } 683 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 684 685 fortranOptions.features = frontendOptions.features; 686 fortranOptions.encoding = frontendOptions.encoding; 687 688 // Adding search directories specified by -I 689 fortranOptions.searchDirectories.insert( 690 fortranOptions.searchDirectories.end(), 691 preprocessorOptions.searchDirectoriesFromDashI.begin(), 692 preprocessorOptions.searchDirectoriesFromDashI.end()); 693 694 // Add the ordered list of -intrinsic-modules-path 695 fortranOptions.searchDirectories.insert( 696 fortranOptions.searchDirectories.end(), 697 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 698 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 699 700 // Add the default intrinsic module directory 701 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 702 703 // Add the directory supplied through -J/-module-dir to the list of search 704 // directories 705 if (moduleDirJ.compare(".") != 0) 706 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 707 708 if (frontendOptions.instrumentedParse) 709 fortranOptions.instrumentedParse = true; 710 711 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 712 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 713 714 if (enableConformanceChecks()) { 715 fortranOptions.features.WarnOnAllNonstandard(); 716 } 717 } 718 719 void CompilerInvocation::SetSemanticsOpts( 720 Fortran::parser::AllCookedSources &allCookedSources) { 721 const auto &fortranOptions = fortranOpts(); 722 723 semanticsContext_ = std::make_unique<semantics::SemanticsContext>( 724 defaultKinds(), fortranOptions.features, allCookedSources); 725 726 semanticsContext_->set_moduleDirectory(moduleDir()) 727 .set_searchDirectories(fortranOptions.searchDirectories) 728 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 729 .set_warnOnNonstandardUsage(enableConformanceChecks()) 730 .set_warningsAreErrors(warnAsErr()) 731 .set_moduleFileSuffix(moduleFileSuffix()); 732 } 733