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