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