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/Frontend/CodeGenOptions.h" 16 #include "flang/Frontend/PreprocessorOptions.h" 17 #include "flang/Frontend/TargetOptions.h" 18 #include "flang/Semantics/semantics.h" 19 #include "flang/Version.inc" 20 #include "clang/Basic/AllDiagnostics.h" 21 #include "clang/Basic/DiagnosticDriver.h" 22 #include "clang/Basic/DiagnosticOptions.h" 23 #include "clang/Driver/DriverDiagnostic.h" 24 #include "clang/Driver/OptionUtils.h" 25 #include "clang/Driver/Options.h" 26 #include "llvm/ADT/StringRef.h" 27 #include "llvm/ADT/StringSwitch.h" 28 #include "llvm/ADT/Triple.h" 29 #include "llvm/Option/Arg.h" 30 #include "llvm/Option/ArgList.h" 31 #include "llvm/Option/OptTable.h" 32 #include "llvm/Support/FileSystem.h" 33 #include "llvm/Support/FileUtilities.h" 34 #include "llvm/Support/Host.h" 35 #include "llvm/Support/Path.h" 36 #include "llvm/Support/Process.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include <memory> 39 #include <optional> 40 41 using namespace Fortran::frontend; 42 43 //===----------------------------------------------------------------------===// 44 // Initialization. 45 //===----------------------------------------------------------------------===// 46 CompilerInvocationBase::CompilerInvocationBase() 47 : diagnosticOpts(new clang::DiagnosticOptions()), 48 preprocessorOpts(new PreprocessorOptions()) {} 49 50 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &x) 51 : diagnosticOpts(new clang::DiagnosticOptions(x.getDiagnosticOpts())), 52 preprocessorOpts(new PreprocessorOptions(x.getPreprocessorOpts())) {} 53 54 CompilerInvocationBase::~CompilerInvocationBase() = default; 55 56 //===----------------------------------------------------------------------===// 57 // Deserialization (from args) 58 //===----------------------------------------------------------------------===// 59 static bool parseShowColorsArgs(const llvm::opt::ArgList &args, 60 bool defaultColor = true) { 61 // Color diagnostics default to auto ("on" if terminal supports) in the 62 // compiler driver `flang-new` but default to off in the frontend driver 63 // `flang-new -fc1`, needing an explicit OPT_fdiagnostics_color. 64 // Support both clang's -f[no-]color-diagnostics and gcc's 65 // -f[no-]diagnostics-colors[=never|always|auto]. 66 enum { 67 Colors_On, 68 Colors_Off, 69 Colors_Auto 70 } showColors = defaultColor ? Colors_Auto : Colors_Off; 71 72 for (auto *a : args) { 73 const llvm::opt::Option &opt = a->getOption(); 74 if (opt.matches(clang::driver::options::OPT_fcolor_diagnostics)) { 75 showColors = Colors_On; 76 } else if (opt.matches(clang::driver::options::OPT_fno_color_diagnostics)) { 77 showColors = Colors_Off; 78 } else if (opt.matches(clang::driver::options::OPT_fdiagnostics_color_EQ)) { 79 llvm::StringRef value(a->getValue()); 80 if (value == "always") 81 showColors = Colors_On; 82 else if (value == "never") 83 showColors = Colors_Off; 84 else if (value == "auto") 85 showColors = Colors_Auto; 86 } 87 } 88 89 return showColors == Colors_On || 90 (showColors == Colors_Auto && 91 llvm::sys::Process::StandardErrHasColors()); 92 } 93 94 /// Extracts the optimisation level from \a args. 95 static unsigned getOptimizationLevel(llvm::opt::ArgList &args, 96 clang::DiagnosticsEngine &diags) { 97 unsigned defaultOpt = llvm::CodeGenOpt::None; 98 99 if (llvm::opt::Arg *a = 100 args.getLastArg(clang::driver::options::OPT_O_Group)) { 101 if (a->getOption().matches(clang::driver::options::OPT_O0)) 102 return llvm::CodeGenOpt::None; 103 104 assert(a->getOption().matches(clang::driver::options::OPT_O)); 105 106 return getLastArgIntValue(args, clang::driver::options::OPT_O, defaultOpt, 107 diags); 108 } 109 110 return defaultOpt; 111 } 112 113 bool Fortran::frontend::parseDiagnosticArgs(clang::DiagnosticOptions &opts, 114 llvm::opt::ArgList &args) { 115 opts.ShowColors = parseShowColorsArgs(args); 116 117 return true; 118 } 119 120 static void parseCodeGenArgs(Fortran::frontend::CodeGenOptions &opts, 121 llvm::opt::ArgList &args, 122 clang::DiagnosticsEngine &diags) { 123 opts.OptimizationLevel = getOptimizationLevel(args, diags); 124 125 if (args.hasFlag(clang::driver::options::OPT_fdebug_pass_manager, 126 clang::driver::options::OPT_fno_debug_pass_manager, false)) 127 opts.DebugPassManager = 1; 128 129 for (auto *a : args.filtered(clang::driver::options::OPT_fpass_plugin_EQ)) 130 opts.LLVMPassPlugins.push_back(a->getValue()); 131 132 // -mrelocation-model option. 133 if (const llvm::opt::Arg *A = 134 args.getLastArg(clang::driver::options::OPT_mrelocation_model)) { 135 llvm::StringRef ModelName = A->getValue(); 136 auto RM = llvm::StringSwitch<std::optional<llvm::Reloc::Model>>(ModelName) 137 .Case("static", llvm::Reloc::Static) 138 .Case("pic", llvm::Reloc::PIC_) 139 .Case("dynamic-no-pic", llvm::Reloc::DynamicNoPIC) 140 .Case("ropi", llvm::Reloc::ROPI) 141 .Case("rwpi", llvm::Reloc::RWPI) 142 .Case("ropi-rwpi", llvm::Reloc::ROPI_RWPI) 143 .Default(std::nullopt); 144 if (RM.has_value()) 145 opts.setRelocationModel(*RM); 146 else 147 diags.Report(clang::diag::err_drv_invalid_value) 148 << A->getAsString(args) << ModelName; 149 } 150 151 // -pic-level and -pic-is-pie option. 152 if (int PICLevel = getLastArgIntValue( 153 args, clang::driver::options::OPT_pic_level, 0, diags)) { 154 if (PICLevel > 2) 155 diags.Report(clang::diag::err_drv_invalid_value) 156 << args.getLastArg(clang::driver::options::OPT_pic_level) 157 ->getAsString(args) 158 << PICLevel; 159 160 opts.PICLevel = PICLevel; 161 if (args.hasArg(clang::driver::options::OPT_pic_is_pie)) 162 opts.IsPIE = 1; 163 } 164 } 165 166 /// Parses all target input arguments and populates the target 167 /// options accordingly. 168 /// 169 /// \param [in] opts The target options instance to update 170 /// \param [in] args The list of input arguments (from the compiler invocation) 171 static void parseTargetArgs(TargetOptions &opts, llvm::opt::ArgList &args) { 172 if (const llvm::opt::Arg *a = 173 args.getLastArg(clang::driver::options::OPT_triple)) 174 opts.triple = a->getValue(); 175 176 if (const llvm::opt::Arg *a = 177 args.getLastArg(clang::driver::options::OPT_target_cpu)) 178 opts.cpu = a->getValue(); 179 180 for (const llvm::opt::Arg *currentArg : 181 args.filtered(clang::driver::options::OPT_target_feature)) 182 opts.featuresAsWritten.emplace_back(currentArg->getValue()); 183 } 184 185 // Tweak the frontend configuration based on the frontend action 186 static void setUpFrontendBasedOnAction(FrontendOptions &opts) { 187 if (opts.programAction == DebugDumpParsingLog) 188 opts.instrumentedParse = true; 189 190 if (opts.programAction == DebugDumpProvenance || 191 opts.programAction == Fortran::frontend::GetDefinition) 192 opts.needProvenanceRangeToCharBlockMappings = true; 193 } 194 195 /// Parse the argument specified for the -fconvert=<value> option 196 static std::optional<const char *> parseConvertArg(const char *s) { 197 return llvm::StringSwitch<std::optional<const char *>>(s) 198 .Case("unknown", "UNKNOWN") 199 .Case("native", "NATIVE") 200 .Case("little-endian", "LITTLE_ENDIAN") 201 .Case("big-endian", "BIG_ENDIAN") 202 .Case("swap", "SWAP") 203 .Default(std::nullopt); 204 } 205 206 static bool parseFrontendArgs(FrontendOptions &opts, llvm::opt::ArgList &args, 207 clang::DiagnosticsEngine &diags) { 208 unsigned numErrorsBefore = diags.getNumErrors(); 209 210 // By default the frontend driver creates a ParseSyntaxOnly action. 211 opts.programAction = ParseSyntaxOnly; 212 213 // Treat multiple action options as an invocation error. Note that `clang 214 // -cc1` does accept multiple action options, but will only consider the 215 // rightmost one. 216 if (args.hasMultipleArgs(clang::driver::options::OPT_Action_Group)) { 217 const unsigned diagID = diags.getCustomDiagID( 218 clang::DiagnosticsEngine::Error, "Only one action option is allowed"); 219 diags.Report(diagID); 220 return false; 221 } 222 223 // Identify the action (i.e. opts.ProgramAction) 224 if (const llvm::opt::Arg *a = 225 args.getLastArg(clang::driver::options::OPT_Action_Group)) { 226 switch (a->getOption().getID()) { 227 default: { 228 llvm_unreachable("Invalid option in group!"); 229 } 230 case clang::driver::options::OPT_test_io: 231 opts.programAction = InputOutputTest; 232 break; 233 case clang::driver::options::OPT_E: 234 opts.programAction = PrintPreprocessedInput; 235 break; 236 case clang::driver::options::OPT_fsyntax_only: 237 opts.programAction = ParseSyntaxOnly; 238 break; 239 case clang::driver::options::OPT_emit_mlir: 240 opts.programAction = EmitMLIR; 241 break; 242 case clang::driver::options::OPT_emit_llvm: 243 opts.programAction = EmitLLVM; 244 break; 245 case clang::driver::options::OPT_emit_llvm_bc: 246 opts.programAction = EmitLLVMBitcode; 247 break; 248 case clang::driver::options::OPT_emit_obj: 249 opts.programAction = EmitObj; 250 break; 251 case clang::driver::options::OPT_S: 252 opts.programAction = EmitAssembly; 253 break; 254 case clang::driver::options::OPT_fdebug_unparse: 255 opts.programAction = DebugUnparse; 256 break; 257 case clang::driver::options::OPT_fdebug_unparse_no_sema: 258 opts.programAction = DebugUnparseNoSema; 259 break; 260 case clang::driver::options::OPT_fdebug_unparse_with_symbols: 261 opts.programAction = DebugUnparseWithSymbols; 262 break; 263 case clang::driver::options::OPT_fdebug_dump_symbols: 264 opts.programAction = DebugDumpSymbols; 265 break; 266 case clang::driver::options::OPT_fdebug_dump_parse_tree: 267 opts.programAction = DebugDumpParseTree; 268 break; 269 case clang::driver::options::OPT_fdebug_dump_pft: 270 opts.programAction = DebugDumpPFT; 271 break; 272 case clang::driver::options::OPT_fdebug_dump_all: 273 opts.programAction = DebugDumpAll; 274 break; 275 case clang::driver::options::OPT_fdebug_dump_parse_tree_no_sema: 276 opts.programAction = DebugDumpParseTreeNoSema; 277 break; 278 case clang::driver::options::OPT_fdebug_dump_provenance: 279 opts.programAction = DebugDumpProvenance; 280 break; 281 case clang::driver::options::OPT_fdebug_dump_parsing_log: 282 opts.programAction = DebugDumpParsingLog; 283 break; 284 case clang::driver::options::OPT_fdebug_measure_parse_tree: 285 opts.programAction = DebugMeasureParseTree; 286 break; 287 case clang::driver::options::OPT_fdebug_pre_fir_tree: 288 opts.programAction = DebugPreFIRTree; 289 break; 290 case clang::driver::options::OPT_fget_symbols_sources: 291 opts.programAction = GetSymbolsSources; 292 break; 293 case clang::driver::options::OPT_fget_definition: 294 opts.programAction = GetDefinition; 295 break; 296 case clang::driver::options::OPT_init_only: 297 opts.programAction = InitOnly; 298 break; 299 300 // TODO: 301 // case clang::driver::options::OPT_emit_llvm: 302 // case clang::driver::options::OPT_emit_llvm_only: 303 // case clang::driver::options::OPT_emit_codegen_only: 304 // case clang::driver::options::OPT_emit_module: 305 // (...) 306 } 307 308 // Parse the values provided with `-fget-definition` (there should be 3 309 // integers) 310 if (llvm::opt::OptSpecifier(a->getOption().getID()) == 311 clang::driver::options::OPT_fget_definition) { 312 unsigned optVals[3] = {0, 0, 0}; 313 314 for (unsigned i = 0; i < 3; i++) { 315 llvm::StringRef val = a->getValue(i); 316 317 if (val.getAsInteger(10, optVals[i])) { 318 // A non-integer was encountered - that's an error. 319 diags.Report(clang::diag::err_drv_invalid_value) 320 << a->getOption().getName() << val; 321 break; 322 } 323 } 324 opts.getDefVals.line = optVals[0]; 325 opts.getDefVals.startColumn = optVals[1]; 326 opts.getDefVals.endColumn = optVals[2]; 327 } 328 } 329 330 // Parsing -load <dsopath> option and storing shared object path 331 if (llvm::opt::Arg *a = args.getLastArg(clang::driver::options::OPT_load)) { 332 opts.plugins.push_back(a->getValue()); 333 } 334 335 // Parsing -plugin <name> option and storing plugin name and setting action 336 if (const llvm::opt::Arg *a = 337 args.getLastArg(clang::driver::options::OPT_plugin)) { 338 opts.programAction = PluginAction; 339 opts.actionName = a->getValue(); 340 } 341 342 opts.outputFile = args.getLastArgValue(clang::driver::options::OPT_o); 343 opts.showHelp = args.hasArg(clang::driver::options::OPT_help); 344 opts.showVersion = args.hasArg(clang::driver::options::OPT_version); 345 346 // Get the input kind (from the value passed via `-x`) 347 InputKind dashX(Language::Unknown); 348 if (const llvm::opt::Arg *a = 349 args.getLastArg(clang::driver::options::OPT_x)) { 350 llvm::StringRef xValue = a->getValue(); 351 // Principal languages. 352 dashX = llvm::StringSwitch<InputKind>(xValue) 353 // Flang does not differentiate between pre-processed and not 354 // pre-processed inputs. 355 .Case("f95", Language::Fortran) 356 .Case("f95-cpp-input", Language::Fortran) 357 .Default(Language::Unknown); 358 359 // Flang's intermediate representations. 360 if (dashX.isUnknown()) 361 dashX = llvm::StringSwitch<InputKind>(xValue) 362 .Case("ir", Language::LLVM_IR) 363 .Case("fir", Language::MLIR) 364 .Case("mlir", Language::MLIR) 365 .Default(Language::Unknown); 366 367 if (dashX.isUnknown()) 368 diags.Report(clang::diag::err_drv_invalid_value) 369 << a->getAsString(args) << a->getValue(); 370 } 371 372 // Collect the input files and save them in our instance of FrontendOptions. 373 std::vector<std::string> inputs = 374 args.getAllArgValues(clang::driver::options::OPT_INPUT); 375 opts.inputs.clear(); 376 if (inputs.empty()) 377 // '-' is the default input if none is given. 378 inputs.push_back("-"); 379 for (unsigned i = 0, e = inputs.size(); i != e; ++i) { 380 InputKind ik = dashX; 381 if (ik.isUnknown()) { 382 ik = FrontendOptions::getInputKindForExtension( 383 llvm::StringRef(inputs[i]).rsplit('.').second); 384 if (ik.isUnknown()) 385 ik = Language::Unknown; 386 if (i == 0) 387 dashX = ik; 388 } 389 390 opts.inputs.emplace_back(std::move(inputs[i]), ik); 391 } 392 393 // Set fortranForm based on options -ffree-form and -ffixed-form. 394 if (const auto *arg = 395 args.getLastArg(clang::driver::options::OPT_ffixed_form, 396 clang::driver::options::OPT_ffree_form)) { 397 opts.fortranForm = 398 arg->getOption().matches(clang::driver::options::OPT_ffixed_form) 399 ? FortranForm::FixedForm 400 : FortranForm::FreeForm; 401 } 402 403 // Set fixedFormColumns based on -ffixed-line-length=<value> 404 if (const auto *arg = 405 args.getLastArg(clang::driver::options::OPT_ffixed_line_length_EQ)) { 406 llvm::StringRef argValue = llvm::StringRef(arg->getValue()); 407 std::int64_t columns = -1; 408 if (argValue == "none") { 409 columns = 0; 410 } else if (argValue.getAsInteger(/*Radix=*/10, columns)) { 411 columns = -1; 412 } 413 if (columns < 0) { 414 diags.Report(clang::diag::err_drv_negative_columns) 415 << arg->getOption().getName() << arg->getValue(); 416 } else if (columns == 0) { 417 opts.fixedFormColumns = 1000000; 418 } else if (columns < 7) { 419 diags.Report(clang::diag::err_drv_small_columns) 420 << arg->getOption().getName() << arg->getValue() << "7"; 421 } else { 422 opts.fixedFormColumns = columns; 423 } 424 } 425 426 // Set conversion based on -fconvert=<value> 427 if (const auto *arg = 428 args.getLastArg(clang::driver::options::OPT_fconvert_EQ)) { 429 const char *argValue = arg->getValue(); 430 if (auto convert = parseConvertArg(argValue)) 431 opts.envDefaults.push_back({"FORT_CONVERT", *convert}); 432 else 433 diags.Report(clang::diag::err_drv_invalid_value) 434 << arg->getAsString(args) << argValue; 435 } 436 437 // -f{no-}implicit-none 438 opts.features.Enable( 439 Fortran::common::LanguageFeature::ImplicitNoneTypeAlways, 440 args.hasFlag(clang::driver::options::OPT_fimplicit_none, 441 clang::driver::options::OPT_fno_implicit_none, false)); 442 443 // -f{no-}backslash 444 opts.features.Enable(Fortran::common::LanguageFeature::BackslashEscapes, 445 args.hasFlag(clang::driver::options::OPT_fbackslash, 446 clang::driver::options::OPT_fno_backslash, 447 false)); 448 449 // -f{no-}logical-abbreviations 450 opts.features.Enable( 451 Fortran::common::LanguageFeature::LogicalAbbreviations, 452 args.hasFlag(clang::driver::options::OPT_flogical_abbreviations, 453 clang::driver::options::OPT_fno_logical_abbreviations, 454 false)); 455 456 // -f{no-}xor-operator 457 opts.features.Enable( 458 Fortran::common::LanguageFeature::XOROperator, 459 args.hasFlag(clang::driver::options::OPT_fxor_operator, 460 clang::driver::options::OPT_fno_xor_operator, false)); 461 462 // -fno-automatic 463 if (args.hasArg(clang::driver::options::OPT_fno_automatic)) { 464 opts.features.Enable(Fortran::common::LanguageFeature::DefaultSave); 465 } 466 467 if (args.hasArg( 468 clang::driver::options::OPT_falternative_parameter_statement)) { 469 opts.features.Enable(Fortran::common::LanguageFeature::OldStyleParameter); 470 } 471 if (const llvm::opt::Arg *arg = 472 args.getLastArg(clang::driver::options::OPT_finput_charset_EQ)) { 473 llvm::StringRef argValue = arg->getValue(); 474 if (argValue == "utf-8") { 475 opts.encoding = Fortran::parser::Encoding::UTF_8; 476 } else if (argValue == "latin-1") { 477 opts.encoding = Fortran::parser::Encoding::LATIN_1; 478 } else { 479 diags.Report(clang::diag::err_drv_invalid_value) 480 << arg->getAsString(args) << argValue; 481 } 482 } 483 484 setUpFrontendBasedOnAction(opts); 485 opts.dashX = dashX; 486 487 return diags.getNumErrors() == numErrorsBefore; 488 } 489 490 // Generate the path to look for intrinsic modules 491 static std::string getIntrinsicDir() { 492 // TODO: Find a system independent API 493 llvm::SmallString<128> driverPath; 494 driverPath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 495 llvm::sys::path::remove_filename(driverPath); 496 driverPath.append("/../include/flang/"); 497 return std::string(driverPath); 498 } 499 500 // Generate the path to look for OpenMP headers 501 static std::string getOpenMPHeadersDir() { 502 llvm::SmallString<128> includePath; 503 includePath.assign(llvm::sys::fs::getMainExecutable(nullptr, nullptr)); 504 llvm::sys::path::remove_filename(includePath); 505 includePath.append("/../include/flang/OpenMP/"); 506 return std::string(includePath); 507 } 508 509 /// Parses all preprocessor input arguments and populates the preprocessor 510 /// options accordingly. 511 /// 512 /// \param [in] opts The preprocessor options instance 513 /// \param [out] args The list of input arguments 514 static void parsePreprocessorArgs(Fortran::frontend::PreprocessorOptions &opts, 515 llvm::opt::ArgList &args) { 516 // Add macros from the command line. 517 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_D, 518 clang::driver::options::OPT_U)) { 519 if (currentArg->getOption().matches(clang::driver::options::OPT_D)) { 520 opts.addMacroDef(currentArg->getValue()); 521 } else { 522 opts.addMacroUndef(currentArg->getValue()); 523 } 524 } 525 526 // Add the ordered list of -I's. 527 for (const auto *currentArg : args.filtered(clang::driver::options::OPT_I)) 528 opts.searchDirectoriesFromDashI.emplace_back(currentArg->getValue()); 529 530 // Prepend the ordered list of -intrinsic-modules-path 531 // to the default location to search. 532 for (const auto *currentArg : 533 args.filtered(clang::driver::options::OPT_fintrinsic_modules_path)) 534 opts.searchDirectoriesFromIntrModPath.emplace_back(currentArg->getValue()); 535 536 // -cpp/-nocpp 537 if (const auto *currentArg = args.getLastArg( 538 clang::driver::options::OPT_cpp, clang::driver::options::OPT_nocpp)) 539 opts.macrosFlag = 540 (currentArg->getOption().matches(clang::driver::options::OPT_cpp)) 541 ? PPMacrosFlag::Include 542 : PPMacrosFlag::Exclude; 543 544 opts.noReformat = args.hasArg(clang::driver::options::OPT_fno_reformat); 545 opts.noLineDirectives = args.hasArg(clang::driver::options::OPT_P); 546 } 547 548 /// Parses all semantic related arguments and populates the variables 549 /// options accordingly. Returns false if new errors are generated. 550 static bool parseSemaArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 551 clang::DiagnosticsEngine &diags) { 552 unsigned numErrorsBefore = diags.getNumErrors(); 553 554 // -J/module-dir option 555 auto moduleDirList = 556 args.getAllArgValues(clang::driver::options::OPT_module_dir); 557 // User can only specify -J/-module-dir once 558 // https://gcc.gnu.org/onlinedocs/gfortran/Directory-Options.html 559 if (moduleDirList.size() > 1) { 560 const unsigned diagID = 561 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 562 "Only one '-module-dir/-J' option allowed"); 563 diags.Report(diagID); 564 } 565 if (moduleDirList.size() == 1) 566 res.setModuleDir(moduleDirList[0]); 567 568 // -fdebug-module-writer option 569 if (args.hasArg(clang::driver::options::OPT_fdebug_module_writer)) { 570 res.setDebugModuleDir(true); 571 } 572 573 // -module-suffix 574 if (const auto *moduleSuffix = 575 args.getLastArg(clang::driver::options::OPT_module_suffix)) { 576 res.setModuleFileSuffix(moduleSuffix->getValue()); 577 } 578 579 // -f{no-}analyzed-objects-for-unparse 580 res.setUseAnalyzedObjectsForUnparse(args.hasFlag( 581 clang::driver::options::OPT_fanalyzed_objects_for_unparse, 582 clang::driver::options::OPT_fno_analyzed_objects_for_unparse, true)); 583 584 return diags.getNumErrors() == numErrorsBefore; 585 } 586 587 /// Parses all diagnostics related arguments and populates the variables 588 /// options accordingly. Returns false if new errors are generated. 589 static bool parseDiagArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 590 clang::DiagnosticsEngine &diags) { 591 unsigned numErrorsBefore = diags.getNumErrors(); 592 593 // -Werror option 594 // TODO: Currently throws a Diagnostic for anything other than -W<error>, 595 // this has to change when other -W<opt>'s are supported. 596 if (args.hasArg(clang::driver::options::OPT_W_Joined)) { 597 if (args.getLastArgValue(clang::driver::options::OPT_W_Joined) 598 .equals("error")) { 599 res.setWarnAsErr(true); 600 } else { 601 const unsigned diagID = 602 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 603 "Only `-Werror` is supported currently."); 604 diags.Report(diagID); 605 } 606 } 607 608 // Default to off for `flang-new -fc1`. 609 res.getFrontendOpts().showColors = 610 parseShowColorsArgs(args, /*defaultDiagColor=*/false); 611 612 return diags.getNumErrors() == numErrorsBefore; 613 } 614 615 /// Parses all Dialect related arguments and populates the variables 616 /// options accordingly. Returns false if new errors are generated. 617 static bool parseDialectArgs(CompilerInvocation &res, llvm::opt::ArgList &args, 618 clang::DiagnosticsEngine &diags) { 619 unsigned numErrorsBefore = diags.getNumErrors(); 620 621 // -fdefault* family 622 if (args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 623 res.getDefaultKinds().set_defaultRealKind(8); 624 res.getDefaultKinds().set_doublePrecisionKind(16); 625 } 626 if (args.hasArg(clang::driver::options::OPT_fdefault_integer_8)) { 627 res.getDefaultKinds().set_defaultIntegerKind(8); 628 res.getDefaultKinds().set_subscriptIntegerKind(8); 629 res.getDefaultKinds().set_sizeIntegerKind(8); 630 } 631 if (args.hasArg(clang::driver::options::OPT_fdefault_double_8)) { 632 if (!args.hasArg(clang::driver::options::OPT_fdefault_real_8)) { 633 // -fdefault-double-8 has to be used with -fdefault-real-8 634 // to be compatible with gfortran 635 const unsigned diagID = diags.getCustomDiagID( 636 clang::DiagnosticsEngine::Error, 637 "Use of `-fdefault-double-8` requires `-fdefault-real-8`"); 638 diags.Report(diagID); 639 } 640 // https://gcc.gnu.org/onlinedocs/gfortran/Fortran-Dialect-Options.html 641 res.getDefaultKinds().set_doublePrecisionKind(8); 642 } 643 if (args.hasArg(clang::driver::options::OPT_flarge_sizes)) 644 res.getDefaultKinds().set_sizeIntegerKind(8); 645 646 // -fopenmp and -fopenacc 647 if (args.hasArg(clang::driver::options::OPT_fopenacc)) { 648 res.getFrontendOpts().features.Enable( 649 Fortran::common::LanguageFeature::OpenACC); 650 } 651 if (args.hasArg(clang::driver::options::OPT_fopenmp)) { 652 res.getFrontendOpts().features.Enable( 653 Fortran::common::LanguageFeature::OpenMP); 654 } 655 656 // -pedantic 657 if (args.hasArg(clang::driver::options::OPT_pedantic)) { 658 res.setEnableConformanceChecks(); 659 } 660 // -std=f2018 (currently this implies -pedantic) 661 // TODO: Set proper options when more fortran standards 662 // are supported. 663 if (args.hasArg(clang::driver::options::OPT_std_EQ)) { 664 auto standard = args.getLastArgValue(clang::driver::options::OPT_std_EQ); 665 // We only allow f2018 as the given standard 666 if (standard.equals("f2018")) { 667 res.setEnableConformanceChecks(); 668 } else { 669 const unsigned diagID = 670 diags.getCustomDiagID(clang::DiagnosticsEngine::Error, 671 "Only -std=f2018 is allowed currently."); 672 diags.Report(diagID); 673 } 674 } 675 return diags.getNumErrors() == numErrorsBefore; 676 } 677 678 /// Parses all floating point related arguments and populates the 679 /// CompilerInvocation accordingly. 680 /// Returns false if new errors are generated. 681 /// 682 /// \param [out] invoc Stores the processed arguments 683 /// \param [in] args The compiler invocation arguments to parse 684 /// \param [out] diags DiagnosticsEngine to report erros with 685 static bool parseFloatingPointArgs(CompilerInvocation &invoc, 686 llvm::opt::ArgList &args, 687 clang::DiagnosticsEngine &diags) { 688 LangOptions &opts = invoc.getLangOpts(); 689 690 if (const llvm::opt::Arg *a = 691 args.getLastArg(clang::driver::options::OPT_ffp_contract)) { 692 const llvm::StringRef val = a->getValue(); 693 enum LangOptions::FPModeKind fpContractMode; 694 695 if (val == "off") 696 fpContractMode = LangOptions::FPM_Off; 697 else if (val == "fast") 698 fpContractMode = LangOptions::FPM_Fast; 699 else { 700 diags.Report(clang::diag::err_drv_unsupported_option_argument) 701 << a->getSpelling() << val; 702 return false; 703 } 704 705 opts.setFPContractMode(fpContractMode); 706 } 707 708 if (args.getLastArg(clang::driver::options::OPT_menable_no_infinities)) { 709 opts.NoHonorInfs = true; 710 } 711 712 if (args.getLastArg(clang::driver::options::OPT_menable_no_nans)) { 713 opts.NoHonorNaNs = true; 714 } 715 716 if (args.getLastArg(clang::driver::options::OPT_fapprox_func)) { 717 opts.ApproxFunc = true; 718 } 719 720 if (args.getLastArg(clang::driver::options::OPT_fno_signed_zeros)) { 721 opts.NoSignedZeros = true; 722 } 723 724 if (args.getLastArg(clang::driver::options::OPT_mreassociate)) { 725 opts.AssociativeMath = true; 726 } 727 728 if (args.getLastArg(clang::driver::options::OPT_freciprocal_math)) { 729 opts.ReciprocalMath = true; 730 } 731 732 if (args.getLastArg(clang::driver::options::OPT_ffast_math)) { 733 opts.NoHonorInfs = true; 734 opts.NoHonorNaNs = true; 735 opts.AssociativeMath = true; 736 opts.ReciprocalMath = true; 737 opts.ApproxFunc = true; 738 opts.NoSignedZeros = true; 739 opts.setFPContractMode(LangOptions::FPM_Fast); 740 } 741 742 return true; 743 } 744 745 bool CompilerInvocation::createFromArgs( 746 CompilerInvocation &res, llvm::ArrayRef<const char *> commandLineArgs, 747 clang::DiagnosticsEngine &diags) { 748 749 bool success = true; 750 751 // Set the default triple for this CompilerInvocation. This might be 752 // overridden by users with `-triple` (see the call to `ParseTargetArgs` 753 // below). 754 // NOTE: Like in Clang, it would be nice to use option marshalling 755 // for this so that the entire logic for setting-up the triple is in one 756 // place. 757 res.getTargetOpts().triple = 758 llvm::Triple::normalize(llvm::sys::getDefaultTargetTriple()); 759 760 // Parse the arguments 761 const llvm::opt::OptTable &opts = clang::driver::getDriverOptTable(); 762 const unsigned includedFlagsBitmask = clang::driver::options::FC1Option; 763 unsigned missingArgIndex, missingArgCount; 764 llvm::opt::InputArgList args = opts.ParseArgs( 765 commandLineArgs, missingArgIndex, missingArgCount, includedFlagsBitmask); 766 767 // Check for missing argument error. 768 if (missingArgCount) { 769 diags.Report(clang::diag::err_drv_missing_argument) 770 << args.getArgString(missingArgIndex) << missingArgCount; 771 success = false; 772 } 773 774 // Issue errors on unknown arguments 775 for (const auto *a : args.filtered(clang::driver::options::OPT_UNKNOWN)) { 776 auto argString = a->getAsString(args); 777 std::string nearest; 778 if (opts.findNearest(argString, nearest, includedFlagsBitmask) > 1) 779 diags.Report(clang::diag::err_drv_unknown_argument) << argString; 780 else 781 diags.Report(clang::diag::err_drv_unknown_argument_with_suggestion) 782 << argString << nearest; 783 success = false; 784 } 785 786 success &= parseFrontendArgs(res.getFrontendOpts(), args, diags); 787 parseTargetArgs(res.getTargetOpts(), args); 788 parsePreprocessorArgs(res.getPreprocessorOpts(), args); 789 parseCodeGenArgs(res.getCodeGenOpts(), args, diags); 790 success &= parseSemaArgs(res, args, diags); 791 success &= parseDialectArgs(res, args, diags); 792 success &= parseDiagArgs(res, args, diags); 793 res.frontendOpts.llvmArgs = 794 args.getAllArgValues(clang::driver::options::OPT_mllvm); 795 796 res.frontendOpts.mlirArgs = 797 args.getAllArgValues(clang::driver::options::OPT_mmlir); 798 799 success &= parseFloatingPointArgs(res, args, diags); 800 801 return success; 802 } 803 804 void CompilerInvocation::collectMacroDefinitions() { 805 auto &ppOpts = this->getPreprocessorOpts(); 806 807 for (unsigned i = 0, n = ppOpts.macros.size(); i != n; ++i) { 808 llvm::StringRef macro = ppOpts.macros[i].first; 809 bool isUndef = ppOpts.macros[i].second; 810 811 std::pair<llvm::StringRef, llvm::StringRef> macroPair = macro.split('='); 812 llvm::StringRef macroName = macroPair.first; 813 llvm::StringRef macroBody = macroPair.second; 814 815 // For an #undef'd macro, we only care about the name. 816 if (isUndef) { 817 parserOpts.predefinitions.emplace_back(macroName.str(), 818 std::optional<std::string>{}); 819 continue; 820 } 821 822 // For a #define'd macro, figure out the actual definition. 823 if (macroName.size() == macro.size()) 824 macroBody = "1"; 825 else { 826 // Note: GCC drops anything following an end-of-line character. 827 llvm::StringRef::size_type end = macroBody.find_first_of("\n\r"); 828 macroBody = macroBody.substr(0, end); 829 } 830 parserOpts.predefinitions.emplace_back( 831 macroName, std::optional<std::string>(macroBody.str())); 832 } 833 } 834 835 void CompilerInvocation::setDefaultFortranOpts() { 836 auto &fortranOptions = getFortranOpts(); 837 838 std::vector<std::string> searchDirectories{"."s}; 839 fortranOptions.searchDirectories = searchDirectories; 840 841 // Add the location of omp_lib.h to the search directories. Currently this is 842 // identical to the modules' directory. 843 fortranOptions.searchDirectories.emplace_back(getOpenMPHeadersDir()); 844 845 fortranOptions.isFixedForm = false; 846 } 847 848 // TODO: When expanding this method, consider creating a dedicated API for 849 // this. Also at some point we will need to differentiate between different 850 // targets and add dedicated predefines for each. 851 void CompilerInvocation::setDefaultPredefinitions() { 852 auto &fortranOptions = getFortranOpts(); 853 const auto &frontendOptions = getFrontendOpts(); 854 855 // Populate the macro list with version numbers and other predefinitions. 856 fortranOptions.predefinitions.emplace_back("__flang__", "1"); 857 fortranOptions.predefinitions.emplace_back("__flang_major__", 858 FLANG_VERSION_MAJOR_STRING); 859 fortranOptions.predefinitions.emplace_back("__flang_minor__", 860 FLANG_VERSION_MINOR_STRING); 861 fortranOptions.predefinitions.emplace_back("__flang_patchlevel__", 862 FLANG_VERSION_PATCHLEVEL_STRING); 863 864 // Add predefinitions based on extensions enabled 865 if (frontendOptions.features.IsEnabled( 866 Fortran::common::LanguageFeature::OpenACC)) { 867 fortranOptions.predefinitions.emplace_back("_OPENACC", "202011"); 868 } 869 if (frontendOptions.features.IsEnabled( 870 Fortran::common::LanguageFeature::OpenMP)) { 871 fortranOptions.predefinitions.emplace_back("_OPENMP", "201511"); 872 } 873 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 874 if (targetTriple.getArch() == llvm::Triple::ArchType::x86_64) { 875 fortranOptions.predefinitions.emplace_back("__x86_64__", "1"); 876 fortranOptions.predefinitions.emplace_back("__x86_64", "1"); 877 } 878 } 879 880 void CompilerInvocation::setFortranOpts() { 881 auto &fortranOptions = getFortranOpts(); 882 const auto &frontendOptions = getFrontendOpts(); 883 const auto &preprocessorOptions = getPreprocessorOpts(); 884 auto &moduleDirJ = getModuleDir(); 885 886 if (frontendOptions.fortranForm != FortranForm::Unknown) { 887 fortranOptions.isFixedForm = 888 frontendOptions.fortranForm == FortranForm::FixedForm; 889 } 890 fortranOptions.fixedFormColumns = frontendOptions.fixedFormColumns; 891 892 fortranOptions.features = frontendOptions.features; 893 fortranOptions.encoding = frontendOptions.encoding; 894 895 // Adding search directories specified by -I 896 fortranOptions.searchDirectories.insert( 897 fortranOptions.searchDirectories.end(), 898 preprocessorOptions.searchDirectoriesFromDashI.begin(), 899 preprocessorOptions.searchDirectoriesFromDashI.end()); 900 901 // Add the ordered list of -intrinsic-modules-path 902 fortranOptions.searchDirectories.insert( 903 fortranOptions.searchDirectories.end(), 904 preprocessorOptions.searchDirectoriesFromIntrModPath.begin(), 905 preprocessorOptions.searchDirectoriesFromIntrModPath.end()); 906 907 // Add the default intrinsic module directory 908 fortranOptions.intrinsicModuleDirectories.emplace_back(getIntrinsicDir()); 909 910 // Add the directory supplied through -J/-module-dir to the list of search 911 // directories 912 if (moduleDirJ != ".") 913 fortranOptions.searchDirectories.emplace_back(moduleDirJ); 914 915 if (frontendOptions.instrumentedParse) 916 fortranOptions.instrumentedParse = true; 917 918 if (frontendOptions.showColors) 919 fortranOptions.showColors = true; 920 921 if (frontendOptions.needProvenanceRangeToCharBlockMappings) 922 fortranOptions.needProvenanceRangeToCharBlockMappings = true; 923 924 if (getEnableConformanceChecks()) { 925 fortranOptions.features.WarnOnAllNonstandard(); 926 } 927 } 928 929 void CompilerInvocation::setSemanticsOpts( 930 Fortran::parser::AllCookedSources &allCookedSources) { 931 auto &fortranOptions = getFortranOpts(); 932 933 semanticsContext = std::make_unique<semantics::SemanticsContext>( 934 getDefaultKinds(), fortranOptions.features, allCookedSources); 935 936 semanticsContext->set_moduleDirectory(getModuleDir()) 937 .set_searchDirectories(fortranOptions.searchDirectories) 938 .set_intrinsicModuleDirectories(fortranOptions.intrinsicModuleDirectories) 939 .set_warnOnNonstandardUsage(getEnableConformanceChecks()) 940 .set_warningsAreErrors(getWarnAsErr()) 941 .set_moduleFileSuffix(getModuleFileSuffix()); 942 943 llvm::Triple targetTriple{llvm::Triple(this->targetOpts.triple)}; 944 // FIXME: Handle real(3) ? 945 if (targetTriple.getArch() != llvm::Triple::ArchType::x86_64) { 946 semanticsContext->targetCharacteristics().DisableType( 947 Fortran::common::TypeCategory::Real, /*kind=*/10); 948 } 949 } 950 951 /// Set \p loweringOptions controlling lowering behavior based 952 /// on the \p optimizationLevel. 953 void CompilerInvocation::setLoweringOptions() { 954 const CodeGenOptions &codegenOpts = getCodeGenOpts(); 955 956 // Lower TRANSPOSE as a runtime call under -O0. 957 loweringOpts.setOptimizeTranspose(codegenOpts.OptimizationLevel > 0); 958 959 const LangOptions &langOptions = getLangOpts(); 960 Fortran::common::MathOptionsBase &mathOpts = loweringOpts.getMathOptions(); 961 // TODO: when LangOptions are finalized, we can represent 962 // the math related options using Fortran::commmon::MathOptionsBase, 963 // so that we can just copy it into LoweringOptions. 964 mathOpts 965 .setFPContractEnabled(langOptions.getFPContractMode() == 966 LangOptions::FPM_Fast) 967 .setNoHonorInfs(langOptions.NoHonorInfs) 968 .setNoHonorNaNs(langOptions.NoHonorNaNs) 969 .setApproxFunc(langOptions.ApproxFunc) 970 .setNoSignedZeros(langOptions.NoSignedZeros) 971 .setAssociativeMath(langOptions.AssociativeMath) 972 .setReciprocalMath(langOptions.ReciprocalMath); 973 } 974