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