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