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