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 if (args.hasFlag( 730 clang::driver::options::OPT_fopenmp_assume_teams_oversubscription, 731 clang::driver::options:: 732 OPT_fno_openmp_assume_teams_oversubscription, 733 /*Default=*/false)) 734 res.getLangOpts().OpenMPTeamSubscription = true; 735 736 if (args.hasArg( 737 clang::driver::options::OPT_fopenmp_assume_no_thread_state)) 738 res.getLangOpts().OpenMPNoThreadState = 1; 739 740 if (args.hasArg( 741 clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism)) 742 res.getLangOpts().OpenMPNoNestedParallelism = 1; 743 744 if (args.hasFlag(clang::driver::options:: 745 OPT_fopenmp_assume_threads_oversubscription, 746 clang::driver::options:: 747 OPT_fno_openmp_assume_threads_oversubscription, 748 /*Default=*/false)) 749 res.getLangOpts().OpenMPThreadSubscription = true; 750 751 if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) || 752 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) { 753 res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue( 754 args, clang::driver::options::OPT_fopenmp_target_debug_EQ, 755 res.getLangOpts().OpenMPTargetDebug, diags); 756 757 if (!res.getLangOpts().OpenMPTargetDebug && 758 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug)) 759 res.getLangOpts().OpenMPTargetDebug = 1; 760 } 761 } 762 } 763 764 // -pedantic 765 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 766 res.setEnableConformanceChecks(); 767 } 768 // -std=f2018 (currently this implies -pedantic) 769 // TODO: Set proper options when more fortran standards 770 // are supported. 771 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 772 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 773 // We only allow f2018 as the given standard 774 if (standard.equals("f2018")) { 775 res.setEnableConformanceChecks(); 776 } else { 777 const unsigned diagID = 778 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 779 "Only -std=f2018 is allowed currently."); 780 diags.Report(diagID); 781 } 782 } 783 return diags.getNumErrors() == numErrorsBefore; 784 } 785 786 /// Parses all floating point related arguments and populates the 787 /// CompilerInvocation accordingly. 788 /// Returns false if new errors are generated. 789 /// 790 /// \param [out] invoc Stores the processed arguments 791 /// \param [in] args The compiler invocation arguments to parse 792 /// \param [out] diags DiagnosticsEngine to report erros with 793 static bool parseFloatingPointArgs(CompilerInvocation &invoc, 794 llvm::opt::ArgList &args, 795 clang::DiagnosticsEngine &diags) { 796 LangOptions &opts = invoc.getLangOpts(); 797 798 if (const llvm::opt::Arg *a = 799 args.getLastArg(clang::driver::options::OPT_ffp_contract)) { 800 const llvm::StringRef val = a->getValue(); 801 enum LangOptions::FPModeKind fpContractMode; 802 803 if (val == "off") 804 fpContractMode = LangOptions::FPM_Off; 805 else if (val == "fast") 806 fpContractMode = LangOptions::FPM_Fast; 807 else { 808 diags.Report(clang::diag::err_drv_unsupported_option_argument) 809 << a->getSpelling() << val; 810 return false; 811 } 812 813 opts.setFPContractMode(fpContractMode); 814 } 815 816 if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) { 817 opts.NoHonorInfs = true; 818 } 819 820 if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) { 821 opts.NoHonorNaNs = true; 822 } 823 824 if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) { 825 opts.ApproxFunc = true; 826 } 827 828 if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) { 829 opts.NoSignedZeros = true; 830 } 831 832 if (args.getLastArg(clang::driver::options::OPT_mreassociate)) { 833 opts.AssociativeMath = true; 834 } 835 836 if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) { 837 opts.ReciprocalMath = true; 838 } 839 840 if (args.getLastArg(clang::driver::options::OPT_ffast_math)) { 841 opts.NoHonorInfs = true; 842 opts.NoHonorNaNs = true; 843 opts.AssociativeMath = true; 844 opts.ReciprocalMath = true; 845 opts.ApproxFunc = true; 846 opts.NoSignedZeros = true; 847 opts.setFPContractMode(LangOptions::FPM_Fast); 848 } 849 850 return true; 851 } 852 853 bool CompilerInvocation::createFromArgs( 854 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 855 clang::DiagnosticsEngine &diags) { 856 857 bool success = true; 858 859 // Set the default triple for this CompilerInvocation. This might be 860 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 861 // below). 862 // NOTE: Like in Clang, it would be nice to use option marshalling 863 // for this so that the entire logic for setting-up the triple is in one 864 // place. 865 res.getTargetOpts().triple = 866 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 867 868 // Parse the arguments 869 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 870 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 871 unsigned missingArgIndex, missingArgCount; 872 llvm::opt::InputArgList args = opts.ParseArgs( 873 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 874 875 // Check for missing argument error. 876 if (missingArgCount) { 877 diags.Report(clang::diag::err_drv_missing_argument) 878 << args.getArgString(missingArgIndex) << missingArgCount; 879 success = false; 880 } 881 882 // Issue errors on unknown arguments 883 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 884 auto argString = a->getAsString(args); 885 std::string nearest; 886 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 887 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 888 else 889 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 890 << argString << nearest; 891 success = false; 892 } 893 894 // -flang-experimental-hlfir 895 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) { 896 res.loweringOpts.setLowerToHighLevelFIR(true); 897 } 898 899 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 900 parseTargetArgs(res.getTargetOpts(), args); 901 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 902 parseCodeGenArgs(res.getCodeGenOpts(), args, diags); 903 success &= parseDebugArgs(res.getCodeGenOpts(), args, diags); 904 success &= parseSemaArgs(res, args, diags); 905 success &= parseDialectArgs(res, args, diags); 906 success &= parseDiagArgs(res, args, diags); 907 res.frontendOpts.llvmArgs = 908 args.getAllArgValues(clang::driver::options::OPT_mllvm); 909 910 res.frontendOpts.mlirArgs = 911 args.getAllArgValues(clang::driver::options::OPT_mmlir); 912 913 success &= parseFloatingPointArgs(res, args, diags); 914 915 return success; 916 } 917 918 void CompilerInvocation::collectMacroDefinitions() { 919 auto &ppOpts = this->getPreprocessorOpts(); 920 921 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 922 llvm::StringRef macro = ppOpts.macros[i].first; 923 bool isUndef = ppOpts.macros[i].second; 924 925 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 926 llvm::StringRef macroName = macroPair.first; 927 llvm::StringRef macroBody = macroPair.second; 928 929 // For an #undef'd macro, we only care about the name. 930 if (isUndef) { 931 parserOpts.predefinitions.emplace_back(macroName.str(), 932 std::optional<std::string>{}); 933 continue; 934 } 935 936 // For a #define'd macro, figure out the actual definition. 937 if (macroName.size() == macro.size()) 938 macroBody = "1"; 939 else { 940 // Note: GCC drops anything following an end-of-line character. 941 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 942 macroBody = macroBody.substr(0, end); 943 } 944 parserOpts.predefinitions.emplace_back( 945 macroName, std::optional<std::string>(macroBody.str())); 946 } 947 } 948 949 void CompilerInvocation::setDefaultFortranOpts() { 950 auto &fortranOptions = getFortranOpts(); 951 952 std::vector<std::string> searchDirectories{"."s}; 953 fortranOptions.searchDirectories = searchDirectories; 954 955 // Add the location of omp_lib.h to the search directories. Currently this is 956 // identical to the modules' directory. 957 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 958 959 fortranOptions.isFixedForm = false; 960 } 961 962 // TODO: When expanding this method, consider creating a dedicated API for 963 // this. Also at some point we will need to differentiate between different 964 // targets and add dedicated predefines for each. 965 void CompilerInvocation::setDefaultPredefinitions() { 966 auto &fortranOptions = getFortranOpts(); 967 const auto &frontendOptions = getFrontendOpts(); 968 969 // Populate the macro list with version numbers and other predefinitions. 970 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 971 fortranOptions.predefinitions.emplace_back("__flang_major__", 972 FLANG_VERSION_MAJOR_STRING); 973 fortranOptions.predefinitions.emplace_back("__flang_minor__", 974 FLANG_VERSION_MINOR_STRING); 975 fortranOptions.predefinitions.emplace_back("__flang_patchlevel__", 976 FLANG_VERSION_PATCHLEVEL_STRING); 977 978 // Add predefinitions based on extensions enabled 979 if (frontendOptions.features.IsEnabled( 980 Fortran::common::LanguageFeature::OpenACC)) { 981 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 982 } 983 if (frontendOptions.features.IsEnabled( 984 Fortran::common::LanguageFeature::OpenMP)) { 985 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 986 } 987 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 988 if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) { 989 fortranOptions.predefinitions.emplace_back("__x86_64__", "1"); 990 fortranOptions.predefinitions.emplace_back("__x86_64", "1"); 991 } 992 } 993 994 void CompilerInvocation::setFortranOpts() { 995 auto &fortranOptions = getFortranOpts(); 996 const auto &frontendOptions = getFrontendOpts(); 997 const auto &preprocessorOptions = getPreprocessorOpts(); 998 auto &moduleDirJ = getModuleDir(); 999 1000 if (frontendOptions.fortranForm != FortranForm::Unknown) { 1001 fortranOptions.isFixedForm = 1002 frontendOptions.fortranForm == FortranForm::FixedForm; 1003 } 1004 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 1005 1006 fortranOptions.features = frontendOptions.features; 1007 fortranOptions.encoding = frontendOptions.encoding; 1008 1009 // Adding search directories specified by -I 1010 fortranOptions.searchDirectories.insert( 1011 fortranOptions.searchDirectories.end(), 1012 preprocessorOptions.searchDirectoriesFromDashI.begin(), 1013 preprocessorOptions.searchDirectoriesFromDashI.end()); 1014 1015 // Add the ordered list of -intrinsic-modules-path 1016 fortranOptions.searchDirectories.insert( 1017 fortranOptions.searchDirectories.end(), 1018 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 1019 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 1020 1021 // Add the default intrinsic module directory 1022 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 1023 1024 // Add the directory supplied through -J/-module-dir to the list of search 1025 // directories 1026 if (moduleDirJ != ".") 1027 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 1028 1029 if (frontendOptions.instrumentedParse) 1030 fortranOptions.instrumentedParse = true; 1031 1032 if (frontendOptions.showColors) 1033 fortranOptions.showColors = true; 1034 1035 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 1036 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 1037 1038 if (getEnableConformanceChecks()) { 1039 fortranOptions.features.WarnOnAllNonstandard(); 1040 } 1041 } 1042 1043 void CompilerInvocation::setSemanticsOpts( 1044 Fortran::parser::AllCookedSources &allCookedSources) { 1045 auto &fortranOptions = getFortranOpts(); 1046 1047 semanticsContext = std::make_unique<semantics::SemanticsContext>( 1048 getDefaultKinds(), fortranOptions.features, allCookedSources); 1049 1050 semanticsContext->set_moduleDirectory(getModuleDir()) 1051 .set_searchDirectories(fortranOptions.searchDirectories) 1052 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 1053 .set_warnOnNonstandardUsage(getEnableConformanceChecks()) 1054 .set_warningsAreErrors(getWarnAsErr()) 1055 .set_moduleFileSuffix(getModuleFileSuffix()); 1056 1057 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1058 // FIXME: Handle real(3) ? 1059 if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) { 1060 semanticsContext->targetCharacteristics().DisableType( 1061 Fortran::common::TypeCategory::Real, /*kind=*/10); 1062 } 1063 } 1064 1065 /// Set \p loweringOptions controlling lowering behavior based 1066 /// on the \p optimizationLevel. 1067 void CompilerInvocation::setLoweringOptions() { 1068 const CodeGenOptions &codegenOpts = getCodeGenOpts(); 1069 1070 // Lower TRANSPOSE as a runtime call under -O0. 1071 loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0); 1072 1073 const LangOptions &langOptions = getLangOpts(); 1074 Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions(); 1075 // TODO: when LangOptions are finalized, we can represent 1076 // the math related options using Fortran::commmon::MathOptionsBase, 1077 // so that we can just copy it into LoweringOptions. 1078 mathOpts 1079 .setFPContractEnabled(langOptions.getFPContractMode() == 1080 LangOptions::FPM_Fast) 1081 .setNoHonorInfs(langOptions.NoHonorInfs) 1082 .setNoHonorNaNs(langOptions.NoHonorNaNs) 1083 .setApproxFunc(langOptions.ApproxFunc) 1084 .setNoSignedZeros(langOptions.NoSignedZeros) 1085 .setAssociativeMath(langOptions.AssociativeMath) 1086 .setReciprocalMath(langOptions.ReciprocalMath); 1087 } 1088