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( 297 Fortran::common::LanguageFeature::LogicalAbbreviations, 298 arg->getOption().matches( 299 clang::driver::options::OPT_flogical_abbreviations)); 300 } 301 if (const llvm::opt::Arg *arg = 302 args.getLastArg(clang::driver::options::OPT_fxor_operator, 303 clang::driver::options::OPT_fno_xor_operator)) { 304 opts.features_.Enable(Fortran::common::LanguageFeature::XOROperator, 305 arg->getOption().matches(clang::driver::options::OPT_fxor_operator)); 306 } 307 if (args.hasArg( 308 clang::driver::options::OPT_falternative_parameter_statement)) { 309 opts.features_.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 310 } 311 if (const llvm::opt::Arg *arg = 312 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 313 llvm::StringRef argValue = arg->getValue(); 314 if (argValue == "utf-8") { 315 opts.encoding_ = Fortran::parser::Encoding::UTF_8; 316 } else if (argValue == "latin-1") { 317 opts.encoding_ = Fortran::parser::Encoding::LATIN_1; 318 } else { 319 diags.Report(clang::diag::err_drv_invalid_value) 320 << arg->getAsString(args) << argValue; 321 } 322 } 323 324 setUpFrontendBasedOnAction(opts); 325 opts.dashX_ = dashX; 326 327 return diags.getNumErrors() == numErrorsBefore; 328 } 329 330 // Generate the path to look for intrinsic modules 331 static std::string getIntrinsicDir() { 332 // TODO: Find a system independent API 333 llvm::SmallString<128> driverPath; 334 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 335 llvm::sys::path::remove_filename(driverPath); 336 driverPath.append("/../include/flang/"); 337 return std::string(driverPath); 338 } 339 340 /// Parses all preprocessor input arguments and populates the preprocessor 341 /// options accordingly. 342 /// 343 /// \param [in] opts The preprocessor options instance 344 /// \param [out] args The list of input arguments 345 static void parsePreprocessorArgs( 346 Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) { 347 // Add macros from the command line. 348 for (const auto *currentArg : args.filtered( 349 clang::driver::options::OPT_D, clang::driver::options::OPT_U)) { 350 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 351 opts.addMacroDef(currentArg->getValue()); 352 } else { 353 opts.addMacroUndef(currentArg->getValue()); 354 } 355 } 356 357 // Add the ordered list of -I's. 358 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 359 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 360 361 // Prepend the ordered list of -intrinsic-modules-path 362 // to the default location to search. 363 for (const auto *currentArg : 364 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 365 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 366 367 // -cpp/-nocpp 368 if (const auto *currentArg = args.getLastArg( 369 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 370 opts.macrosFlag_ = 371 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 372 ? PPMacrosFlag::Include 373 : PPMacrosFlag::Exclude; 374 } 375 376 /// Parses all semantic related arguments and populates the variables 377 /// options accordingly. Returns false if new errors are generated. 378 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 379 clang::DiagnosticsEngine &diags) { 380 unsigned numErrorsBefore = diags.getNumErrors(); 381 382 // -J/module-dir option 383 auto moduleDirList = 384 args.getAllArgValues(clang::driver::options::OPT_module_dir); 385 // User can only specify -J/-module-dir once 386 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 387 if (moduleDirList.size() > 1) { 388 const unsigned diagID = 389 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 390 "Only one '-module-dir/-J' option allowed"); 391 diags.Report(diagID); 392 } 393 if (moduleDirList.size() == 1) 394 res.SetModuleDir(moduleDirList[0]); 395 396 // -fdebug-module-writer option 397 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 398 res.SetDebugModuleDir(true); 399 } 400 401 // -module-suffix 402 if (const auto *moduleSuffix = 403 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 404 res.SetModuleFileSuffix(moduleSuffix->getValue()); 405 } 406 407 // -fno-analyzed-objects-for-unparse 408 if (args.hasArg( 409 clang::driver::options::OPT_fno_analyzed_objects_for_unparse)) { 410 res.SetUseAnalyzedObjectsForUnparse(false); 411 } 412 413 return diags.getNumErrors() == numErrorsBefore; 414 } 415 416 /// Parses all diagnostics related arguments and populates the variables 417 /// options accordingly. Returns false if new errors are generated. 418 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 419 clang::DiagnosticsEngine &diags) { 420 unsigned numErrorsBefore = diags.getNumErrors(); 421 422 // -Werror option 423 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 424 // this has to change when other -W<opt>'s are supported. 425 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 426 if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) 427 .equals("error")) { 428 res.SetWarnAsErr(true); 429 } else { 430 const unsigned diagID = 431 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 432 "Only `-Werror` is supported currently."); 433 diags.Report(diagID); 434 } 435 } 436 437 return diags.getNumErrors() == numErrorsBefore; 438 } 439 440 /// Parses all Dialect related arguments and populates the variables 441 /// options accordingly. Returns false if new errors are generated. 442 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 443 clang::DiagnosticsEngine &diags) { 444 unsigned numErrorsBefore = diags.getNumErrors(); 445 446 // -fdefault* family 447 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 448 res.defaultKinds().set_defaultRealKind(8); 449 res.defaultKinds().set_doublePrecisionKind(16); 450 } 451 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 452 res.defaultKinds().set_defaultIntegerKind(8); 453 res.defaultKinds().set_subscriptIntegerKind(8); 454 res.defaultKinds().set_sizeIntegerKind(8); 455 } 456 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 457 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 458 // -fdefault-double-8 has to be used with -fdefault-real-8 459 // to be compatible with gfortran 460 const unsigned diagID = 461 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 462 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 463 diags.Report(diagID); 464 } 465 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 466 res.defaultKinds().set_doublePrecisionKind(8); 467 } 468 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 469 res.defaultKinds().set_sizeIntegerKind(8); 470 471 // -fopenmp and -fopenacc 472 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 473 res.frontendOpts().features_.Enable( 474 Fortran::common::LanguageFeature::OpenACC); 475 } 476 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 477 res.frontendOpts().features_.Enable( 478 Fortran::common::LanguageFeature::OpenMP); 479 } 480 481 // -pedantic 482 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 483 res.set_EnableConformanceChecks(); 484 } 485 // -std=f2018 (currently this implies -pedantic) 486 // TODO: Set proper options when more fortran standards 487 // are supported. 488 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 489 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 490 // We only allow f2018 as the given standard 491 if (standard.equals("f2018")) { 492 res.set_EnableConformanceChecks(); 493 } else { 494 const unsigned diagID = 495 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 496 "Only -std=f2018 is allowed currently."); 497 diags.Report(diagID); 498 } 499 } 500 return diags.getNumErrors() == numErrorsBefore; 501 } 502 503 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &res, 504 llvm::ArrayRef<const char *> commandLineArgs, 505 clang::DiagnosticsEngine &diags) { 506 507 bool success = true; 508 509 // Parse the arguments 510 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 511 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 512 unsigned missingArgIndex, missingArgCount; 513 llvm::opt::InputArgList args = opts.ParseArgs( 514 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 515 516 // Check for missing argument error. 517 if (missingArgCount) { 518 diags.Report(clang::diag::err_drv_missing_argument) 519 << args.getArgString(missingArgIndex) << missingArgCount; 520 success = false; 521 } 522 523 // Issue errors on unknown arguments 524 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 525 auto argString = a->getAsString(args); 526 std::string nearest; 527 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 528 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 529 else 530 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 531 << argString << nearest; 532 success = false; 533 } 534 535 success &= ParseFrontendArgs(res.frontendOpts(), args, diags); 536 parsePreprocessorArgs(res.preprocessorOpts(), args); 537 success &= parseSemaArgs(res, args, diags); 538 success &= parseDialectArgs(res, args, diags); 539 success &= parseDiagArgs(res, args, diags); 540 541 return success; 542 } 543 544 void CompilerInvocation::collectMacroDefinitions() { 545 auto &ppOpts = this->preprocessorOpts(); 546 547 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 548 llvm::StringRef macro = ppOpts.macros[i].first; 549 bool isUndef = ppOpts.macros[i].second; 550 551 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 552 llvm::StringRef macroName = macroPair.first; 553 llvm::StringRef macroBody = macroPair.second; 554 555 // For an #undef'd macro, we only care about the name. 556 if (isUndef) { 557 parserOpts_.predefinitions.emplace_back( 558 macroName.str(), std::optional<std::string>{}); 559 continue; 560 } 561 562 // For a #define'd macro, figure out the actual definition. 563 if (macroName.size() == macro.size()) 564 macroBody = "1"; 565 else { 566 // Note: GCC drops anything following an end-of-line character. 567 llvm::StringRef::size_type End = macroBody.find_first_of("\n\r"); 568 macroBody = macroBody.substr(0, End); 569 } 570 parserOpts_.predefinitions.emplace_back( 571 macroName, std::optional<std::string>(macroBody.str())); 572 } 573 } 574 575 void CompilerInvocation::SetDefaultFortranOpts() { 576 auto &fortranOptions = fortranOpts(); 577 578 // These defaults are based on the defaults in f18/f18.cpp. 579 std::vector<std::string> searchDirectories{"."s}; 580 fortranOptions.searchDirectories = searchDirectories; 581 fortranOptions.isFixedForm = false; 582 } 583 584 // TODO: When expanding this method, consider creating a dedicated API for 585 // this. Also at some point we will need to differentiate between different 586 // targets and add dedicated predefines for each. 587 void CompilerInvocation::setDefaultPredefinitions() { 588 auto &fortranOptions = fortranOpts(); 589 const auto &frontendOptions = frontendOpts(); 590 591 // Populate the macro list with version numbers and other predefinitions. 592 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 593 fortranOptions.predefinitions.emplace_back( 594 "__flang_major__", FLANG_VERSION_MAJOR_STRING); 595 fortranOptions.predefinitions.emplace_back( 596 "__flang_minor__", FLANG_VERSION_MINOR_STRING); 597 fortranOptions.predefinitions.emplace_back( 598 "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING); 599 600 // Add predefinitions based on extensions enabled 601 if (frontendOptions.features_.IsEnabled( 602 Fortran::common::LanguageFeature::OpenACC)) { 603 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 604 } 605 if (frontendOptions.features_.IsEnabled( 606 Fortran::common::LanguageFeature::OpenMP)) { 607 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 608 } 609 } 610 611 void CompilerInvocation::setFortranOpts() { 612 auto &fortranOptions = fortranOpts(); 613 const auto &frontendOptions = frontendOpts(); 614 const auto &preprocessorOptions = preprocessorOpts(); 615 auto &moduleDirJ = moduleDir(); 616 617 if (frontendOptions.fortranForm_ != FortranForm::Unknown) { 618 fortranOptions.isFixedForm = 619 frontendOptions.fortranForm_ == FortranForm::FixedForm; 620 } 621 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns_; 622 623 fortranOptions.features = frontendOptions.features_; 624 fortranOptions.encoding = frontendOptions.encoding_; 625 626 // Adding search directories specified by -I 627 fortranOptions.searchDirectories.insert( 628 fortranOptions.searchDirectories.end(), 629 preprocessorOptions.searchDirectoriesFromDashI.begin(), 630 preprocessorOptions.searchDirectoriesFromDashI.end()); 631 632 // Add the ordered list of -intrinsic-modules-path 633 fortranOptions.searchDirectories.insert( 634 fortranOptions.searchDirectories.end(), 635 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 636 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 637 638 // Add the default intrinsic module directory at the end 639 fortranOptions.searchDirectories.emplace_back(getIntrinsicDir()); 640 641 // Add the directory supplied through -J/-module-dir to the list of search 642 // directories 643 if (moduleDirJ.compare(".") != 0) 644 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 645 646 if (frontendOptions.instrumentedParse_) 647 fortranOptions.instrumentedParse = true; 648 649 if (frontendOptions.needProvenanceRangeToCharBlockMappings_) 650 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 651 652 if (enableConformanceChecks()) { 653 fortranOptions.features.WarnOnAllNonstandard(); 654 } 655 } 656 657 void CompilerInvocation::setSemanticsOpts( 658 Fortran::parser::AllCookedSources &allCookedSources) { 659 const auto &fortranOptions = fortranOpts(); 660 661 semanticsContext_ = std::make_unique<semantics::SemanticsContext>( 662 defaultKinds(), fortranOptions.features, allCookedSources); 663 664 semanticsContext_->set_moduleDirectory(moduleDir()) 665 .set_searchDirectories(fortranOptions.searchDirectories) 666 .set_warnOnNonstandardUsage(enableConformanceChecks()) 667 .set_warningsAreErrors(warnAsErr()) 668 .set_moduleFileSuffix(moduleFileSuffix()); 669 } 670