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