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 // Coding style: https://mlir.llvm.org/getting_started/DeveloperGuide/ 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "flang/Frontend/CompilerInvocation.h" 14 #include "flang/Common/Fortran-features.h" 15 #include "flang/Frontend/CodeGenOptions.h" 16 #include "flang/Frontend/PreprocessorOptions.h" 17 #include "flang/Frontend/TargetOptions.h" 18 #include "flang/Semantics/semantics.h" 19 #include "flang/Version.inc" 20 #include "clang/Basic/AllDiagnostics.h" 21 #include "clang/Basic/DiagnosticDriver.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Driver/DriverDiagnostic.h" 24 #include "clang/Driver/OptionUtils.h" 25 #include "clang/Driver/Options.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/Option/Arg.h" 30 #include "llvm/Option/ArgList.h" 31 #include "llvm/Option/OptTable.h" 32 #include "llvm/Support/FileSystem.h" 33 #include "llvm/Support/FileUtilities.h" 34 #include "llvm/Support/Host.h" 35 #include "llvm/Support/Path.h" 36 #include "llvm/Support/Process.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <memory> 39 40 using namespace Fortran::frontend; 41 42 //===----------------------------------------------------------------------===// 43 // Initialization. 44 //===----------------------------------------------------------------------===// 45 CompilerInvocationBase::CompilerInvocationBase() 46 : diagnosticOpts(new clang::DiagnosticOptions()), 47 preprocessorOpts(new PreprocessorOptions()) {} 48 49 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 50 : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())), 51 preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {} 52 53 CompilerInvocationBase::~CompilerInvocationBase() = default; 54 55 //===----------------------------------------------------------------------===// 56 // Deserialization (from args) 57 //===----------------------------------------------------------------------===// 58 static bool parseShowColorsArgs(const llvm::opt::ArgList &args, 59 bool defaultColor = true) { 60 // Color diagnostics default to auto ("on" if terminal supports) in the 61 // compiler driver `flang-new` but default to off in the frontend driver 62 // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color. 63 // Support both clang's -f[no-]color-diagnostics and gcc's 64 // -f[no-]diagnostics-colors[=never|always|auto]. 65 enum { 66 Colors_On, 67 Colors_Off, 68 Colors_Auto 69 } showColors = defaultColor ? Colors_Auto : Colors_Off; 70 71 for (auto *a : args) { 72 const llvm::opt::Option &opt = a->getOption(); 73 if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) { 74 showColors = Colors_On; 75 } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) { 76 showColors = Colors_Off; 77 } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 78 llvm::StringRef value(a->getValue()); 79 if (value == "always") 80 showColors = Colors_On; 81 else if (value == "never") 82 showColors = Colors_Off; 83 else if (value == "auto") 84 showColors = Colors_Auto; 85 } 86 } 87 88 return showColors == Colors_On || 89 (showColors == Colors_Auto && 90 llvm::sys::Process::StandardErrHasColors()); 91 } 92 93 /// Extracts the optimisation level from \a args. 94 static unsigned getOptimizationLevel(llvm::opt::ArgList &args, 95 clang::DiagnosticsEngine &diags) { 96 unsigned defaultOpt = llvm::CodeGenOpt::None; 97 98 if (llvm::opt::Arg *a = 99 args.getLastArg(clang::driver::options::OPT_O_Group)) { 100 if (a->getOption().matches(clang::driver::options::OPT_O0)) 101 return llvm::CodeGenOpt::None; 102 103 assert(a->getOption().matches(clang::driver::options::OPT_O)); 104 105 return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt, 106 diags); 107 } 108 109 return defaultOpt; 110 } 111 112 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts, 113 llvm::opt::ArgList &args) { 114 opts.ShowColors = parseShowColorsArgs(args); 115 116 return true; 117 } 118 119 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts, 120 llvm::opt::ArgList &args, 121 clang::DiagnosticsEngine &diags) { 122 opts.OptimizationLevel = getOptimizationLevel(args, diags); 123 124 if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager, 125 clang::driver::options::OPT_fno_debug_pass_manager, false)) 126 opts.DebugPassManager = 1; 127 128 // -mrelocation-model option. 129 if (const llvm::opt::Arg *A = 130 args.getLastArg(clang::driver::options::OPT_mrelocation_model)) { 131 llvm::StringRef ModelName = A->getValue(); 132 auto RM = llvm::StringSwitch<llvm::Optional<llvm::Reloc::Model>>(ModelName) 133 .Case("static", llvm::Reloc::Static) 134 .Case("pic", llvm::Reloc::PIC_) 135 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC) 136 .Case("ropi", llvm::Reloc::ROPI) 137 .Case("rwpi", llvm::Reloc::RWPI) 138 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 139 .Default(llvm::None); 140 if (RM.has_value()) 141 opts.setRelocationModel(*RM); 142 else 143 diags.Report(clang::diag::err_drv_invalid_value) 144 << A->getAsString(args) << ModelName; 145 } 146 147 // -pic-level and -pic-is-pie option. 148 if (int PICLevel = getLastArgIntValue( 149 args, clang::driver::options::OPT_pic_level, 0, diags)) { 150 if (PICLevel > 2) 151 diags.Report(clang::diag::err_drv_invalid_value) 152 << args.getLastArg(clang::driver::options::OPT_pic_level) 153 ->getAsString(args) 154 << PICLevel; 155 156 opts.PICLevel = PICLevel; 157 if (args.hasArg(clang::driver::options::OPT_pic_is_pie)) 158 opts.IsPIE = 1; 159 } 160 } 161 162 /// Parses all target input arguments and populates the target 163 /// options accordingly. 164 /// 165 /// \param [in] opts The target options instance to update 166 /// \param [in] args The list of input arguments (from the compiler invocation) 167 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { 168 if (const llvm::opt::Arg *a = 169 args.getLastArg(clang::driver::options::OPT_triple)) 170 opts.triple = a->getValue(); 171 } 172 173 // Tweak the frontend configuration based on the frontend action 174 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 175 if (opts.programAction == DebugDumpParsingLog) 176 opts.instrumentedParse = true; 177 178 if (opts.programAction == DebugDumpProvenance || 179 opts.programAction == Fortran::frontend::GetDefinition) 180 opts.needProvenanceRangeToCharBlockMappings = true; 181 } 182 183 /// Parse the argument specified for the -fconvert=<value> option 184 static std::optional<const char *> parseConvertArg(const char *s) { 185 return llvm::StringSwitch<std::optional<const char *>>(s) 186 .Case("unknown", "UNKNOWN") 187 .Case("native", "NATIVE") 188 .Case("little-endian", "LITTLE_ENDIAN") 189 .Case("big-endian", "BIG_ENDIAN") 190 .Case("swap", "SWAP") 191 .Default(std::nullopt); 192 } 193 194 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 195 clang::DiagnosticsEngine &diags) { 196 unsigned numErrorsBefore = diags.getNumErrors(); 197 198 // By default the frontend driver creates a ParseSyntaxOnly action. 199 opts.programAction = ParseSyntaxOnly; 200 201 // Treat multiple action options as an invocation error. Note that `clang 202 // -cc1` does accept multiple action options, but will only consider the 203 // rightmost one. 204 if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) { 205 const unsigned diagID = diags.getCustomDiagID( 206 clang::DiagnosticsEngine::Error, "Only one action option is allowed"); 207 diags.Report(diagID); 208 return false; 209 } 210 211 // Identify the action (i.e. opts.ProgramAction) 212 if (const llvm::opt::Arg *a = 213 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 214 switch (a->getOption().getID()) { 215 default: { 216 llvm_unreachable("Invalid option in group!"); 217 } 218 case clang::driver::options::OPT_test_io: 219 opts.programAction = InputOutputTest; 220 break; 221 case clang::driver::options::OPT_E: 222 opts.programAction = PrintPreprocessedInput; 223 break; 224 case clang::driver::options::OPT_fsyntax_only: 225 opts.programAction = ParseSyntaxOnly; 226 break; 227 case clang::driver::options::OPT_emit_mlir: 228 opts.programAction = EmitMLIR; 229 break; 230 case clang::driver::options::OPT_emit_llvm: 231 opts.programAction = EmitLLVM; 232 break; 233 case clang::driver::options::OPT_emit_llvm_bc: 234 opts.programAction = EmitLLVMBitcode; 235 break; 236 case clang::driver::options::OPT_emit_obj: 237 opts.programAction = EmitObj; 238 break; 239 case clang::driver::options::OPT_S: 240 opts.programAction = EmitAssembly; 241 break; 242 case clang::driver::options::OPT_fdebug_unparse: 243 opts.programAction = DebugUnparse; 244 break; 245 case clang::driver::options::OPT_fdebug_unparse_no_sema: 246 opts.programAction = DebugUnparseNoSema; 247 break; 248 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 249 opts.programAction = DebugUnparseWithSymbols; 250 break; 251 case clang::driver::options::OPT_fdebug_dump_symbols: 252 opts.programAction = DebugDumpSymbols; 253 break; 254 case clang::driver::options::OPT_fdebug_dump_parse_tree: 255 opts.programAction = DebugDumpParseTree; 256 break; 257 case clang::driver::options::OPT_fdebug_dump_pft: 258 opts.programAction = DebugDumpPFT; 259 break; 260 case clang::driver::options::OPT_fdebug_dump_all: 261 opts.programAction = DebugDumpAll; 262 break; 263 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 264 opts.programAction = DebugDumpParseTreeNoSema; 265 break; 266 case clang::driver::options::OPT_fdebug_dump_provenance: 267 opts.programAction = DebugDumpProvenance; 268 break; 269 case clang::driver::options::OPT_fdebug_dump_parsing_log: 270 opts.programAction = DebugDumpParsingLog; 271 break; 272 case clang::driver::options::OPT_fdebug_measure_parse_tree: 273 opts.programAction = DebugMeasureParseTree; 274 break; 275 case clang::driver::options::OPT_fdebug_pre_fir_tree: 276 opts.programAction = DebugPreFIRTree; 277 break; 278 case clang::driver::options::OPT_fget_symbols_sources: 279 opts.programAction = GetSymbolsSources; 280 break; 281 case clang::driver::options::OPT_fget_definition: 282 opts.programAction = GetDefinition; 283 break; 284 case clang::driver::options::OPT_init_only: 285 opts.programAction = InitOnly; 286 break; 287 288 // TODO: 289 // case clang::driver::options::OPT_emit_llvm: 290 // case clang::driver::options::OPT_emit_llvm_only: 291 // case clang::driver::options::OPT_emit_codegen_only: 292 // case clang::driver::options::OPT_emit_module: 293 // (...) 294 } 295 296 // Parse the values provided with `-fget-definition` (there should be 3 297 // integers) 298 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 299 clang::driver::options::OPT_fget_definition) { 300 unsigned optVals[3] = {0, 0, 0}; 301 302 for (unsigned i = 0; i < 3; i++) { 303 llvm::StringRef val = a->getValue(i); 304 305 if (val.getAsInteger(10, optVals[i])) { 306 // A non-integer was encountered - that's an error. 307 diags.Report(clang::diag::err_drv_invalid_value) 308 << a->getOption().getName() << val; 309 break; 310 } 311 } 312 opts.getDefVals.line = optVals[0]; 313 opts.getDefVals.startColumn = optVals[1]; 314 opts.getDefVals.endColumn = optVals[2]; 315 } 316 } 317 318 // Parsing -load <dsopath> option and storing shared object path 319 if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) { 320 opts.plugins.push_back(a->getValue()); 321 } 322 323 // Parsing -plugin <name> option and storing plugin name and setting action 324 if (const llvm::opt::Arg *a = 325 args.getLastArg(clang::driver::options::OPT_plugin)) { 326 opts.programAction = PluginAction; 327 opts.actionName = a->getValue(); 328 } 329 330 opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); 331 opts.showHelp = args.hasArg(clang::driver::options::OPT_help); 332 opts.showVersion = args.hasArg(clang::driver::options::OPT_version); 333 334 // Get the input kind (from the value passed via `-x`) 335 InputKind dashX(Language::Unknown); 336 if (const llvm::opt::Arg *a = 337 args.getLastArg(clang::driver::options::OPT_x)) { 338 llvm::StringRef xValue = a->getValue(); 339 // Principal languages. 340 dashX = llvm::StringSwitch<InputKind>(xValue) 341 // Flang does not differentiate between pre-processed and not 342 // pre-processed inputs. 343 .Case("f95", Language::Fortran) 344 .Case("f95-cpp-input", Language::Fortran) 345 .Default(Language::Unknown); 346 347 // Flang's intermediate representations. 348 if (dashX.isUnknown()) 349 dashX = llvm::StringSwitch<InputKind>(xValue) 350 .Case("ir", Language::LLVM_IR) 351 .Case("fir", Language::MLIR) 352 .Case("mlir", Language::MLIR) 353 .Default(Language::Unknown); 354 355 if (dashX.isUnknown()) 356 diags.Report(clang::diag::err_drv_invalid_value) 357 << a->getAsString(args) << a->getValue(); 358 } 359 360 // Collect the input files and save them in our instance of FrontendOptions. 361 std::vector<std::string> inputs = 362 args.getAllArgValues(clang::driver::options::OPT_INPUT); 363 opts.inputs.clear(); 364 if (inputs.empty()) 365 // '-' is the default input if none is given. 366 inputs.push_back("-"); 367 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 368 InputKind ik = dashX; 369 if (ik.isUnknown()) { 370 ik = FrontendOptions::getInputKindForExtension( 371 llvm::StringRef(inputs[i]).rsplit('.').second); 372 if (ik.isUnknown()) 373 ik = Language::Unknown; 374 if (i == 0) 375 dashX = ik; 376 } 377 378 opts.inputs.emplace_back(std::move(inputs[i]), ik); 379 } 380 381 // Set fortranForm based on options -ffree-form and -ffixed-form. 382 if (const auto *arg = args.getLastArg(clang::driver::options::OPT_ffixed_form, 383 clang::driver::options::OPT_ffree_form)) { 384 opts.fortranForm = 385 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 386 ? FortranForm::FixedForm 387 : FortranForm::FreeForm; 388 } 389 390 // Set fixedFormColumns based on -ffixed-line-length=<value> 391 if (const auto *arg = 392 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 393 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 394 std::int64_t columns = -1; 395 if (argValue == "none") { 396 columns = 0; 397 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 398 columns = -1; 399 } 400 if (columns < 0) { 401 diags.Report(clang::diag::err_drv_negative_columns) 402 << arg->getOption().getName() << arg->getValue(); 403 } else if (columns == 0) { 404 opts.fixedFormColumns = 1000000; 405 } else if (columns < 7) { 406 diags.Report(clang::diag::err_drv_small_columns) 407 << arg->getOption().getName() << arg->getValue() << "7"; 408 } else { 409 opts.fixedFormColumns = columns; 410 } 411 } 412 413 // Set conversion based on -fconvert=<value> 414 if (const auto *arg = 415 args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) { 416 const char *argValue = arg->getValue(); 417 if (auto convert = parseConvertArg(argValue)) 418 opts.envDefaults.push_back({"FORT_CONVERT", *convert}); 419 else 420 diags.Report(clang::diag::err_drv_invalid_value) 421 << arg->getAsString(args) << argValue; 422 } 423 424 // -f{no-}implicit-none 425 opts.features.Enable( 426 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 427 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 428 clang::driver::options::OPT_fno_implicit_none, false)); 429 430 // -f{no-}backslash 431 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 432 args.hasFlag(clang::driver::options::OPT_fbackslash, 433 clang::driver::options::OPT_fno_backslash, false)); 434 435 // -f{no-}logical-abbreviations 436 opts.features.Enable(Fortran::common::LanguageFeature::LogicalAbbreviations, 437 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 438 clang::driver::options::OPT_fno_logical_abbreviations, false)); 439 440 // -f{no-}xor-operator 441 opts.features.Enable(Fortran::common::LanguageFeature::XOROperator, 442 args.hasFlag(clang::driver::options::OPT_fxor_operator, 443 clang::driver::options::OPT_fno_xor_operator, false)); 444 445 // -fno-automatic 446 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 447 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 448 } 449 450 if (args.hasArg( 451 clang::driver::options::OPT_falternative_parameter_statement)) { 452 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 453 } 454 if (const llvm::opt::Arg *arg = 455 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 456 llvm::StringRef argValue = arg->getValue(); 457 if (argValue == "utf-8") { 458 opts.encoding = Fortran::parser::Encoding::UTF_8; 459 } else if (argValue == "latin-1") { 460 opts.encoding = Fortran::parser::Encoding::LATIN_1; 461 } else { 462 diags.Report(clang::diag::err_drv_invalid_value) 463 << arg->getAsString(args) << argValue; 464 } 465 } 466 467 setUpFrontendBasedOnAction(opts); 468 opts.dashX = dashX; 469 470 return diags.getNumErrors() == numErrorsBefore; 471 } 472 473 // Generate the path to look for intrinsic modules 474 static std::string getIntrinsicDir() { 475 // TODO: Find a system independent API 476 llvm::SmallString<128> driverPath; 477 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 478 llvm::sys::path::remove_filename(driverPath); 479 driverPath.append("/../include/flang/"); 480 return std::string(driverPath); 481 } 482 483 // Generate the path to look for OpenMP headers 484 static std::string getOpenMPHeadersDir() { 485 llvm::SmallString<128> includePath; 486 includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 487 llvm::sys::path::remove_filename(includePath); 488 includePath.append("/../include/flang/OpenMP/"); 489 return std::string(includePath); 490 } 491 492 /// Parses all preprocessor input arguments and populates the preprocessor 493 /// options accordingly. 494 /// 495 /// \param [in] opts The preprocessor options instance 496 /// \param [out] args The list of input arguments 497 static void parsePreprocessorArgs( 498 Fortran::frontend::PreprocessorOptions &opts, llvm::opt::ArgList &args) { 499 // Add macros from the command line. 500 for (const auto *currentArg : args.filtered( 501 clang::driver::options::OPT_D, clang::driver::options::OPT_U)) { 502 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 503 opts.addMacroDef(currentArg->getValue()); 504 } else { 505 opts.addMacroUndef(currentArg->getValue()); 506 } 507 } 508 509 // Add the ordered list of -I's. 510 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 511 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 512 513 // Prepend the ordered list of -intrinsic-modules-path 514 // to the default location to search. 515 for (const auto *currentArg : 516 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 517 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 518 519 // -cpp/-nocpp 520 if (const auto *currentArg = args.getLastArg( 521 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 522 opts.macrosFlag = 523 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 524 ? PPMacrosFlag::Include 525 : PPMacrosFlag::Exclude; 526 527 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 528 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 529 } 530 531 /// Parses all semantic related arguments and populates the variables 532 /// options accordingly. Returns false if new errors are generated. 533 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 534 clang::DiagnosticsEngine &diags) { 535 unsigned numErrorsBefore = diags.getNumErrors(); 536 537 // -J/module-dir option 538 auto moduleDirList = 539 args.getAllArgValues(clang::driver::options::OPT_module_dir); 540 // User can only specify -J/-module-dir once 541 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 542 if (moduleDirList.size() > 1) { 543 const unsigned diagID = 544 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 545 "Only one '-module-dir/-J' option allowed"); 546 diags.Report(diagID); 547 } 548 if (moduleDirList.size() == 1) 549 res.setModuleDir(moduleDirList[0]); 550 551 // -fdebug-module-writer option 552 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 553 res.setDebugModuleDir(true); 554 } 555 556 // -module-suffix 557 if (const auto *moduleSuffix = 558 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 559 res.setModuleFileSuffix(moduleSuffix->getValue()); 560 } 561 562 // -f{no-}analyzed-objects-for-unparse 563 res.setUseAnalyzedObjectsForUnparse(args.hasFlag( 564 clang::driver::options::OPT_fanalyzed_objects_for_unparse, 565 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 566 567 return diags.getNumErrors() == numErrorsBefore; 568 } 569 570 /// Parses all diagnostics related arguments and populates the variables 571 /// options accordingly. Returns false if new errors are generated. 572 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 573 clang::DiagnosticsEngine &diags) { 574 unsigned numErrorsBefore = diags.getNumErrors(); 575 576 // -Werror option 577 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 578 // this has to change when other -W<opt>'s are supported. 579 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 580 if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) 581 .equals("error")) { 582 res.setWarnAsErr(true); 583 } else { 584 const unsigned diagID = 585 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 586 "Only `-Werror` is supported currently."); 587 diags.Report(diagID); 588 } 589 } 590 591 // Default to off for `flang-new -fc1`. 592 res.getFrontendOpts().showColors = 593 parseShowColorsArgs(args, /*defaultDiagColor=*/false); 594 595 return diags.getNumErrors() == numErrorsBefore; 596 } 597 598 /// Parses all Dialect related arguments and populates the variables 599 /// options accordingly. Returns false if new errors are generated. 600 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 601 clang::DiagnosticsEngine &diags) { 602 unsigned numErrorsBefore = diags.getNumErrors(); 603 604 // -fdefault* family 605 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 606 res.getDefaultKinds().set_defaultRealKind(8); 607 res.getDefaultKinds().set_doublePrecisionKind(16); 608 } 609 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 610 res.getDefaultKinds().set_defaultIntegerKind(8); 611 res.getDefaultKinds().set_subscriptIntegerKind(8); 612 res.getDefaultKinds().set_sizeIntegerKind(8); 613 } 614 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 615 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 616 // -fdefault-double-8 has to be used with -fdefault-real-8 617 // to be compatible with gfortran 618 const unsigned diagID = 619 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 620 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 621 diags.Report(diagID); 622 } 623 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 624 res.getDefaultKinds().set_doublePrecisionKind(8); 625 } 626 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 627 res.getDefaultKinds().set_sizeIntegerKind(8); 628 629 // -fopenmp and -fopenacc 630 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 631 res.getFrontendOpts().features.Enable( 632 Fortran::common::LanguageFeature::OpenACC); 633 } 634 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 635 res.getFrontendOpts().features.Enable( 636 Fortran::common::LanguageFeature::OpenMP); 637 } 638 639 // -pedantic 640 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 641 res.setEnableConformanceChecks(); 642 } 643 // -std=f2018 (currently this implies -pedantic) 644 // TODO: Set proper options when more fortran standards 645 // are supported. 646 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 647 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 648 // We only allow f2018 as the given standard 649 if (standard.equals("f2018")) { 650 res.setEnableConformanceChecks(); 651 } else { 652 const unsigned diagID = 653 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 654 "Only -std=f2018 is allowed currently."); 655 diags.Report(diagID); 656 } 657 } 658 return diags.getNumErrors() == numErrorsBefore; 659 } 660 661 bool CompilerInvocation::createFromArgs( 662 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 663 clang::DiagnosticsEngine &diags) { 664 665 bool success = true; 666 667 // Set the default triple for this CompilerInvocation. This might be 668 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 669 // below). 670 // NOTE: Like in Clang, it would be nice to use option marshalling 671 // for this so that the entire logic for setting-up the triple is in one 672 // place. 673 res.getTargetOpts().triple = 674 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 675 676 // Parse the arguments 677 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 678 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 679 unsigned missingArgIndex, missingArgCount; 680 llvm::opt::InputArgList args = opts.ParseArgs( 681 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 682 683 // Check for missing argument error. 684 if (missingArgCount) { 685 diags.Report(clang::diag::err_drv_missing_argument) 686 << args.getArgString(missingArgIndex) << missingArgCount; 687 success = false; 688 } 689 690 // Issue errors on unknown arguments 691 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 692 auto argString = a->getAsString(args); 693 std::string nearest; 694 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 695 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 696 else 697 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 698 << argString << nearest; 699 success = false; 700 } 701 702 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 703 parseTargetArgs(res.getTargetOpts(), args); 704 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 705 parseCodeGenArgs(res.getCodeGenOpts(), args, diags); 706 success &= parseSemaArgs(res, args, diags); 707 success &= parseDialectArgs(res, args, diags); 708 success &= parseDiagArgs(res, args, diags); 709 res.frontendOpts.llvmArgs = 710 args.getAllArgValues(clang::driver::options::OPT_mllvm); 711 712 res.frontendOpts.mlirArgs = 713 args.getAllArgValues(clang::driver::options::OPT_mmlir); 714 715 return success; 716 } 717 718 void CompilerInvocation::collectMacroDefinitions() { 719 auto &ppOpts = this->getPreprocessorOpts(); 720 721 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 722 llvm::StringRef macro = ppOpts.macros[i].first; 723 bool isUndef = ppOpts.macros[i].second; 724 725 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 726 llvm::StringRef macroName = macroPair.first; 727 llvm::StringRef macroBody = macroPair.second; 728 729 // For an #undef'd macro, we only care about the name. 730 if (isUndef) { 731 parserOpts.predefinitions.emplace_back(macroName.str(), 732 std::optional<std::string>{}); 733 continue; 734 } 735 736 // For a #define'd macro, figure out the actual definition. 737 if (macroName.size() == macro.size()) 738 macroBody = "1"; 739 else { 740 // Note: GCC drops anything following an end-of-line character. 741 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 742 macroBody = macroBody.substr(0, end); 743 } 744 parserOpts.predefinitions.emplace_back( 745 macroName, std::optional<std::string>(macroBody.str())); 746 } 747 } 748 749 void CompilerInvocation::setDefaultFortranOpts() { 750 auto &fortranOptions = getFortranOpts(); 751 752 std::vector<std::string> searchDirectories{"."s}; 753 fortranOptions.searchDirectories = searchDirectories; 754 755 // Add the location of omp_lib.h to the search directories. Currently this is 756 // identical to the modules' directory. 757 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 758 759 fortranOptions.isFixedForm = false; 760 } 761 762 // TODO: When expanding this method, consider creating a dedicated API for 763 // this. Also at some point we will need to differentiate between different 764 // targets and add dedicated predefines for each. 765 void CompilerInvocation::setDefaultPredefinitions() { 766 auto &fortranOptions = getFortranOpts(); 767 const auto &frontendOptions = getFrontendOpts(); 768 769 // Populate the macro list with version numbers and other predefinitions. 770 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 771 fortranOptions.predefinitions.emplace_back( 772 "__flang_major__", FLANG_VERSION_MAJOR_STRING); 773 fortranOptions.predefinitions.emplace_back( 774 "__flang_minor__", FLANG_VERSION_MINOR_STRING); 775 fortranOptions.predefinitions.emplace_back( 776 "__flang_patchlevel__", FLANG_VERSION_PATCHLEVEL_STRING); 777 778 // Add predefinitions based on extensions enabled 779 if (frontendOptions.features.IsEnabled( 780 Fortran::common::LanguageFeature::OpenACC)) { 781 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 782 } 783 if (frontendOptions.features.IsEnabled( 784 Fortran::common::LanguageFeature::OpenMP)) { 785 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 786 } 787 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 788 if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) { 789 fortranOptions.predefinitions.emplace_back("__x86_64__", "1"); 790 fortranOptions.predefinitions.emplace_back("__x86_64", "1"); 791 } 792 } 793 794 void CompilerInvocation::setFortranOpts() { 795 auto &fortranOptions = getFortranOpts(); 796 const auto &frontendOptions = getFrontendOpts(); 797 const auto &preprocessorOptions = getPreprocessorOpts(); 798 auto &moduleDirJ = getModuleDir(); 799 800 if (frontendOptions.fortranForm != FortranForm::Unknown) { 801 fortranOptions.isFixedForm = 802 frontendOptions.fortranForm == FortranForm::FixedForm; 803 } 804 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 805 806 fortranOptions.features = frontendOptions.features; 807 fortranOptions.encoding = frontendOptions.encoding; 808 809 // Adding search directories specified by -I 810 fortranOptions.searchDirectories.insert( 811 fortranOptions.searchDirectories.end(), 812 preprocessorOptions.searchDirectoriesFromDashI.begin(), 813 preprocessorOptions.searchDirectoriesFromDashI.end()); 814 815 // Add the ordered list of -intrinsic-modules-path 816 fortranOptions.searchDirectories.insert( 817 fortranOptions.searchDirectories.end(), 818 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 819 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 820 821 // Add the default intrinsic module directory 822 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 823 824 // Add the directory supplied through -J/-module-dir to the list of search 825 // directories 826 if (moduleDirJ != ".") 827 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 828 829 if (frontendOptions.instrumentedParse) 830 fortranOptions.instrumentedParse = true; 831 832 if (frontendOptions.showColors) 833 fortranOptions.showColors = true; 834 835 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 836 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 837 838 if (getEnableConformanceChecks()) { 839 fortranOptions.features.WarnOnAllNonstandard(); 840 } 841 } 842 843 void CompilerInvocation::setSemanticsOpts( 844 Fortran::parser::AllCookedSources &allCookedSources) { 845 auto &fortranOptions = getFortranOpts(); 846 847 semanticsContext = std::make_unique<semantics::SemanticsContext>( 848 getDefaultKinds(), fortranOptions.features, allCookedSources); 849 850 semanticsContext->set_moduleDirectory(getModuleDir()) 851 .set_searchDirectories(fortranOptions.searchDirectories) 852 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 853 .set_warnOnNonstandardUsage(getEnableConformanceChecks()) 854 .set_warningsAreErrors(getWarnAsErr()) 855 .set_moduleFileSuffix(getModuleFileSuffix()); 856 857 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 858 // FIXME: Handle real(3) ? 859 if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) { 860 semanticsContext->targetCharacteristics().DisableType( 861 Fortran::common::TypeCategory::Real, /*kind=*/10); 862 } 863 } 864 865 /// Set \p loweringOptions controlling lowering behavior based 866 /// on the \p optimizationLevel. 867 void CompilerInvocation::setLoweringOptions() { 868 const auto &codegenOpts = getCodeGenOpts(); 869 870 // Lower TRANSPOSE as a runtime call under -O0. 871 loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0); 872 } 873