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