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