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