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/Common/OpenMP-features.h" 16 #include "flang/Common/Version.h" 17 #include "flang/Frontend/CodeGenOptions.h" 18 #include "flang/Frontend/PreprocessorOptions.h" 19 #include "flang/Frontend/TargetOptions.h" 20 #include "flang/Semantics/semantics.h" 21 #include "flang/Version.inc" 22 #include "clang/Basic/AllDiagnostics.h" 23 #include "clang/Basic/DiagnosticDriver.h" 24 #include "clang/Basic/DiagnosticOptions.h" 25 #include "clang/Driver/DriverDiagnostic.h" 26 #include "clang/Driver/OptionUtils.h" 27 #include "clang/Driver/Options.h" 28 #include "llvm/ADT/StringRef.h" 29 #include "llvm/ADT/StringSwitch.h" 30 #include "llvm/Frontend/Debug/Options.h" 31 #include "llvm/Option/Arg.h" 32 #include "llvm/Option/ArgList.h" 33 #include "llvm/Option/OptTable.h" 34 #include "llvm/Support/FileSystem.h" 35 #include "llvm/Support/FileUtilities.h" 36 #include "llvm/Support/Path.h" 37 #include "llvm/Support/Process.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/TargetParser/Host.h" 40 #include "llvm/TargetParser/Triple.h" 41 #include <cstdlib> 42 #include <memory> 43 #include <optional> 44 45 using namespace Fortran::frontend; 46 47 //===----------------------------------------------------------------------===// 48 // Initialization. 49 //===----------------------------------------------------------------------===// 50 CompilerInvocationBase::CompilerInvocationBase() 51 : diagnosticOpts(new clang::DiagnosticOptions()), 52 preprocessorOpts(new PreprocessorOptions()) {} 53 54 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 55 : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())), 56 preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {} 57 58 CompilerInvocationBase::~CompilerInvocationBase() = default; 59 60 //===----------------------------------------------------------------------===// 61 // Deserialization (from args) 62 //===----------------------------------------------------------------------===// 63 static bool parseShowColorsArgs(const llvm::opt::ArgList &args, 64 bool defaultColor = true) { 65 // Color diagnostics default to auto ("on" if terminal supports) in the 66 // compiler driver `flang-new` but default to off in the frontend driver 67 // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color. 68 // Support both clang's -f[no-]color-diagnostics and gcc's 69 // -f[no-]diagnostics-colors[=never|always|auto]. 70 enum { 71 Colors_On, 72 Colors_Off, 73 Colors_Auto 74 } showColors = defaultColor ? Colors_Auto : Colors_Off; 75 76 for (auto *a : args) { 77 const llvm::opt::Option &opt = a->getOption(); 78 if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) { 79 showColors = Colors_On; 80 } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) { 81 showColors = Colors_Off; 82 } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 83 llvm::StringRef value(a->getValue()); 84 if (value == "always") 85 showColors = Colors_On; 86 else if (value == "never") 87 showColors = Colors_Off; 88 else if (value == "auto") 89 showColors = Colors_Auto; 90 } 91 } 92 93 return showColors == Colors_On || 94 (showColors == Colors_Auto && 95 llvm::sys::Process::StandardErrHasColors()); 96 } 97 98 /// Extracts the optimisation level from \a args. 99 static unsigned getOptimizationLevel(llvm::opt::ArgList &args, 100 clang::DiagnosticsEngine &diags) { 101 unsigned defaultOpt = 0; 102 103 if (llvm::opt::Arg *a = 104 args.getLastArg(clang::driver::options::OPT_O_Group)) { 105 if (a->getOption().matches(clang::driver::options::OPT_O0)) 106 return 0; 107 108 assert(a->getOption().matches(clang::driver::options::OPT_O)); 109 110 return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt, 111 diags); 112 } 113 114 return defaultOpt; 115 } 116 117 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts, 118 llvm::opt::ArgList &args) { 119 opts.ShowColors = parseShowColorsArgs(args); 120 121 return true; 122 } 123 124 static bool parseDebugArgs(Fortran::frontend::CodeGenOptions &opts, 125 llvm::opt::ArgList &args, 126 clang::DiagnosticsEngine &diags) { 127 using DebugInfoKind = llvm::codegenoptions::DebugInfoKind; 128 if (llvm::opt::Arg *arg = 129 args.getLastArg(clang::driver::options::OPT_debug_info_kind_EQ)) { 130 std::optional<DebugInfoKind> val = 131 llvm::StringSwitch<std::optional<DebugInfoKind>>(arg->getValue()) 132 .Case("line-tables-only", llvm::codegenoptions::DebugLineTablesOnly) 133 .Case("line-directives-only", 134 llvm::codegenoptions::DebugDirectivesOnly) 135 .Case("constructor", llvm::codegenoptions::DebugInfoConstructor) 136 .Case("limited", llvm::codegenoptions::LimitedDebugInfo) 137 .Case("standalone", llvm::codegenoptions::FullDebugInfo) 138 .Case("unused-types", llvm::codegenoptions::UnusedTypeInfo) 139 .Default(std::nullopt); 140 if (!val.has_value()) { 141 diags.Report(clang::diag::err_drv_invalid_value) 142 << arg->getAsString(args) << arg->getValue(); 143 return false; 144 } 145 opts.setDebugInfo(val.value()); 146 if (val != llvm::codegenoptions::DebugLineTablesOnly && 147 val != llvm::codegenoptions::NoDebugInfo) { 148 const auto debugWarning = diags.getCustomDiagID( 149 clang::DiagnosticsEngine::Warning, "Unsupported debug option: %0"); 150 diags.Report(debugWarning) << arg->getValue(); 151 } 152 } 153 return true; 154 } 155 156 static bool parseVectorLibArg(Fortran::frontend::CodeGenOptions &opts, 157 llvm::opt::ArgList &args, 158 clang::DiagnosticsEngine &diags) { 159 llvm::opt::Arg *arg = args.getLastArg(clang::driver::options::OPT_fveclib); 160 if (!arg) 161 return true; 162 163 using VectorLibrary = llvm::driver::VectorLibrary; 164 std::optional<VectorLibrary> val = 165 llvm::StringSwitch<std::optional<VectorLibrary>>(arg->getValue()) 166 .Case("Accelerate", VectorLibrary::Accelerate) 167 .Case("LIBMVEC", VectorLibrary::LIBMVEC) 168 .Case("MASSV", VectorLibrary::MASSV) 169 .Case("SVML", VectorLibrary::SVML) 170 .Case("SLEEF", VectorLibrary::SLEEF) 171 .Case("Darwin_libsystem_m", VectorLibrary::Darwin_libsystem_m) 172 .Case("ArmPL", VectorLibrary::ArmPL) 173 .Case("NoLibrary", VectorLibrary::NoLibrary) 174 .Default(std::nullopt); 175 if (!val.has_value()) { 176 diags.Report(clang::diag::err_drv_invalid_value) 177 << arg->getAsString(args) << arg->getValue(); 178 return false; 179 } 180 opts.setVecLib(val.value()); 181 return true; 182 } 183 184 // Generate an OptRemark object containing info on if the -Rgroup 185 // specified is enabled or not. 186 static CodeGenOptions::OptRemark 187 parseOptimizationRemark(clang::DiagnosticsEngine &diags, 188 llvm::opt::ArgList &args, llvm::opt::OptSpecifier optEq, 189 llvm::StringRef remarkOptName) { 190 assert((remarkOptName == "pass" || remarkOptName == "pass-missed" || 191 remarkOptName == "pass-analysis") && 192 "Unsupported remark option name provided."); 193 CodeGenOptions::OptRemark result; 194 195 for (llvm::opt::Arg *a : args) { 196 if (a->getOption().matches(clang::driver::options::OPT_R_Joined)) { 197 llvm::StringRef value = a->getValue(); 198 199 if (value == remarkOptName) { 200 result.Kind = CodeGenOptions::RemarkKind::RK_Enabled; 201 // Enable everything 202 result.Pattern = ".*"; 203 result.Regex = std::make_shared<llvm::Regex>(result.Pattern); 204 205 } else if (value.split('-') == 206 std::make_pair(llvm::StringRef("no"), remarkOptName)) { 207 result.Kind = CodeGenOptions::RemarkKind::RK_Disabled; 208 // Disable everything 209 result.Pattern = ""; 210 result.Regex = nullptr; 211 } 212 } else if (a->getOption().matches(optEq)) { 213 result.Kind = CodeGenOptions::RemarkKind::RK_WithPattern; 214 result.Pattern = a->getValue(); 215 result.Regex = std::make_shared<llvm::Regex>(result.Pattern); 216 std::string regexError; 217 218 if (!result.Regex->isValid(regexError)) { 219 diags.Report(clang::diag::err_drv_optimization_remark_pattern) 220 << regexError << a->getAsString(args); 221 return CodeGenOptions::OptRemark(); 222 } 223 } 224 } 225 return result; 226 } 227 228 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts, 229 llvm::opt::ArgList &args, 230 clang::DiagnosticsEngine &diags) { 231 opts.OptimizationLevel = getOptimizationLevel(args, diags); 232 233 if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager, 234 clang::driver::options::OPT_fno_debug_pass_manager, false)) 235 opts.DebugPassManager = 1; 236 237 if (args.hasFlag(clang::driver::options::OPT_fstack_arrays, 238 clang::driver::options::OPT_fno_stack_arrays, false)) 239 opts.StackArrays = 1; 240 241 if (args.hasFlag(clang::driver::options::OPT_floop_versioning, 242 clang::driver::options::OPT_fno_loop_versioning, false)) 243 opts.LoopVersioning = 1; 244 245 opts.AliasAnalysis = opts.OptimizationLevel > 0; 246 if (auto *arg = 247 args.getLastArg(clang::driver::options::OPT_falias_analysis, 248 clang::driver::options::OPT_fno_alias_analysis)) 249 opts.AliasAnalysis = 250 arg->getOption().matches(clang::driver::options::OPT_falias_analysis); 251 252 for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ)) 253 opts.LLVMPassPlugins.push_back(a->getValue()); 254 255 // -fembed-offload-object option 256 for (auto *a : 257 args.filtered(clang::driver::options::OPT_fembed_offload_object_EQ)) 258 opts.OffloadObjects.push_back(a->getValue()); 259 260 // -flto=full/thin option. 261 if (const llvm::opt::Arg *a = 262 args.getLastArg(clang::driver::options::OPT_flto_EQ)) { 263 llvm::StringRef s = a->getValue(); 264 assert((s == "full" || s == "thin") && "Unknown LTO mode."); 265 if (s == "full") 266 opts.PrepareForFullLTO = true; 267 else 268 opts.PrepareForThinLTO = true; 269 } 270 271 if (const llvm::opt::Arg *a = args.getLastArg( 272 clang::driver::options::OPT_mcode_object_version_EQ)) { 273 llvm::StringRef s = a->getValue(); 274 if (s == "5") 275 opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_5; 276 if (s == "4") 277 opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_4; 278 if (s == "none") 279 opts.CodeObjectVersion = llvm::CodeObjectVersionKind::COV_None; 280 } 281 282 // -f[no-]save-optimization-record[=<format>] 283 if (const llvm::opt::Arg *a = 284 args.getLastArg(clang::driver::options::OPT_opt_record_file)) 285 opts.OptRecordFile = a->getValue(); 286 287 // Optimization file format. Defaults to yaml 288 if (const llvm::opt::Arg *a = 289 args.getLastArg(clang::driver::options::OPT_opt_record_format)) 290 opts.OptRecordFormat = a->getValue(); 291 292 // Specifies, using a regex, which successful optimization passes(middle and 293 // backend), to include in the final optimization record file generated. If 294 // not provided -fsave-optimization-record will include all passes. 295 if (const llvm::opt::Arg *a = 296 args.getLastArg(clang::driver::options::OPT_opt_record_passes)) 297 opts.OptRecordPasses = a->getValue(); 298 299 // Create OptRemark that allows printing of all successful optimization 300 // passes applied. 301 opts.OptimizationRemark = 302 parseOptimizationRemark(diags, args, clang::driver::options::OPT_Rpass_EQ, 303 /*remarkOptName=*/"pass"); 304 305 // Create OptRemark that allows all missed optimization passes to be printed. 306 opts.OptimizationRemarkMissed = parseOptimizationRemark( 307 diags, args, clang::driver::options::OPT_Rpass_missed_EQ, 308 /*remarkOptName=*/"pass-missed"); 309 310 // Create OptRemark that allows all optimization decisions made by LLVM 311 // to be printed. 312 opts.OptimizationRemarkAnalysis = parseOptimizationRemark( 313 diags, args, clang::driver::options::OPT_Rpass_analysis_EQ, 314 /*remarkOptName=*/"pass-analysis"); 315 316 if (opts.getDebugInfo() == llvm::codegenoptions::NoDebugInfo) { 317 // If the user requested a flag that requires source locations available in 318 // the backend, make sure that the backend tracks source location 319 // information. 320 bool needLocTracking = !opts.OptRecordFile.empty() || 321 !opts.OptRecordPasses.empty() || 322 !opts.OptRecordFormat.empty() || 323 opts.OptimizationRemark.hasValidPattern() || 324 opts.OptimizationRemarkMissed.hasValidPattern() || 325 opts.OptimizationRemarkAnalysis.hasValidPattern(); 326 327 if (needLocTracking) 328 opts.setDebugInfo(llvm::codegenoptions::LocTrackingOnly); 329 } 330 331 if (auto *a = args.getLastArg(clang::driver::options::OPT_save_temps_EQ)) 332 opts.SaveTempsDir = a->getValue(); 333 334 // -mrelocation-model option. 335 if (const llvm::opt::Arg *a = 336 args.getLastArg(clang::driver::options::OPT_mrelocation_model)) { 337 llvm::StringRef modelName = a->getValue(); 338 auto relocModel = 339 llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(modelName) 340 .Case("static", llvm::Reloc::Static) 341 .Case("pic", llvm::Reloc::PIC_) 342 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC) 343 .Case("ropi", llvm::Reloc::ROPI) 344 .Case("rwpi", llvm::Reloc::RWPI) 345 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 346 .Default(std::nullopt); 347 if (relocModel.has_value()) 348 opts.setRelocationModel(*relocModel); 349 else 350 diags.Report(clang::diag::err_drv_invalid_value) 351 << a->getAsString(args) << modelName; 352 } 353 354 // -pic-level and -pic-is-pie option. 355 if (int picLevel = getLastArgIntValue( 356 args, clang::driver::options::OPT_pic_level, 0, diags)) { 357 if (picLevel > 2) 358 diags.Report(clang::diag::err_drv_invalid_value) 359 << args.getLastArg(clang::driver::options::OPT_pic_level) 360 ->getAsString(args) 361 << picLevel; 362 363 opts.PICLevel = picLevel; 364 if (args.hasArg(clang::driver::options::OPT_pic_is_pie)) 365 opts.IsPIE = 1; 366 } 367 368 // This option is compatible with -f[no-]underscoring in gfortran. 369 if (args.hasFlag(clang::driver::options::OPT_fno_underscoring, 370 clang::driver::options::OPT_funderscoring, false)) { 371 opts.Underscoring = 0; 372 } 373 } 374 375 /// Parses all target input arguments and populates the target 376 /// options accordingly. 377 /// 378 /// \param [in] opts The target options instance to update 379 /// \param [in] args The list of input arguments (from the compiler invocation) 380 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { 381 if (const llvm::opt::Arg *a = 382 args.getLastArg(clang::driver::options::OPT_triple)) 383 opts.triple = a->getValue(); 384 385 if (const llvm::opt::Arg *a = 386 args.getLastArg(clang::driver::options::OPT_target_cpu)) 387 opts.cpu = a->getValue(); 388 389 for (const llvm::opt::Arg *currentArg : 390 args.filtered(clang::driver::options::OPT_target_feature)) 391 opts.featuresAsWritten.emplace_back(currentArg->getValue()); 392 } 393 394 // Tweak the frontend configuration based on the frontend action 395 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 396 if (opts.programAction == DebugDumpParsingLog) 397 opts.instrumentedParse = true; 398 399 if (opts.programAction == DebugDumpProvenance || 400 opts.programAction == Fortran::frontend::GetDefinition) 401 opts.needProvenanceRangeToCharBlockMappings = true; 402 } 403 404 /// Parse the argument specified for the -fconvert=<value> option 405 static std::optional<const char *> parseConvertArg(const char *s) { 406 return llvm::StringSwitch<std::optional<const char *>>(s) 407 .Case("unknown", "UNKNOWN") 408 .Case("native", "NATIVE") 409 .Case("little-endian", "LITTLE_ENDIAN") 410 .Case("big-endian", "BIG_ENDIAN") 411 .Case("swap", "SWAP") 412 .Default(std::nullopt); 413 } 414 415 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 416 clang::DiagnosticsEngine &diags) { 417 unsigned numErrorsBefore = diags.getNumErrors(); 418 419 // By default the frontend driver creates a ParseSyntaxOnly action. 420 opts.programAction = ParseSyntaxOnly; 421 422 // Treat multiple action options as an invocation error. Note that `clang 423 // -cc1` does accept multiple action options, but will only consider the 424 // rightmost one. 425 if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) { 426 const unsigned diagID = diags.getCustomDiagID( 427 clang::DiagnosticsEngine::Error, "Only one action option is allowed"); 428 diags.Report(diagID); 429 return false; 430 } 431 432 // Identify the action (i.e. opts.ProgramAction) 433 if (const llvm::opt::Arg *a = 434 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 435 switch (a->getOption().getID()) { 436 default: { 437 llvm_unreachable("Invalid option in group!"); 438 } 439 case clang::driver::options::OPT_test_io: 440 opts.programAction = InputOutputTest; 441 break; 442 case clang::driver::options::OPT_E: 443 opts.programAction = PrintPreprocessedInput; 444 break; 445 case clang::driver::options::OPT_fsyntax_only: 446 opts.programAction = ParseSyntaxOnly; 447 break; 448 case clang::driver::options::OPT_emit_fir: 449 opts.programAction = EmitFIR; 450 break; 451 case clang::driver::options::OPT_emit_hlfir: 452 opts.programAction = EmitHLFIR; 453 break; 454 case clang::driver::options::OPT_emit_llvm: 455 opts.programAction = EmitLLVM; 456 break; 457 case clang::driver::options::OPT_emit_llvm_bc: 458 opts.programAction = EmitLLVMBitcode; 459 break; 460 case clang::driver::options::OPT_emit_obj: 461 opts.programAction = EmitObj; 462 break; 463 case clang::driver::options::OPT_S: 464 opts.programAction = EmitAssembly; 465 break; 466 case clang::driver::options::OPT_fdebug_unparse: 467 opts.programAction = DebugUnparse; 468 break; 469 case clang::driver::options::OPT_fdebug_unparse_no_sema: 470 opts.programAction = DebugUnparseNoSema; 471 break; 472 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 473 opts.programAction = DebugUnparseWithSymbols; 474 break; 475 case clang::driver::options::OPT_fdebug_dump_symbols: 476 opts.programAction = DebugDumpSymbols; 477 break; 478 case clang::driver::options::OPT_fdebug_dump_parse_tree: 479 opts.programAction = DebugDumpParseTree; 480 break; 481 case clang::driver::options::OPT_fdebug_dump_pft: 482 opts.programAction = DebugDumpPFT; 483 break; 484 case clang::driver::options::OPT_fdebug_dump_all: 485 opts.programAction = DebugDumpAll; 486 break; 487 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 488 opts.programAction = DebugDumpParseTreeNoSema; 489 break; 490 case clang::driver::options::OPT_fdebug_dump_provenance: 491 opts.programAction = DebugDumpProvenance; 492 break; 493 case clang::driver::options::OPT_fdebug_dump_parsing_log: 494 opts.programAction = DebugDumpParsingLog; 495 break; 496 case clang::driver::options::OPT_fdebug_measure_parse_tree: 497 opts.programAction = DebugMeasureParseTree; 498 break; 499 case clang::driver::options::OPT_fdebug_pre_fir_tree: 500 opts.programAction = DebugPreFIRTree; 501 break; 502 case clang::driver::options::OPT_fget_symbols_sources: 503 opts.programAction = GetSymbolsSources; 504 break; 505 case clang::driver::options::OPT_fget_definition: 506 opts.programAction = GetDefinition; 507 break; 508 case clang::driver::options::OPT_init_only: 509 opts.programAction = InitOnly; 510 break; 511 512 // TODO: 513 // case clang::driver::options::OPT_emit_llvm: 514 // case clang::driver::options::OPT_emit_llvm_only: 515 // case clang::driver::options::OPT_emit_codegen_only: 516 // case clang::driver::options::OPT_emit_module: 517 // (...) 518 } 519 520 // Parse the values provided with `-fget-definition` (there should be 3 521 // integers) 522 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 523 clang::driver::options::OPT_fget_definition) { 524 unsigned optVals[3] = {0, 0, 0}; 525 526 for (unsigned i = 0; i < 3; i++) { 527 llvm::StringRef val = a->getValue(i); 528 529 if (val.getAsInteger(10, optVals[i])) { 530 // A non-integer was encountered - that's an error. 531 diags.Report(clang::diag::err_drv_invalid_value) 532 << a->getOption().getName() << val; 533 break; 534 } 535 } 536 opts.getDefVals.line = optVals[0]; 537 opts.getDefVals.startColumn = optVals[1]; 538 opts.getDefVals.endColumn = optVals[2]; 539 } 540 } 541 542 // Parsing -load <dsopath> option and storing shared object path 543 if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) { 544 opts.plugins.push_back(a->getValue()); 545 } 546 547 // Parsing -plugin <name> option and storing plugin name and setting action 548 if (const llvm::opt::Arg *a = 549 args.getLastArg(clang::driver::options::OPT_plugin)) { 550 opts.programAction = PluginAction; 551 opts.actionName = a->getValue(); 552 } 553 554 opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); 555 opts.showHelp = args.hasArg(clang::driver::options::OPT_help); 556 opts.showVersion = args.hasArg(clang::driver::options::OPT_version); 557 558 // Get the input kind (from the value passed via `-x`) 559 InputKind dashX(Language::Unknown); 560 if (const llvm::opt::Arg *a = 561 args.getLastArg(clang::driver::options::OPT_x)) { 562 llvm::StringRef xValue = a->getValue(); 563 // Principal languages. 564 dashX = llvm::StringSwitch<InputKind>(xValue) 565 // Flang does not differentiate between pre-processed and not 566 // pre-processed inputs. 567 .Case("f95", Language::Fortran) 568 .Case("f95-cpp-input", Language::Fortran) 569 .Default(Language::Unknown); 570 571 // Flang's intermediate representations. 572 if (dashX.isUnknown()) 573 dashX = llvm::StringSwitch<InputKind>(xValue) 574 .Case("ir", Language::LLVM_IR) 575 .Case("fir", Language::MLIR) 576 .Case("mlir", Language::MLIR) 577 .Default(Language::Unknown); 578 579 if (dashX.isUnknown()) 580 diags.Report(clang::diag::err_drv_invalid_value) 581 << a->getAsString(args) << a->getValue(); 582 } 583 584 // Collect the input files and save them in our instance of FrontendOptions. 585 std::vector<std::string> inputs = 586 args.getAllArgValues(clang::driver::options::OPT_INPUT); 587 opts.inputs.clear(); 588 if (inputs.empty()) 589 // '-' is the default input if none is given. 590 inputs.push_back("-"); 591 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 592 InputKind ik = dashX; 593 if (ik.isUnknown()) { 594 ik = FrontendOptions::getInputKindForExtension( 595 llvm::StringRef(inputs[i]).rsplit('.').second); 596 if (ik.isUnknown()) 597 ik = Language::Unknown; 598 if (i == 0) 599 dashX = ik; 600 } 601 602 opts.inputs.emplace_back(std::move(inputs[i]), ik); 603 } 604 605 // Set fortranForm based on options -ffree-form and -ffixed-form. 606 if (const auto *arg = 607 args.getLastArg(clang::driver::options::OPT_ffixed_form, 608 clang::driver::options::OPT_ffree_form)) { 609 opts.fortranForm = 610 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 611 ? FortranForm::FixedForm 612 : FortranForm::FreeForm; 613 } 614 615 // Set fixedFormColumns based on -ffixed-line-length=<value> 616 if (const auto *arg = 617 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 618 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 619 std::int64_t columns = -1; 620 if (argValue == "none") { 621 columns = 0; 622 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 623 columns = -1; 624 } 625 if (columns < 0) { 626 diags.Report(clang::diag::err_drv_negative_columns) 627 << arg->getOption().getName() << arg->getValue(); 628 } else if (columns == 0) { 629 opts.fixedFormColumns = 1000000; 630 } else if (columns < 7) { 631 diags.Report(clang::diag::err_drv_small_columns) 632 << arg->getOption().getName() << arg->getValue() << "7"; 633 } else { 634 opts.fixedFormColumns = columns; 635 } 636 } 637 638 // Set conversion based on -fconvert=<value> 639 if (const auto *arg = 640 args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) { 641 const char *argValue = arg->getValue(); 642 if (auto convert = parseConvertArg(argValue)) 643 opts.envDefaults.push_back({"FORT_CONVERT", *convert}); 644 else 645 diags.Report(clang::diag::err_drv_invalid_value) 646 << arg->getAsString(args) << argValue; 647 } 648 649 // -f{no-}implicit-none 650 opts.features.Enable( 651 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 652 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 653 clang::driver::options::OPT_fno_implicit_none, false)); 654 655 // -f{no-}backslash 656 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 657 args.hasFlag(clang::driver::options::OPT_fbackslash, 658 clang::driver::options::OPT_fno_backslash, 659 false)); 660 661 // -f{no-}logical-abbreviations 662 opts.features.Enable( 663 Fortran::common::LanguageFeature::LogicalAbbreviations, 664 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 665 clang::driver::options::OPT_fno_logical_abbreviations, 666 false)); 667 668 // -f{no-}xor-operator 669 opts.features.Enable( 670 Fortran::common::LanguageFeature::XOROperator, 671 args.hasFlag(clang::driver::options::OPT_fxor_operator, 672 clang::driver::options::OPT_fno_xor_operator, false)); 673 674 // -fno-automatic 675 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 676 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 677 } 678 679 if (args.hasArg( 680 clang::driver::options::OPT_falternative_parameter_statement)) { 681 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 682 } 683 if (const llvm::opt::Arg *arg = 684 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 685 llvm::StringRef argValue = arg->getValue(); 686 if (argValue == "utf-8") { 687 opts.encoding = Fortran::parser::Encoding::UTF_8; 688 } else if (argValue == "latin-1") { 689 opts.encoding = Fortran::parser::Encoding::LATIN_1; 690 } else { 691 diags.Report(clang::diag::err_drv_invalid_value) 692 << arg->getAsString(args) << argValue; 693 } 694 } 695 696 setUpFrontendBasedOnAction(opts); 697 opts.dashX = dashX; 698 699 return diags.getNumErrors() == numErrorsBefore; 700 } 701 702 // Generate the path to look for intrinsic modules 703 static std::string getIntrinsicDir(const char *argv) { 704 // TODO: Find a system independent API 705 llvm::SmallString<128> driverPath; 706 driverPath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr)); 707 llvm::sys::path::remove_filename(driverPath); 708 driverPath.append("/../include/flang/"); 709 return std::string(driverPath); 710 } 711 712 // Generate the path to look for OpenMP headers 713 static std::string getOpenMPHeadersDir(const char *argv) { 714 llvm::SmallString<128> includePath; 715 includePath.assign(llvm::sys::fs::getMainExecutable(argv, nullptr)); 716 llvm::sys::path::remove_filename(includePath); 717 includePath.append("/../include/flang/OpenMP/"); 718 return std::string(includePath); 719 } 720 721 /// Parses all preprocessor input arguments and populates the preprocessor 722 /// options accordingly. 723 /// 724 /// \param [in] opts The preprocessor options instance 725 /// \param [out] args The list of input arguments 726 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts, 727 llvm::opt::ArgList &args) { 728 // Add macros from the command line. 729 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D, 730 clang::driver::options::OPT_U)) { 731 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 732 opts.addMacroDef(currentArg->getValue()); 733 } else { 734 opts.addMacroUndef(currentArg->getValue()); 735 } 736 } 737 738 // Add the ordered list of -I's. 739 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 740 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 741 742 // Prepend the ordered list of -intrinsic-modules-path 743 // to the default location to search. 744 for (const auto *currentArg : 745 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 746 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 747 748 // -cpp/-nocpp 749 if (const auto *currentArg = args.getLastArg( 750 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 751 opts.macrosFlag = 752 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 753 ? PPMacrosFlag::Include 754 : PPMacrosFlag::Exclude; 755 756 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 757 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 758 } 759 760 /// Parses all semantic related arguments and populates the variables 761 /// options accordingly. Returns false if new errors are generated. 762 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 763 clang::DiagnosticsEngine &diags) { 764 unsigned numErrorsBefore = diags.getNumErrors(); 765 766 // -J/module-dir option 767 auto moduleDirList = 768 args.getAllArgValues(clang::driver::options::OPT_module_dir); 769 // User can only specify -J/-module-dir once 770 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 771 if (moduleDirList.size() > 1) { 772 const unsigned diagID = 773 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 774 "Only one '-module-dir/-J' option allowed"); 775 diags.Report(diagID); 776 } 777 if (moduleDirList.size() == 1) 778 res.setModuleDir(moduleDirList[0]); 779 780 // -fdebug-module-writer option 781 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 782 res.setDebugModuleDir(true); 783 } 784 785 // -module-suffix 786 if (const auto *moduleSuffix = 787 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 788 res.setModuleFileSuffix(moduleSuffix->getValue()); 789 } 790 791 // -f{no-}analyzed-objects-for-unparse 792 res.setUseAnalyzedObjectsForUnparse(args.hasFlag( 793 clang::driver::options::OPT_fanalyzed_objects_for_unparse, 794 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 795 796 return diags.getNumErrors() == numErrorsBefore; 797 } 798 799 /// Parses all diagnostics related arguments and populates the variables 800 /// options accordingly. Returns false if new errors are generated. 801 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 802 clang::DiagnosticsEngine &diags) { 803 unsigned numErrorsBefore = diags.getNumErrors(); 804 805 // -Werror option 806 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 807 // this has to change when other -W<opt>'s are supported. 808 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 809 const auto &wArgs = 810 args.getAllArgValues(clang::driver::options::OPT_W_Joined); 811 for (const auto &wArg : wArgs) { 812 if (wArg == "error") { 813 res.setWarnAsErr(true); 814 } else { 815 const unsigned diagID = 816 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 817 "Only `-Werror` is supported currently."); 818 diags.Report(diagID); 819 } 820 } 821 } 822 823 // Default to off for `flang-new -fc1`. 824 res.getFrontendOpts().showColors = 825 parseShowColorsArgs(args, /*defaultDiagColor=*/false); 826 827 // Honor color diagnostics. 828 res.getDiagnosticOpts().ShowColors = res.getFrontendOpts().showColors; 829 830 return diags.getNumErrors() == numErrorsBefore; 831 } 832 833 /// Parses all Dialect related arguments and populates the variables 834 /// options accordingly. Returns false if new errors are generated. 835 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 836 clang::DiagnosticsEngine &diags) { 837 unsigned numErrorsBefore = diags.getNumErrors(); 838 839 // -fdefault* family 840 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 841 res.getDefaultKinds().set_defaultRealKind(8); 842 res.getDefaultKinds().set_doublePrecisionKind(16); 843 } 844 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 845 res.getDefaultKinds().set_defaultIntegerKind(8); 846 res.getDefaultKinds().set_subscriptIntegerKind(8); 847 res.getDefaultKinds().set_sizeIntegerKind(8); 848 res.getDefaultKinds().set_defaultLogicalKind(8); 849 } 850 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 851 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 852 // -fdefault-double-8 has to be used with -fdefault-real-8 853 // to be compatible with gfortran 854 const unsigned diagID = diags.getCustomDiagID( 855 clang::DiagnosticsEngine::Error, 856 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 857 diags.Report(diagID); 858 } 859 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 860 res.getDefaultKinds().set_doublePrecisionKind(8); 861 } 862 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 863 res.getDefaultKinds().set_sizeIntegerKind(8); 864 865 // -fopenmp and -fopenacc 866 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 867 res.getFrontendOpts().features.Enable( 868 Fortran::common::LanguageFeature::OpenACC); 869 } 870 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 871 // By default OpenMP is set to 1.1 version 872 res.getLangOpts().OpenMPVersion = 11; 873 res.getFrontendOpts().features.Enable( 874 Fortran::common::LanguageFeature::OpenMP); 875 if (int Version = getLastArgIntValue( 876 args, clang::driver::options::OPT_fopenmp_version_EQ, 877 res.getLangOpts().OpenMPVersion, diags)) { 878 res.getLangOpts().OpenMPVersion = Version; 879 } 880 if (args.hasArg(clang::driver::options::OPT_fopenmp_is_target_device)) { 881 res.getLangOpts().OpenMPIsTargetDevice = 1; 882 883 // Get OpenMP host file path if any and report if a non existent file is 884 // found 885 if (auto *arg = args.getLastArg( 886 clang::driver::options::OPT_fopenmp_host_ir_file_path)) { 887 res.getLangOpts().OMPHostIRFile = arg->getValue(); 888 if (!llvm::sys::fs::exists(res.getLangOpts().OMPHostIRFile)) 889 diags.Report(clang::diag::err_drv_omp_host_ir_file_not_found) 890 << res.getLangOpts().OMPHostIRFile; 891 } 892 893 if (args.hasFlag( 894 clang::driver::options::OPT_fopenmp_assume_teams_oversubscription, 895 clang::driver::options:: 896 OPT_fno_openmp_assume_teams_oversubscription, 897 /*Default=*/false)) 898 res.getLangOpts().OpenMPTeamSubscription = true; 899 900 if (args.hasArg( 901 clang::driver::options::OPT_fopenmp_assume_no_thread_state)) 902 res.getLangOpts().OpenMPNoThreadState = 1; 903 904 if (args.hasArg( 905 clang::driver::options::OPT_fopenmp_assume_no_nested_parallelism)) 906 res.getLangOpts().OpenMPNoNestedParallelism = 1; 907 908 if (args.hasFlag(clang::driver::options:: 909 OPT_fopenmp_assume_threads_oversubscription, 910 clang::driver::options:: 911 OPT_fno_openmp_assume_threads_oversubscription, 912 /*Default=*/false)) 913 res.getLangOpts().OpenMPThreadSubscription = true; 914 915 if ((args.hasArg(clang::driver::options::OPT_fopenmp_target_debug) || 916 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug_EQ))) { 917 res.getLangOpts().OpenMPTargetDebug = getLastArgIntValue( 918 args, clang::driver::options::OPT_fopenmp_target_debug_EQ, 919 res.getLangOpts().OpenMPTargetDebug, diags); 920 921 if (!res.getLangOpts().OpenMPTargetDebug && 922 args.hasArg(clang::driver::options::OPT_fopenmp_target_debug)) 923 res.getLangOpts().OpenMPTargetDebug = 1; 924 } 925 } 926 927 switch (llvm::Triple(res.getTargetOpts().triple).getArch()) { 928 case llvm::Triple::nvptx: 929 case llvm::Triple::nvptx64: 930 case llvm::Triple::amdgcn: 931 if (!res.getLangOpts().OpenMPIsTargetDevice) { 932 const unsigned diagID = diags.getCustomDiagID( 933 clang::DiagnosticsEngine::Error, 934 "OpenMP AMDGPU/NVPTX is only prepared to deal with device code."); 935 diags.Report(diagID); 936 } 937 res.getLangOpts().OpenMPIsGPU = 1; 938 break; 939 default: 940 res.getLangOpts().OpenMPIsGPU = 0; 941 break; 942 } 943 } 944 945 // -pedantic 946 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 947 res.setEnableConformanceChecks(); 948 res.setEnableUsageChecks(); 949 } 950 // -std=f2018 951 // TODO: Set proper options when more fortran standards 952 // are supported. 953 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 954 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 955 // We only allow f2018 as the given standard 956 if (standard.equals("f2018")) { 957 res.setEnableConformanceChecks(); 958 } else { 959 const unsigned diagID = 960 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 961 "Only -std=f2018 is allowed currently."); 962 diags.Report(diagID); 963 } 964 } 965 return diags.getNumErrors() == numErrorsBefore; 966 } 967 968 /// Parses all floating point related arguments and populates the 969 /// CompilerInvocation accordingly. 970 /// Returns false if new errors are generated. 971 /// 972 /// \param [out] invoc Stores the processed arguments 973 /// \param [in] args The compiler invocation arguments to parse 974 /// \param [out] diags DiagnosticsEngine to report erros with 975 static bool parseFloatingPointArgs(CompilerInvocation &invoc, 976 llvm::opt::ArgList &args, 977 clang::DiagnosticsEngine &diags) { 978 LangOptions &opts = invoc.getLangOpts(); 979 980 if (const llvm::opt::Arg *a = 981 args.getLastArg(clang::driver::options::OPT_ffp_contract)) { 982 const llvm::StringRef val = a->getValue(); 983 enum LangOptions::FPModeKind fpContractMode; 984 985 if (val == "off") 986 fpContractMode = LangOptions::FPM_Off; 987 else if (val == "fast") 988 fpContractMode = LangOptions::FPM_Fast; 989 else { 990 diags.Report(clang::diag::err_drv_unsupported_option_argument) 991 << a->getSpelling() << val; 992 return false; 993 } 994 995 opts.setFPContractMode(fpContractMode); 996 } 997 998 if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) { 999 opts.NoHonorInfs = true; 1000 } 1001 1002 if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) { 1003 opts.NoHonorNaNs = true; 1004 } 1005 1006 if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) { 1007 opts.ApproxFunc = true; 1008 } 1009 1010 if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) { 1011 opts.NoSignedZeros = true; 1012 } 1013 1014 if (args.getLastArg(clang::driver::options::OPT_mreassociate)) { 1015 opts.AssociativeMath = true; 1016 } 1017 1018 if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) { 1019 opts.ReciprocalMath = true; 1020 } 1021 1022 if (args.getLastArg(clang::driver::options::OPT_ffast_math)) { 1023 opts.NoHonorInfs = true; 1024 opts.NoHonorNaNs = true; 1025 opts.AssociativeMath = true; 1026 opts.ReciprocalMath = true; 1027 opts.ApproxFunc = true; 1028 opts.NoSignedZeros = true; 1029 opts.setFPContractMode(LangOptions::FPM_Fast); 1030 } 1031 1032 return true; 1033 } 1034 1035 /// Parses vscale range options and populates the CompilerInvocation 1036 /// accordingly. 1037 /// Returns false if new errors are generated. 1038 /// 1039 /// \param [out] invoc Stores the processed arguments 1040 /// \param [in] args The compiler invocation arguments to parse 1041 /// \param [out] diags DiagnosticsEngine to report erros with 1042 static bool parseVScaleArgs(CompilerInvocation &invoc, llvm::opt::ArgList &args, 1043 clang::DiagnosticsEngine &diags) { 1044 LangOptions &opts = invoc.getLangOpts(); 1045 if (const auto arg = 1046 args.getLastArg(clang::driver::options::OPT_mvscale_min_EQ)) { 1047 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 1048 unsigned VScaleMin; 1049 if (argValue.getAsInteger(/*Radix=*/10, VScaleMin)) { 1050 diags.Report(clang::diag::err_drv_unsupported_option_argument) 1051 << arg->getSpelling() << argValue; 1052 return false; 1053 } 1054 opts.VScaleMin = VScaleMin; 1055 } 1056 if (const auto arg = 1057 args.getLastArg(clang::driver::options::OPT_mvscale_max_EQ)) { 1058 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 1059 unsigned VScaleMax; 1060 if (argValue.getAsInteger(/*Radix=w*/ 10, VScaleMax)) { 1061 diags.Report(clang::diag::err_drv_unsupported_option_argument) 1062 << arg->getSpelling() << argValue; 1063 return false; 1064 } 1065 opts.VScaleMax = VScaleMax; 1066 } 1067 return true; 1068 } 1069 1070 static bool parseLinkerOptionsArgs(CompilerInvocation &invoc, 1071 llvm::opt::ArgList &args, 1072 clang::DiagnosticsEngine &diags) { 1073 llvm::Triple triple = llvm::Triple(invoc.getTargetOpts().triple); 1074 1075 // TODO: support --dependent-lib on other platforms when MLIR supports 1076 // !llvm.dependent.lib 1077 if (args.hasArg(clang::driver::options::OPT_dependent_lib) && 1078 !triple.isOSWindows()) { 1079 const unsigned diagID = 1080 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 1081 "--dependent-lib is only supported on Windows"); 1082 diags.Report(diagID); 1083 return false; 1084 } 1085 1086 invoc.getCodeGenOpts().DependentLibs = 1087 args.getAllArgValues(clang::driver::options::OPT_dependent_lib); 1088 return true; 1089 } 1090 1091 bool CompilerInvocation::createFromArgs( 1092 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 1093 clang::DiagnosticsEngine &diags, const char *argv0) { 1094 1095 bool success = true; 1096 1097 // Set the default triple for this CompilerInvocation. This might be 1098 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 1099 // below). 1100 // NOTE: Like in Clang, it would be nice to use option marshalling 1101 // for this so that the entire logic for setting-up the triple is in one 1102 // place. 1103 res.getTargetOpts().triple = 1104 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 1105 1106 // Parse the arguments 1107 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 1108 llvm::opt::Visibility visibilityMask(clang::driver::options::FC1Option); 1109 unsigned missingArgIndex, missingArgCount; 1110 llvm::opt::InputArgList args = opts.ParseArgs( 1111 commandLineArgs, missingArgIndex, missingArgCount, visibilityMask); 1112 1113 // Check for missing argument error. 1114 if (missingArgCount) { 1115 diags.Report(clang::diag::err_drv_missing_argument) 1116 << args.getArgString(missingArgIndex) << missingArgCount; 1117 success = false; 1118 } 1119 1120 // Issue errors on unknown arguments 1121 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 1122 auto argString = a->getAsString(args); 1123 std::string nearest; 1124 if (opts.findNearest(argString, nearest, visibilityMask) > 1) 1125 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 1126 else 1127 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 1128 << argString << nearest; 1129 success = false; 1130 } 1131 1132 // -flang-experimental-hlfir 1133 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir) || 1134 args.hasArg(clang::driver::options::OPT_emit_hlfir)) { 1135 res.loweringOpts.setLowerToHighLevelFIR(true); 1136 } 1137 1138 // -flang-deprecated-no-hlfir 1139 if (args.hasArg(clang::driver::options::OPT_flang_deprecated_no_hlfir) && 1140 !args.hasArg(clang::driver::options::OPT_emit_hlfir)) { 1141 if (args.hasArg(clang::driver::options::OPT_flang_experimental_hlfir)) { 1142 const unsigned diagID = diags.getCustomDiagID( 1143 clang::DiagnosticsEngine::Error, 1144 "Options '-flang-experimental-hlfir' and " 1145 "'-flang-deprecated-no-hlfir' cannot be both specified"); 1146 diags.Report(diagID); 1147 } 1148 res.loweringOpts.setLowerToHighLevelFIR(false); 1149 } 1150 1151 if (args.hasArg(clang::driver::options::OPT_flang_experimental_polymorphism)) { 1152 res.loweringOpts.setPolymorphicTypeImpl(true); 1153 } 1154 1155 // -fno-ppc-native-vector-element-order 1156 if (args.hasArg(clang::driver::options::OPT_fno_ppc_native_vec_elem_order)) { 1157 res.loweringOpts.setNoPPCNativeVecElemOrder(true); 1158 } 1159 1160 // Preserve all the remark options requested, i.e. -Rpass, -Rpass-missed or 1161 // -Rpass-analysis. This will be used later when processing and outputting the 1162 // remarks generated by LLVM in ExecuteCompilerInvocation.cpp. 1163 for (auto *a : args.filtered(clang::driver::options::OPT_R_Group)) { 1164 if (a->getOption().matches(clang::driver::options::OPT_R_value_Group)) 1165 // This is -Rfoo=, where foo is the name of the diagnostic 1166 // group. Add only the remark option name to the diagnostics. e.g. for 1167 // -Rpass= we will add the string "pass". 1168 res.getDiagnosticOpts().Remarks.push_back( 1169 std::string(a->getOption().getName().drop_front(1).rtrim("=-"))); 1170 else 1171 // If no regex was provided, add the provided value, e.g. for -Rpass add 1172 // the string "pass". 1173 res.getDiagnosticOpts().Remarks.push_back(a->getValue()); 1174 } 1175 1176 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 1177 parseTargetArgs(res.getTargetOpts(), args); 1178 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 1179 parseCodeGenArgs(res.getCodeGenOpts(), args, diags); 1180 success &= parseDebugArgs(res.getCodeGenOpts(), args, diags); 1181 success &= parseVectorLibArg(res.getCodeGenOpts(), args, diags); 1182 success &= parseSemaArgs(res, args, diags); 1183 success &= parseDialectArgs(res, args, diags); 1184 success &= parseDiagArgs(res, args, diags); 1185 1186 // Collect LLVM (-mllvm) and MLIR (-mmlir) options. 1187 // NOTE: Try to avoid adding any options directly to `llvmArgs` or 1188 // `mlirArgs`. Instead, you can use 1189 // * `-mllvm <your-llvm-option>`, or 1190 // * `-mmlir <your-mlir-option>`. 1191 res.frontendOpts.llvmArgs = 1192 args.getAllArgValues(clang::driver::options::OPT_mllvm); 1193 res.frontendOpts.mlirArgs = 1194 args.getAllArgValues(clang::driver::options::OPT_mmlir); 1195 1196 success &= parseFloatingPointArgs(res, args, diags); 1197 1198 success &= parseVScaleArgs(res, args, diags); 1199 1200 success &= parseLinkerOptionsArgs(res, args, diags); 1201 1202 // Set the string to be used as the return value of the COMPILER_OPTIONS 1203 // intrinsic of iso_fortran_env. This is either passed in from the parent 1204 // compiler driver invocation with an environment variable, or failing that 1205 // set to the command line arguments of the frontend driver invocation. 1206 res.allCompilerInvocOpts = std::string(); 1207 llvm::raw_string_ostream os(res.allCompilerInvocOpts); 1208 char *compilerOptsEnv = std::getenv("FLANG_COMPILER_OPTIONS_STRING"); 1209 if (compilerOptsEnv != nullptr) { 1210 os << compilerOptsEnv; 1211 } else { 1212 os << argv0 << ' '; 1213 for (auto it = commandLineArgs.begin(), e = commandLineArgs.end(); it != e; 1214 ++it) { 1215 os << ' ' << *it; 1216 } 1217 } 1218 1219 res.setArgv0(argv0); 1220 1221 return success; 1222 } 1223 1224 void CompilerInvocation::collectMacroDefinitions() { 1225 auto &ppOpts = this->getPreprocessorOpts(); 1226 1227 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 1228 llvm::StringRef macro = ppOpts.macros[i].first; 1229 bool isUndef = ppOpts.macros[i].second; 1230 1231 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 1232 llvm::StringRef macroName = macroPair.first; 1233 llvm::StringRef macroBody = macroPair.second; 1234 1235 // For an #undef'd macro, we only care about the name. 1236 if (isUndef) { 1237 parserOpts.predefinitions.emplace_back(macroName.str(), 1238 std::optional<std::string>{}); 1239 continue; 1240 } 1241 1242 // For a #define'd macro, figure out the actual definition. 1243 if (macroName.size() == macro.size()) 1244 macroBody = "1"; 1245 else { 1246 // Note: GCC drops anything following an end-of-line character. 1247 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 1248 macroBody = macroBody.substr(0, end); 1249 } 1250 parserOpts.predefinitions.emplace_back( 1251 macroName, std::optional<std::string>(macroBody.str())); 1252 } 1253 } 1254 1255 void CompilerInvocation::setDefaultFortranOpts() { 1256 auto &fortranOptions = getFortranOpts(); 1257 1258 std::vector<std::string> searchDirectories{"."s}; 1259 fortranOptions.searchDirectories = searchDirectories; 1260 1261 // Add the location of omp_lib.h to the search directories. Currently this is 1262 // identical to the modules' directory. 1263 fortranOptions.searchDirectories.emplace_back( 1264 getOpenMPHeadersDir(getArgv0())); 1265 1266 fortranOptions.isFixedForm = false; 1267 } 1268 1269 // TODO: When expanding this method, consider creating a dedicated API for 1270 // this. Also at some point we will need to differentiate between different 1271 // targets and add dedicated predefines for each. 1272 void CompilerInvocation::setDefaultPredefinitions() { 1273 auto &fortranOptions = getFortranOpts(); 1274 const auto &frontendOptions = getFrontendOpts(); 1275 // Populate the macro list with version numbers and other predefinitions. 1276 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 1277 fortranOptions.predefinitions.emplace_back("__flang_major__", 1278 FLANG_VERSION_MAJOR_STRING); 1279 fortranOptions.predefinitions.emplace_back("__flang_minor__", 1280 FLANG_VERSION_MINOR_STRING); 1281 fortranOptions.predefinitions.emplace_back("__flang_patchlevel__", 1282 FLANG_VERSION_PATCHLEVEL_STRING); 1283 1284 // Add predefinitions based on extensions enabled 1285 if (frontendOptions.features.IsEnabled( 1286 Fortran::common::LanguageFeature::OpenACC)) { 1287 fortranOptions.predefinitions.emplace_back("_OPENACC", "202211"); 1288 } 1289 if (frontendOptions.features.IsEnabled( 1290 Fortran::common::LanguageFeature::OpenMP)) { 1291 Fortran::common::setOpenMPMacro(getLangOpts().OpenMPVersion, 1292 fortranOptions.predefinitions); 1293 } 1294 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1295 if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) { 1296 fortranOptions.predefinitions.emplace_back("__x86_64__", "1"); 1297 fortranOptions.predefinitions.emplace_back("__x86_64", "1"); 1298 } 1299 } 1300 1301 void CompilerInvocation::setFortranOpts() { 1302 auto &fortranOptions = getFortranOpts(); 1303 const auto &frontendOptions = getFrontendOpts(); 1304 const auto &preprocessorOptions = getPreprocessorOpts(); 1305 auto &moduleDirJ = getModuleDir(); 1306 1307 if (frontendOptions.fortranForm != FortranForm::Unknown) { 1308 fortranOptions.isFixedForm = 1309 frontendOptions.fortranForm == FortranForm::FixedForm; 1310 } 1311 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 1312 1313 fortranOptions.features = frontendOptions.features; 1314 fortranOptions.encoding = frontendOptions.encoding; 1315 1316 // Adding search directories specified by -I 1317 fortranOptions.searchDirectories.insert( 1318 fortranOptions.searchDirectories.end(), 1319 preprocessorOptions.searchDirectoriesFromDashI.begin(), 1320 preprocessorOptions.searchDirectoriesFromDashI.end()); 1321 1322 // Add the ordered list of -intrinsic-modules-path 1323 fortranOptions.searchDirectories.insert( 1324 fortranOptions.searchDirectories.end(), 1325 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 1326 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 1327 1328 // Add the default intrinsic module directory 1329 fortranOptions.intrinsicModuleDirectories.emplace_back( 1330 getIntrinsicDir(getArgv0())); 1331 1332 // Add the directory supplied through -J/-module-dir to the list of search 1333 // directories 1334 if (moduleDirJ != ".") 1335 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 1336 1337 if (frontendOptions.instrumentedParse) 1338 fortranOptions.instrumentedParse = true; 1339 1340 if (frontendOptions.showColors) 1341 fortranOptions.showColors = true; 1342 1343 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 1344 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 1345 1346 if (getEnableConformanceChecks()) 1347 fortranOptions.features.WarnOnAllNonstandard(); 1348 1349 if (getEnableUsageChecks()) 1350 fortranOptions.features.WarnOnAllUsage(); 1351 } 1352 1353 std::unique_ptr<Fortran::semantics::SemanticsContext> 1354 CompilerInvocation::getSemanticsCtx( 1355 Fortran::parser::AllCookedSources &allCookedSources) { 1356 auto &fortranOptions = getFortranOpts(); 1357 1358 auto semanticsContext = std::make_unique<semantics::SemanticsContext>( 1359 getDefaultKinds(), fortranOptions.features, allCookedSources); 1360 1361 semanticsContext->set_moduleDirectory(getModuleDir()) 1362 .set_searchDirectories(fortranOptions.searchDirectories) 1363 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 1364 .set_warningsAreErrors(getWarnAsErr()) 1365 .set_moduleFileSuffix(getModuleFileSuffix()) 1366 .set_underscoring(getCodeGenOpts().Underscoring); 1367 1368 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 1369 // FIXME: Handle real(3) ? 1370 if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) { 1371 semanticsContext->targetCharacteristics().DisableType( 1372 Fortran::common::TypeCategory::Real, /*kind=*/10); 1373 } 1374 1375 std::string version = Fortran::common::getFlangFullVersion(); 1376 semanticsContext->targetCharacteristics() 1377 .set_compilerOptionsString(allCompilerInvocOpts) 1378 .set_compilerVersionString(version); 1379 1380 if (targetTriple.isPPC()) 1381 semanticsContext->targetCharacteristics().set_isPPC(true); 1382 1383 return semanticsContext; 1384 } 1385 1386 /// Set \p loweringOptions controlling lowering behavior based 1387 /// on the \p optimizationLevel. 1388 void CompilerInvocation::setLoweringOptions() { 1389 const CodeGenOptions &codegenOpts = getCodeGenOpts(); 1390 1391 // Lower TRANSPOSE as a runtime call under -O0. 1392 loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0); 1393 loweringOpts.setUnderscoring(codegenOpts.Underscoring); 1394 1395 const LangOptions &langOptions = getLangOpts(); 1396 Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions(); 1397 // TODO: when LangOptions are finalized, we can represent 1398 // the math related options using Fortran::commmon::MathOptionsBase, 1399 // so that we can just copy it into LoweringOptions. 1400 mathOpts 1401 .setFPContractEnabled(langOptions.getFPContractMode() == 1402 LangOptions::FPM_Fast) 1403 .setNoHonorInfs(langOptions.NoHonorInfs) 1404 .setNoHonorNaNs(langOptions.NoHonorNaNs) 1405 .setApproxFunc(langOptions.ApproxFunc) 1406 .setNoSignedZeros(langOptions.NoSignedZeros) 1407 .setAssociativeMath(langOptions.AssociativeMath) 1408 .setReciprocalMath(langOptions.ReciprocalMath); 1409 } 1410