1 //===--- CompilerInvocation.cpp -------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 10 #include "TestModuleFileExtension.h" 11 #include "clang/Frontend/CompilerInvocation.h" 12 #include "clang/Basic/FileManager.h" 13 #include "clang/Basic/Version.h" 14 #include "clang/Config/config.h" 15 #include "clang/Driver/DriverDiagnostic.h" 16 #include "clang/Driver/Options.h" 17 #include "clang/Driver/Util.h" 18 #include "clang/Frontend/FrontendDiagnostic.h" 19 #include "clang/Frontend/LangStandard.h" 20 #include "clang/Frontend/Utils.h" 21 #include "clang/Lex/HeaderSearchOptions.h" 22 #include "clang/Serialization/ASTReader.h" 23 #include "clang/Serialization/ModuleFileExtension.h" 24 #include "llvm/ADT/Hashing.h" 25 #include "llvm/ADT/STLExtras.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/StringExtras.h" 28 #include "llvm/ADT/StringSwitch.h" 29 #include "llvm/ADT/Triple.h" 30 #include "llvm/Linker/Linker.h" 31 #include "llvm/Option/Arg.h" 32 #include "llvm/Option/ArgList.h" 33 #include "llvm/Option/OptTable.h" 34 #include "llvm/Option/Option.h" 35 #include "llvm/Support/CodeGen.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/FileSystem.h" 38 #include "llvm/Support/Host.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/Process.h" 41 #include "llvm/Target/TargetOptions.h" 42 #include <atomic> 43 #include <memory> 44 #include <sys/stat.h> 45 #include <system_error> 46 using namespace clang; 47 48 //===----------------------------------------------------------------------===// 49 // Initialization. 50 //===----------------------------------------------------------------------===// 51 52 CompilerInvocationBase::CompilerInvocationBase() 53 : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()), 54 DiagnosticOpts(new DiagnosticOptions()), 55 HeaderSearchOpts(new HeaderSearchOptions()), 56 PreprocessorOpts(new PreprocessorOptions()) {} 57 58 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X) 59 : RefCountedBase<CompilerInvocation>(), 60 LangOpts(new LangOptions(*X.getLangOpts())), 61 TargetOpts(new TargetOptions(X.getTargetOpts())), 62 DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())), 63 HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())), 64 PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {} 65 66 CompilerInvocationBase::~CompilerInvocationBase() {} 67 68 //===----------------------------------------------------------------------===// 69 // Deserialization (from args) 70 //===----------------------------------------------------------------------===// 71 72 using namespace clang::driver; 73 using namespace clang::driver::options; 74 using namespace llvm::opt; 75 76 // 77 78 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK, 79 DiagnosticsEngine &Diags) { 80 unsigned DefaultOpt = 0; 81 if (IK == IK_OpenCL && !Args.hasArg(OPT_cl_opt_disable)) 82 DefaultOpt = 2; 83 84 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 85 if (A->getOption().matches(options::OPT_O0)) 86 return 0; 87 88 if (A->getOption().matches(options::OPT_Ofast)) 89 return 3; 90 91 assert (A->getOption().matches(options::OPT_O)); 92 93 StringRef S(A->getValue()); 94 if (S == "s" || S == "z" || S.empty()) 95 return 2; 96 97 return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags); 98 } 99 100 return DefaultOpt; 101 } 102 103 static unsigned getOptimizationLevelSize(ArgList &Args) { 104 if (Arg *A = Args.getLastArg(options::OPT_O_Group)) { 105 if (A->getOption().matches(options::OPT_O)) { 106 switch (A->getValue()[0]) { 107 default: 108 return 0; 109 case 's': 110 return 1; 111 case 'z': 112 return 2; 113 } 114 } 115 } 116 return 0; 117 } 118 119 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group, 120 OptSpecifier GroupWithValue, 121 std::vector<std::string> &Diagnostics) { 122 for (Arg *A : Args.filtered(Group)) { 123 if (A->getOption().getKind() == Option::FlagClass) { 124 // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add 125 // its name (minus the "W" or "R" at the beginning) to the warning list. 126 Diagnostics.push_back(A->getOption().getName().drop_front(1)); 127 } else if (A->getOption().matches(GroupWithValue)) { 128 // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group. 129 Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-")); 130 } else { 131 // Otherwise, add its value (for OPT_W_Joined and similar). 132 for (const char *Arg : A->getValues()) 133 Diagnostics.emplace_back(Arg); 134 } 135 } 136 } 137 138 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args, 139 DiagnosticsEngine &Diags) { 140 using namespace options; 141 bool Success = true; 142 if (Arg *A = Args.getLastArg(OPT_analyzer_store)) { 143 StringRef Name = A->getValue(); 144 AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name) 145 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \ 146 .Case(CMDFLAG, NAME##Model) 147 #include "clang/StaticAnalyzer/Core/Analyses.def" 148 .Default(NumStores); 149 if (Value == NumStores) { 150 Diags.Report(diag::err_drv_invalid_value) 151 << A->getAsString(Args) << Name; 152 Success = false; 153 } else { 154 Opts.AnalysisStoreOpt = Value; 155 } 156 } 157 158 if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) { 159 StringRef Name = A->getValue(); 160 AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name) 161 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \ 162 .Case(CMDFLAG, NAME##Model) 163 #include "clang/StaticAnalyzer/Core/Analyses.def" 164 .Default(NumConstraints); 165 if (Value == NumConstraints) { 166 Diags.Report(diag::err_drv_invalid_value) 167 << A->getAsString(Args) << Name; 168 Success = false; 169 } else { 170 Opts.AnalysisConstraintsOpt = Value; 171 } 172 } 173 174 if (Arg *A = Args.getLastArg(OPT_analyzer_output)) { 175 StringRef Name = A->getValue(); 176 AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name) 177 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \ 178 .Case(CMDFLAG, PD_##NAME) 179 #include "clang/StaticAnalyzer/Core/Analyses.def" 180 .Default(NUM_ANALYSIS_DIAG_CLIENTS); 181 if (Value == NUM_ANALYSIS_DIAG_CLIENTS) { 182 Diags.Report(diag::err_drv_invalid_value) 183 << A->getAsString(Args) << Name; 184 Success = false; 185 } else { 186 Opts.AnalysisDiagOpt = Value; 187 } 188 } 189 190 if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) { 191 StringRef Name = A->getValue(); 192 AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name) 193 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \ 194 .Case(CMDFLAG, NAME) 195 #include "clang/StaticAnalyzer/Core/Analyses.def" 196 .Default(NumPurgeModes); 197 if (Value == NumPurgeModes) { 198 Diags.Report(diag::err_drv_invalid_value) 199 << A->getAsString(Args) << Name; 200 Success = false; 201 } else { 202 Opts.AnalysisPurgeOpt = Value; 203 } 204 } 205 206 if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) { 207 StringRef Name = A->getValue(); 208 AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name) 209 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \ 210 .Case(CMDFLAG, NAME) 211 #include "clang/StaticAnalyzer/Core/Analyses.def" 212 .Default(NumInliningModes); 213 if (Value == NumInliningModes) { 214 Diags.Report(diag::err_drv_invalid_value) 215 << A->getAsString(Args) << Name; 216 Success = false; 217 } else { 218 Opts.InliningMode = Value; 219 } 220 } 221 222 Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help); 223 Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks); 224 225 Opts.visualizeExplodedGraphWithGraphViz = 226 Args.hasArg(OPT_analyzer_viz_egraph_graphviz); 227 Opts.visualizeExplodedGraphWithUbiGraph = 228 Args.hasArg(OPT_analyzer_viz_egraph_ubigraph); 229 Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted); 230 Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers); 231 Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress); 232 Opts.AnalyzeNestedBlocks = 233 Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks); 234 Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume); 235 Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function); 236 Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG); 237 Opts.TrimGraph = Args.hasArg(OPT_trim_egraph); 238 Opts.maxBlockVisitOnPath = 239 getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags); 240 Opts.PrintStats = Args.hasArg(OPT_analyzer_stats); 241 Opts.InlineMaxStackDepth = 242 getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth, 243 Opts.InlineMaxStackDepth, Diags); 244 245 Opts.CheckersControlList.clear(); 246 for (const Arg *A : 247 Args.filtered(OPT_analyzer_checker, OPT_analyzer_disable_checker)) { 248 A->claim(); 249 bool enable = (A->getOption().getID() == OPT_analyzer_checker); 250 // We can have a list of comma separated checker names, e.g: 251 // '-analyzer-checker=cocoa,unix' 252 StringRef checkerList = A->getValue(); 253 SmallVector<StringRef, 4> checkers; 254 checkerList.split(checkers, ","); 255 for (StringRef checker : checkers) 256 Opts.CheckersControlList.emplace_back(checker, enable); 257 } 258 259 // Go through the analyzer configuration options. 260 for (const Arg *A : Args.filtered(OPT_analyzer_config)) { 261 A->claim(); 262 // We can have a list of comma separated config names, e.g: 263 // '-analyzer-config key1=val1,key2=val2' 264 StringRef configList = A->getValue(); 265 SmallVector<StringRef, 4> configVals; 266 configList.split(configVals, ","); 267 for (unsigned i = 0, e = configVals.size(); i != e; ++i) { 268 StringRef key, val; 269 std::tie(key, val) = configVals[i].split("="); 270 if (val.empty()) { 271 Diags.Report(SourceLocation(), 272 diag::err_analyzer_config_no_value) << configVals[i]; 273 Success = false; 274 break; 275 } 276 if (val.find('=') != StringRef::npos) { 277 Diags.Report(SourceLocation(), 278 diag::err_analyzer_config_multiple_values) 279 << configVals[i]; 280 Success = false; 281 break; 282 } 283 Opts.Config[key] = val; 284 } 285 } 286 287 return Success; 288 } 289 290 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) { 291 Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error); 292 Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal); 293 return true; 294 } 295 296 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) { 297 Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands); 298 Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments); 299 } 300 301 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) { 302 if (Arg *A = Args.getLastArg(OPT_mcode_model)) { 303 StringRef Value = A->getValue(); 304 if (Value == "small" || Value == "kernel" || Value == "medium" || 305 Value == "large") 306 return Value; 307 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value; 308 } 309 return "default"; 310 } 311 312 /// \brief Create a new Regex instance out of the string value in \p RpassArg. 313 /// It returns a pointer to the newly generated Regex instance. 314 static std::shared_ptr<llvm::Regex> 315 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args, 316 Arg *RpassArg) { 317 StringRef Val = RpassArg->getValue(); 318 std::string RegexError; 319 std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val); 320 if (!Pattern->isValid(RegexError)) { 321 Diags.Report(diag::err_drv_optimization_remark_pattern) 322 << RegexError << RpassArg->getAsString(Args); 323 Pattern.reset(); 324 } 325 return Pattern; 326 } 327 328 static bool parseDiagnosticLevelMask(StringRef FlagName, 329 const std::vector<std::string> &Levels, 330 DiagnosticsEngine *Diags, 331 DiagnosticLevelMask &M) { 332 bool Success = true; 333 for (const auto &Level : Levels) { 334 DiagnosticLevelMask const PM = 335 llvm::StringSwitch<DiagnosticLevelMask>(Level) 336 .Case("note", DiagnosticLevelMask::Note) 337 .Case("remark", DiagnosticLevelMask::Remark) 338 .Case("warning", DiagnosticLevelMask::Warning) 339 .Case("error", DiagnosticLevelMask::Error) 340 .Default(DiagnosticLevelMask::None); 341 if (PM == DiagnosticLevelMask::None) { 342 Success = false; 343 if (Diags) 344 Diags->Report(diag::err_drv_invalid_value) << FlagName << Level; 345 } 346 M = M | PM; 347 } 348 return Success; 349 } 350 351 static void parseSanitizerKinds(StringRef FlagName, 352 const std::vector<std::string> &Sanitizers, 353 DiagnosticsEngine &Diags, SanitizerSet &S) { 354 for (const auto &Sanitizer : Sanitizers) { 355 SanitizerMask K = parseSanitizerValue(Sanitizer, /*AllowGroups=*/false); 356 if (K == 0) 357 Diags.Report(diag::err_drv_invalid_value) << FlagName << Sanitizer; 358 else 359 S.set(K, true); 360 } 361 } 362 363 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK, 364 DiagnosticsEngine &Diags, 365 const TargetOptions &TargetOpts) { 366 using namespace options; 367 bool Success = true; 368 llvm::Triple Triple = llvm::Triple(TargetOpts.Triple); 369 370 unsigned OptimizationLevel = getOptimizationLevel(Args, IK, Diags); 371 // TODO: This could be done in Driver 372 unsigned MaxOptLevel = 3; 373 if (OptimizationLevel > MaxOptLevel) { 374 // If the optimization level is not supported, fall back on the default 375 // optimization 376 Diags.Report(diag::warn_drv_optimization_value) 377 << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel; 378 OptimizationLevel = MaxOptLevel; 379 } 380 Opts.OptimizationLevel = OptimizationLevel; 381 382 // We must always run at least the always inlining pass. 383 Opts.setInlining( 384 (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalInlining 385 : CodeGenOptions::OnlyAlwaysInlining); 386 // -fno-inline-functions overrides OptimizationLevel > 1. 387 Opts.NoInline = Args.hasArg(OPT_fno_inline); 388 Opts.setInlining(Args.hasArg(OPT_fno_inline_functions) ? 389 CodeGenOptions::OnlyAlwaysInlining : Opts.getInlining()); 390 391 if (Arg *A = Args.getLastArg(OPT_fveclib)) { 392 StringRef Name = A->getValue(); 393 if (Name == "Accelerate") 394 Opts.setVecLib(CodeGenOptions::Accelerate); 395 else if (Name == "none") 396 Opts.setVecLib(CodeGenOptions::NoLibrary); 397 else 398 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 399 } 400 401 if (Arg *A = Args.getLastArg(OPT_debug_info_kind_EQ)) { 402 Opts.setDebugInfo( 403 llvm::StringSwitch<CodeGenOptions::DebugInfoKind>(A->getValue()) 404 .Case("line-tables-only", CodeGenOptions::DebugLineTablesOnly) 405 .Case("limited", CodeGenOptions::LimitedDebugInfo) 406 .Case("standalone", CodeGenOptions::FullDebugInfo)); 407 } 408 if (Arg *A = Args.getLastArg(OPT_debugger_tuning_EQ)) { 409 Opts.setDebuggerTuning( 410 llvm::StringSwitch<CodeGenOptions::DebuggerKind>(A->getValue()) 411 .Case("gdb", CodeGenOptions::DebuggerKindGDB) 412 .Case("lldb", CodeGenOptions::DebuggerKindLLDB) 413 .Case("sce", CodeGenOptions::DebuggerKindSCE)); 414 } 415 Opts.DwarfVersion = getLastArgIntValue(Args, OPT_dwarf_version_EQ, 0, Diags); 416 Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info); 417 Opts.EmitCodeView = Args.hasArg(OPT_gcodeview); 418 Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file); 419 Opts.DebugTypeExtRefs = Args.hasArg(OPT_dwarf_ext_refs); 420 if (Triple.isPS4CPU()) 421 Opts.DebugExplicitImport = true; 422 423 for (const auto &Arg : Args.getAllArgValues(OPT_fdebug_prefix_map_EQ)) 424 Opts.DebugPrefixMap.insert(StringRef(Arg).split('=')); 425 426 if (const Arg *A = 427 Args.getLastArg(OPT_emit_llvm_uselists, OPT_no_emit_llvm_uselists)) 428 Opts.EmitLLVMUseLists = A->getOption().getID() == OPT_emit_llvm_uselists; 429 430 Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns); 431 Opts.DisableLLVMPasses = Args.hasArg(OPT_disable_llvm_passes); 432 Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone); 433 Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables); 434 Opts.UseRegisterSizedBitfieldAccess = Args.hasArg( 435 OPT_fuse_register_sized_bitfield_access); 436 Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing); 437 Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa); 438 Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags); 439 Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants); 440 Opts.NoCommon = Args.hasArg(OPT_fno_common); 441 Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float); 442 Opts.OptimizeSize = getOptimizationLevelSize(Args); 443 Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) || 444 Args.hasArg(OPT_ffreestanding)); 445 Opts.UnrollLoops = 446 Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops, 447 (Opts.OptimizationLevel > 1 && !Opts.OptimizeSize)); 448 Opts.RerollLoops = Args.hasArg(OPT_freroll_loops); 449 450 Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as); 451 Opts.Autolink = !Args.hasArg(OPT_fno_autolink); 452 Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ); 453 Opts.ProfileInstrGenerate = Args.hasArg(OPT_fprofile_instr_generate) || 454 Args.hasArg(OPT_fprofile_instr_generate_EQ); 455 Opts.InstrProfileOutput = Args.getLastArgValue(OPT_fprofile_instr_generate_EQ); 456 Opts.InstrProfileInput = Args.getLastArgValue(OPT_fprofile_instr_use_EQ); 457 Opts.CoverageMapping = 458 Args.hasFlag(OPT_fcoverage_mapping, OPT_fno_coverage_mapping, false); 459 Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping); 460 Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose); 461 Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions); 462 Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit); 463 Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases); 464 Opts.CodeModel = getCodeModel(Args, Diags); 465 Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass); 466 Opts.DisableFPElim = 467 (Args.hasArg(OPT_mdisable_fp_elim) || Args.hasArg(OPT_pg)); 468 Opts.DisableFree = Args.hasArg(OPT_disable_free); 469 Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls); 470 Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi); 471 if (Arg *A = Args.getLastArg(OPT_meabi)) { 472 StringRef Value = A->getValue(); 473 llvm::EABI EABIVersion = llvm::StringSwitch<llvm::EABI>(Value) 474 .Case("default", llvm::EABI::Default) 475 .Case("4", llvm::EABI::EABI4) 476 .Case("5", llvm::EABI::EABI5) 477 .Case("gnu", llvm::EABI::GNU) 478 .Default(llvm::EABI::Unknown); 479 if (EABIVersion == llvm::EABI::Unknown) 480 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 481 << Value; 482 else 483 Opts.EABIVersion = Value; 484 } 485 Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable); 486 Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision); 487 Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) || 488 Args.hasArg(OPT_cl_finite_math_only) || 489 Args.hasArg(OPT_cl_fast_relaxed_math)); 490 Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) || 491 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 492 Args.hasArg(OPT_cl_finite_math_only) || 493 Args.hasArg(OPT_cl_fast_relaxed_math)); 494 Opts.NoSignedZeros = Args.hasArg(OPT_fno_signed_zeros); 495 Opts.ReciprocalMath = Args.hasArg(OPT_freciprocal_math); 496 Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss); 497 Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option); 498 Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags); 499 Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack); 500 Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings); 501 Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks); 502 Opts.RelaxAll = Args.hasArg(OPT_mrelax_all); 503 Opts.IncrementalLinkerCompatible = 504 Args.hasArg(OPT_mincremental_linker_compatible); 505 Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer); 506 Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels); 507 Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm); 508 Opts.SoftFloat = Args.hasArg(OPT_msoft_float); 509 Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums); 510 Opts.StrictVTablePointers = Args.hasArg(OPT_fstrict_vtable_pointers); 511 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) || 512 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 513 Args.hasArg(OPT_cl_fast_relaxed_math); 514 Opts.UnwindTables = Args.hasArg(OPT_munwind_tables); 515 Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic"); 516 Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix"); 517 if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single") 518 Diags.Report(diag::err_drv_invalid_value) 519 << Args.getLastArg(OPT_mthread_model)->getAsString(Args) 520 << Opts.ThreadModel; 521 Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ); 522 Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array); 523 524 Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections, 525 OPT_fno_function_sections, false); 526 Opts.DataSections = Args.hasFlag(OPT_fdata_sections, 527 OPT_fno_data_sections, false); 528 Opts.UniqueSectionNames = Args.hasFlag(OPT_funique_section_names, 529 OPT_fno_unique_section_names, true); 530 531 Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions); 532 533 Opts.PrepareForLTO = Args.hasArg(OPT_flto, OPT_flto_EQ); 534 const Arg *A = Args.getLastArg(OPT_flto, OPT_flto_EQ); 535 Opts.EmitFunctionSummary = A && A->containsValue("thin"); 536 if (Arg *A = Args.getLastArg(OPT_fthinlto_index_EQ)) { 537 if (IK != IK_LLVM_IR) 538 Diags.Report(diag::err_drv_argument_only_allowed_with) 539 << A->getAsString(Args) << "-x ir"; 540 Opts.ThinLTOIndexFile = Args.getLastArgValue(OPT_fthinlto_index_EQ); 541 } 542 543 Opts.MSVolatile = Args.hasArg(OPT_fms_volatile); 544 545 Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive); 546 Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops); 547 Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp); 548 549 Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name); 550 Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier); 551 552 Opts.DisableGCov = Args.hasArg(OPT_test_coverage); 553 Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data); 554 Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes); 555 if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) { 556 Opts.CoverageFile = Args.getLastArgValue(OPT_coverage_file); 557 Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum); 558 Opts.CoverageNoFunctionNamesInData = 559 Args.hasArg(OPT_coverage_no_function_names_in_data); 560 Opts.CoverageExitBlockBeforeBody = 561 Args.hasArg(OPT_coverage_exit_block_before_body); 562 if (Args.hasArg(OPT_coverage_version_EQ)) { 563 StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ); 564 if (CoverageVersion.size() != 4) { 565 Diags.Report(diag::err_drv_invalid_value) 566 << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args) 567 << CoverageVersion; 568 } else { 569 memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4); 570 } 571 } 572 } 573 574 Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions); 575 Opts.InstrumentForProfiling = Args.hasArg(OPT_pg); 576 Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info); 577 Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections); 578 Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir); 579 for (auto A : Args.filtered(OPT_mlink_bitcode_file, OPT_mlink_cuda_bitcode)) { 580 unsigned LinkFlags = llvm::Linker::Flags::None; 581 if (A->getOption().matches(OPT_mlink_cuda_bitcode)) 582 LinkFlags = llvm::Linker::Flags::LinkOnlyNeeded | 583 llvm::Linker::Flags::InternalizeLinkedSymbols; 584 Opts.LinkBitcodeFiles.push_back(std::make_pair(LinkFlags, A->getValue())); 585 } 586 Opts.SanitizeCoverageType = 587 getLastArgIntValue(Args, OPT_fsanitize_coverage_type, 0, Diags); 588 Opts.SanitizeCoverageIndirectCalls = 589 Args.hasArg(OPT_fsanitize_coverage_indirect_calls); 590 Opts.SanitizeCoverageTraceBB = Args.hasArg(OPT_fsanitize_coverage_trace_bb); 591 Opts.SanitizeCoverageTraceCmp = Args.hasArg(OPT_fsanitize_coverage_trace_cmp); 592 Opts.SanitizeCoverage8bitCounters = 593 Args.hasArg(OPT_fsanitize_coverage_8bit_counters); 594 Opts.SanitizeMemoryTrackOrigins = 595 getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags); 596 Opts.SanitizeMemoryUseAfterDtor = 597 Args.hasArg(OPT_fsanitize_memory_use_after_dtor); 598 Opts.SanitizeCfiCrossDso = Args.hasArg(OPT_fsanitize_cfi_cross_dso); 599 Opts.SSPBufferSize = 600 getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags); 601 Opts.StackRealignment = Args.hasArg(OPT_mstackrealign); 602 if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) { 603 StringRef Val = A->getValue(); 604 unsigned StackAlignment = Opts.StackAlignment; 605 Val.getAsInteger(10, StackAlignment); 606 Opts.StackAlignment = StackAlignment; 607 } 608 609 if (Arg *A = Args.getLastArg(OPT_mstack_probe_size)) { 610 StringRef Val = A->getValue(); 611 unsigned StackProbeSize = Opts.StackProbeSize; 612 Val.getAsInteger(0, StackProbeSize); 613 Opts.StackProbeSize = StackProbeSize; 614 } 615 616 if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) { 617 StringRef Name = A->getValue(); 618 unsigned Method = llvm::StringSwitch<unsigned>(Name) 619 .Case("legacy", CodeGenOptions::Legacy) 620 .Case("non-legacy", CodeGenOptions::NonLegacy) 621 .Case("mixed", CodeGenOptions::Mixed) 622 .Default(~0U); 623 if (Method == ~0U) { 624 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 625 Success = false; 626 } else { 627 Opts.setObjCDispatchMethod( 628 static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method)); 629 } 630 } 631 632 Opts.EmulatedTLS = 633 Args.hasFlag(OPT_femulated_tls, OPT_fno_emulated_tls, false); 634 635 if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) { 636 StringRef Name = A->getValue(); 637 unsigned Model = llvm::StringSwitch<unsigned>(Name) 638 .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel) 639 .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel) 640 .Case("initial-exec", CodeGenOptions::InitialExecTLSModel) 641 .Case("local-exec", CodeGenOptions::LocalExecTLSModel) 642 .Default(~0U); 643 if (Model == ~0U) { 644 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 645 Success = false; 646 } else { 647 Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model)); 648 } 649 } 650 651 if (Arg *A = Args.getLastArg(OPT_ffp_contract)) { 652 StringRef Val = A->getValue(); 653 if (Val == "fast") 654 Opts.setFPContractMode(CodeGenOptions::FPC_Fast); 655 else if (Val == "on") 656 Opts.setFPContractMode(CodeGenOptions::FPC_On); 657 else if (Val == "off") 658 Opts.setFPContractMode(CodeGenOptions::FPC_Off); 659 else 660 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val; 661 } 662 663 if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) { 664 if (A->getOption().matches(OPT_fpcc_struct_return)) { 665 Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack); 666 } else { 667 assert(A->getOption().matches(OPT_freg_struct_return)); 668 Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs); 669 } 670 } 671 672 Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib); 673 bool NeedLocTracking = false; 674 675 if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) { 676 Opts.OptimizationRemarkPattern = 677 GenerateOptimizationRemarkRegex(Diags, Args, A); 678 NeedLocTracking = true; 679 } 680 681 if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) { 682 Opts.OptimizationRemarkMissedPattern = 683 GenerateOptimizationRemarkRegex(Diags, Args, A); 684 NeedLocTracking = true; 685 } 686 687 if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) { 688 Opts.OptimizationRemarkAnalysisPattern = 689 GenerateOptimizationRemarkRegex(Diags, Args, A); 690 NeedLocTracking = true; 691 } 692 693 // If the user requested to use a sample profile for PGO, then the 694 // backend will need to track source location information so the profile 695 // can be incorporated into the IR. 696 if (!Opts.SampleProfileFile.empty()) 697 NeedLocTracking = true; 698 699 // If the user requested a flag that requires source locations available in 700 // the backend, make sure that the backend tracks source location information. 701 if (NeedLocTracking && Opts.getDebugInfo() == CodeGenOptions::NoDebugInfo) 702 Opts.setDebugInfo(CodeGenOptions::LocTrackingOnly); 703 704 Opts.RewriteMapFiles = Args.getAllArgValues(OPT_frewrite_map_file); 705 706 // Parse -fsanitize-recover= arguments. 707 // FIXME: Report unrecoverable sanitizers incorrectly specified here. 708 parseSanitizerKinds("-fsanitize-recover=", 709 Args.getAllArgValues(OPT_fsanitize_recover_EQ), Diags, 710 Opts.SanitizeRecover); 711 parseSanitizerKinds("-fsanitize-trap=", 712 Args.getAllArgValues(OPT_fsanitize_trap_EQ), Diags, 713 Opts.SanitizeTrap); 714 715 Opts.CudaGpuBinaryFileNames = 716 Args.getAllArgValues(OPT_fcuda_include_gpubinary); 717 718 return Success; 719 } 720 721 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts, 722 ArgList &Args) { 723 using namespace options; 724 Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file); 725 Opts.Targets = Args.getAllArgValues(OPT_MT); 726 Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps); 727 Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps); 728 Opts.UsePhonyTargets = Args.hasArg(OPT_MP); 729 Opts.ShowHeaderIncludes = Args.hasArg(OPT_H); 730 Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file); 731 Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG); 732 Opts.PrintShowIncludes = Args.hasArg(OPT_show_includes); 733 Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot); 734 Opts.ModuleDependencyOutputDir = 735 Args.getLastArgValue(OPT_module_dependency_dir); 736 if (Args.hasArg(OPT_MV)) 737 Opts.OutputFormat = DependencyOutputFormat::NMake; 738 // Add sanitizer blacklists as extra dependencies. 739 // They won't be discovered by the regular preprocessor, so 740 // we let make / ninja to know about this implicit dependency. 741 Opts.ExtraDeps = Args.getAllArgValues(OPT_fdepfile_entry); 742 auto ModuleFiles = Args.getAllArgValues(OPT_fmodule_file); 743 Opts.ExtraDeps.insert(Opts.ExtraDeps.end(), ModuleFiles.begin(), 744 ModuleFiles.end()); 745 } 746 747 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args, 748 DiagnosticsEngine *Diags) { 749 using namespace options; 750 bool Success = true; 751 752 Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file); 753 if (Arg *A = 754 Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags)) 755 Opts.DiagnosticSerializationFile = A->getValue(); 756 Opts.IgnoreWarnings = Args.hasArg(OPT_w); 757 Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros); 758 Opts.Pedantic = Args.hasArg(OPT_pedantic); 759 Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors); 760 Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics); 761 Opts.ShowColors = Args.hasArg(OPT_fcolor_diagnostics); 762 Opts.ShowColumn = Args.hasFlag(OPT_fshow_column, 763 OPT_fno_show_column, 764 /*Default=*/true); 765 Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info); 766 Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location); 767 Opts.ShowOptionNames = Args.hasArg(OPT_fdiagnostics_show_option); 768 769 llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes)); 770 771 // Default behavior is to not to show note include stacks. 772 Opts.ShowNoteIncludeStack = false; 773 if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack, 774 OPT_fno_diagnostics_show_note_include_stack)) 775 if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack)) 776 Opts.ShowNoteIncludeStack = true; 777 778 StringRef ShowOverloads = 779 Args.getLastArgValue(OPT_fshow_overloads_EQ, "all"); 780 if (ShowOverloads == "best") 781 Opts.setShowOverloads(Ovl_Best); 782 else if (ShowOverloads == "all") 783 Opts.setShowOverloads(Ovl_All); 784 else { 785 Success = false; 786 if (Diags) 787 Diags->Report(diag::err_drv_invalid_value) 788 << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args) 789 << ShowOverloads; 790 } 791 792 StringRef ShowCategory = 793 Args.getLastArgValue(OPT_fdiagnostics_show_category, "none"); 794 if (ShowCategory == "none") 795 Opts.ShowCategories = 0; 796 else if (ShowCategory == "id") 797 Opts.ShowCategories = 1; 798 else if (ShowCategory == "name") 799 Opts.ShowCategories = 2; 800 else { 801 Success = false; 802 if (Diags) 803 Diags->Report(diag::err_drv_invalid_value) 804 << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args) 805 << ShowCategory; 806 } 807 808 StringRef Format = 809 Args.getLastArgValue(OPT_fdiagnostics_format, "clang"); 810 if (Format == "clang") 811 Opts.setFormat(DiagnosticOptions::Clang); 812 else if (Format == "msvc") 813 Opts.setFormat(DiagnosticOptions::MSVC); 814 else if (Format == "msvc-fallback") { 815 Opts.setFormat(DiagnosticOptions::MSVC); 816 Opts.CLFallbackMode = true; 817 } else if (Format == "vi") 818 Opts.setFormat(DiagnosticOptions::Vi); 819 else { 820 Success = false; 821 if (Diags) 822 Diags->Report(diag::err_drv_invalid_value) 823 << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args) 824 << Format; 825 } 826 827 Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info); 828 Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits); 829 Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location); 830 Opts.VerifyDiagnostics = Args.hasArg(OPT_verify); 831 DiagnosticLevelMask DiagMask = DiagnosticLevelMask::None; 832 Success &= parseDiagnosticLevelMask("-verify-ignore-unexpected=", 833 Args.getAllArgValues(OPT_verify_ignore_unexpected_EQ), 834 Diags, DiagMask); 835 if (Args.hasArg(OPT_verify_ignore_unexpected)) 836 DiagMask = DiagnosticLevelMask::All; 837 Opts.setVerifyIgnoreUnexpected(DiagMask); 838 Opts.ElideType = !Args.hasArg(OPT_fno_elide_type); 839 Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree); 840 Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags); 841 Opts.MacroBacktraceLimit = 842 getLastArgIntValue(Args, OPT_fmacro_backtrace_limit, 843 DiagnosticOptions::DefaultMacroBacktraceLimit, Diags); 844 Opts.TemplateBacktraceLimit = getLastArgIntValue( 845 Args, OPT_ftemplate_backtrace_limit, 846 DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags); 847 Opts.ConstexprBacktraceLimit = getLastArgIntValue( 848 Args, OPT_fconstexpr_backtrace_limit, 849 DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags); 850 Opts.SpellCheckingLimit = getLastArgIntValue( 851 Args, OPT_fspell_checking_limit, 852 DiagnosticOptions::DefaultSpellCheckingLimit, Diags); 853 Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop, 854 DiagnosticOptions::DefaultTabStop, Diags); 855 if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) { 856 Opts.TabStop = DiagnosticOptions::DefaultTabStop; 857 if (Diags) 858 Diags->Report(diag::warn_ignoring_ftabstop_value) 859 << Opts.TabStop << DiagnosticOptions::DefaultTabStop; 860 } 861 Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags); 862 addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings); 863 addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks); 864 865 return Success; 866 } 867 868 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) { 869 Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory); 870 } 871 872 /// Parse the argument to the -ftest-module-file-extension 873 /// command-line argument. 874 /// 875 /// \returns true on error, false on success. 876 static bool parseTestModuleFileExtensionArg(StringRef Arg, 877 std::string &BlockName, 878 unsigned &MajorVersion, 879 unsigned &MinorVersion, 880 bool &Hashed, 881 std::string &UserInfo) { 882 SmallVector<StringRef, 5> Args; 883 Arg.split(Args, ':', 5); 884 if (Args.size() < 5) 885 return true; 886 887 BlockName = Args[0]; 888 if (Args[1].getAsInteger(10, MajorVersion)) return true; 889 if (Args[2].getAsInteger(10, MinorVersion)) return true; 890 if (Args[3].getAsInteger(2, Hashed)) return true; 891 if (Args.size() > 4) 892 UserInfo = Args[4]; 893 return false; 894 } 895 896 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args, 897 DiagnosticsEngine &Diags) { 898 using namespace options; 899 Opts.ProgramAction = frontend::ParseSyntaxOnly; 900 if (const Arg *A = Args.getLastArg(OPT_Action_Group)) { 901 switch (A->getOption().getID()) { 902 default: 903 llvm_unreachable("Invalid option in group!"); 904 case OPT_ast_list: 905 Opts.ProgramAction = frontend::ASTDeclList; break; 906 case OPT_ast_dump: 907 case OPT_ast_dump_lookups: 908 Opts.ProgramAction = frontend::ASTDump; break; 909 case OPT_ast_print: 910 Opts.ProgramAction = frontend::ASTPrint; break; 911 case OPT_ast_view: 912 Opts.ProgramAction = frontend::ASTView; break; 913 case OPT_dump_raw_tokens: 914 Opts.ProgramAction = frontend::DumpRawTokens; break; 915 case OPT_dump_tokens: 916 Opts.ProgramAction = frontend::DumpTokens; break; 917 case OPT_S: 918 Opts.ProgramAction = frontend::EmitAssembly; break; 919 case OPT_emit_llvm_bc: 920 Opts.ProgramAction = frontend::EmitBC; break; 921 case OPT_emit_html: 922 Opts.ProgramAction = frontend::EmitHTML; break; 923 case OPT_emit_llvm: 924 Opts.ProgramAction = frontend::EmitLLVM; break; 925 case OPT_emit_llvm_only: 926 Opts.ProgramAction = frontend::EmitLLVMOnly; break; 927 case OPT_emit_codegen_only: 928 Opts.ProgramAction = frontend::EmitCodeGenOnly; break; 929 case OPT_emit_obj: 930 Opts.ProgramAction = frontend::EmitObj; break; 931 case OPT_fixit_EQ: 932 Opts.FixItSuffix = A->getValue(); 933 // fall-through! 934 case OPT_fixit: 935 Opts.ProgramAction = frontend::FixIt; break; 936 case OPT_emit_module: 937 Opts.ProgramAction = frontend::GenerateModule; break; 938 case OPT_emit_pch: 939 Opts.ProgramAction = frontend::GeneratePCH; break; 940 case OPT_emit_pth: 941 Opts.ProgramAction = frontend::GeneratePTH; break; 942 case OPT_init_only: 943 Opts.ProgramAction = frontend::InitOnly; break; 944 case OPT_fsyntax_only: 945 Opts.ProgramAction = frontend::ParseSyntaxOnly; break; 946 case OPT_module_file_info: 947 Opts.ProgramAction = frontend::ModuleFileInfo; break; 948 case OPT_verify_pch: 949 Opts.ProgramAction = frontend::VerifyPCH; break; 950 case OPT_print_decl_contexts: 951 Opts.ProgramAction = frontend::PrintDeclContext; break; 952 case OPT_print_preamble: 953 Opts.ProgramAction = frontend::PrintPreamble; break; 954 case OPT_E: 955 Opts.ProgramAction = frontend::PrintPreprocessedInput; break; 956 case OPT_rewrite_macros: 957 Opts.ProgramAction = frontend::RewriteMacros; break; 958 case OPT_rewrite_objc: 959 Opts.ProgramAction = frontend::RewriteObjC; break; 960 case OPT_rewrite_test: 961 Opts.ProgramAction = frontend::RewriteTest; break; 962 case OPT_analyze: 963 Opts.ProgramAction = frontend::RunAnalysis; break; 964 case OPT_migrate: 965 Opts.ProgramAction = frontend::MigrateSource; break; 966 case OPT_Eonly: 967 Opts.ProgramAction = frontend::RunPreprocessorOnly; break; 968 } 969 } 970 971 if (const Arg* A = Args.getLastArg(OPT_plugin)) { 972 Opts.Plugins.emplace_back(A->getValue(0)); 973 Opts.ProgramAction = frontend::PluginAction; 974 Opts.ActionName = A->getValue(); 975 976 for (const Arg *AA : Args.filtered(OPT_plugin_arg)) 977 if (AA->getValue(0) == Opts.ActionName) 978 Opts.PluginArgs.emplace_back(AA->getValue(1)); 979 } 980 981 Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin); 982 Opts.AddPluginArgs.resize(Opts.AddPluginActions.size()); 983 for (int i = 0, e = Opts.AddPluginActions.size(); i != e; ++i) 984 for (const Arg *A : Args.filtered(OPT_plugin_arg)) 985 if (A->getValue(0) == Opts.AddPluginActions[i]) 986 Opts.AddPluginArgs[i].emplace_back(A->getValue(1)); 987 988 for (const std::string &Arg : 989 Args.getAllArgValues(OPT_ftest_module_file_extension_EQ)) { 990 std::string BlockName; 991 unsigned MajorVersion; 992 unsigned MinorVersion; 993 bool Hashed; 994 std::string UserInfo; 995 if (parseTestModuleFileExtensionArg(Arg, BlockName, MajorVersion, 996 MinorVersion, Hashed, UserInfo)) { 997 Diags.Report(diag::err_test_module_file_extension_format) << Arg; 998 999 continue; 1000 } 1001 1002 // Add the testing module file extension. 1003 Opts.ModuleFileExtensions.push_back( 1004 new TestModuleFileExtension(BlockName, MajorVersion, MinorVersion, 1005 Hashed, UserInfo)); 1006 } 1007 1008 if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) { 1009 Opts.CodeCompletionAt = 1010 ParsedSourceLocation::FromString(A->getValue()); 1011 if (Opts.CodeCompletionAt.FileName.empty()) 1012 Diags.Report(diag::err_drv_invalid_value) 1013 << A->getAsString(Args) << A->getValue(); 1014 } 1015 Opts.DisableFree = Args.hasArg(OPT_disable_free); 1016 1017 Opts.OutputFile = Args.getLastArgValue(OPT_o); 1018 Opts.Plugins = Args.getAllArgValues(OPT_load); 1019 Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch); 1020 Opts.ShowHelp = Args.hasArg(OPT_help); 1021 Opts.ShowStats = Args.hasArg(OPT_print_stats); 1022 Opts.ShowTimers = Args.hasArg(OPT_ftime_report); 1023 Opts.ShowVersion = Args.hasArg(OPT_version); 1024 Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge); 1025 Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm); 1026 Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can); 1027 Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings); 1028 Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile); 1029 Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp); 1030 Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump); 1031 Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter); 1032 Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups); 1033 Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index); 1034 Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex; 1035 Opts.ModuleMapFiles = Args.getAllArgValues(OPT_fmodule_map_file); 1036 Opts.ModuleFiles = Args.getAllArgValues(OPT_fmodule_file); 1037 Opts.ModulesEmbedFiles = Args.getAllArgValues(OPT_fmodules_embed_file_EQ); 1038 Opts.ModulesEmbedAllFiles = Args.hasArg(OPT_fmodules_embed_all_files); 1039 1040 Opts.CodeCompleteOpts.IncludeMacros 1041 = Args.hasArg(OPT_code_completion_macros); 1042 Opts.CodeCompleteOpts.IncludeCodePatterns 1043 = Args.hasArg(OPT_code_completion_patterns); 1044 Opts.CodeCompleteOpts.IncludeGlobals 1045 = !Args.hasArg(OPT_no_code_completion_globals); 1046 Opts.CodeCompleteOpts.IncludeBriefComments 1047 = Args.hasArg(OPT_code_completion_brief_comments); 1048 1049 Opts.OverrideRecordLayoutsFile 1050 = Args.getLastArgValue(OPT_foverride_record_layout_EQ); 1051 Opts.AuxTriple = 1052 llvm::Triple::normalize(Args.getLastArgValue(OPT_aux_triple)); 1053 1054 if (const Arg *A = Args.getLastArg(OPT_arcmt_check, 1055 OPT_arcmt_modify, 1056 OPT_arcmt_migrate)) { 1057 switch (A->getOption().getID()) { 1058 default: 1059 llvm_unreachable("missed a case"); 1060 case OPT_arcmt_check: 1061 Opts.ARCMTAction = FrontendOptions::ARCMT_Check; 1062 break; 1063 case OPT_arcmt_modify: 1064 Opts.ARCMTAction = FrontendOptions::ARCMT_Modify; 1065 break; 1066 case OPT_arcmt_migrate: 1067 Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate; 1068 break; 1069 } 1070 } 1071 Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory); 1072 Opts.ARCMTMigrateReportOut 1073 = Args.getLastArgValue(OPT_arcmt_migrate_report_output); 1074 Opts.ARCMTMigrateEmitARCErrors 1075 = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors); 1076 1077 if (Args.hasArg(OPT_objcmt_migrate_literals)) 1078 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals; 1079 if (Args.hasArg(OPT_objcmt_migrate_subscripting)) 1080 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting; 1081 if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax)) 1082 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax; 1083 if (Args.hasArg(OPT_objcmt_migrate_property)) 1084 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property; 1085 if (Args.hasArg(OPT_objcmt_migrate_readonly_property)) 1086 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty; 1087 if (Args.hasArg(OPT_objcmt_migrate_readwrite_property)) 1088 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty; 1089 if (Args.hasArg(OPT_objcmt_migrate_annotation)) 1090 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation; 1091 if (Args.hasArg(OPT_objcmt_returns_innerpointer_property)) 1092 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty; 1093 if (Args.hasArg(OPT_objcmt_migrate_instancetype)) 1094 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype; 1095 if (Args.hasArg(OPT_objcmt_migrate_nsmacros)) 1096 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros; 1097 if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance)) 1098 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance; 1099 if (Args.hasArg(OPT_objcmt_atomic_property)) 1100 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty; 1101 if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly)) 1102 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty; 1103 if (Args.hasArg(OPT_objcmt_migrate_designated_init)) 1104 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer; 1105 if (Args.hasArg(OPT_objcmt_migrate_all)) 1106 Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls; 1107 1108 Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path); 1109 1110 if (Opts.ARCMTAction != FrontendOptions::ARCMT_None && 1111 Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) { 1112 Diags.Report(diag::err_drv_argument_not_allowed_with) 1113 << "ARC migration" << "ObjC migration"; 1114 } 1115 1116 InputKind DashX = IK_None; 1117 if (const Arg *A = Args.getLastArg(OPT_x)) { 1118 DashX = llvm::StringSwitch<InputKind>(A->getValue()) 1119 .Case("c", IK_C) 1120 .Case("cl", IK_OpenCL) 1121 .Case("cuda", IK_CUDA) 1122 .Case("c++", IK_CXX) 1123 .Case("objective-c", IK_ObjC) 1124 .Case("objective-c++", IK_ObjCXX) 1125 .Case("cpp-output", IK_PreprocessedC) 1126 .Case("assembler-with-cpp", IK_Asm) 1127 .Case("c++-cpp-output", IK_PreprocessedCXX) 1128 .Case("cuda-cpp-output", IK_PreprocessedCuda) 1129 .Case("objective-c-cpp-output", IK_PreprocessedObjC) 1130 .Case("objc-cpp-output", IK_PreprocessedObjC) 1131 .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX) 1132 .Case("objc++-cpp-output", IK_PreprocessedObjCXX) 1133 .Case("c-header", IK_C) 1134 .Case("cl-header", IK_OpenCL) 1135 .Case("objective-c-header", IK_ObjC) 1136 .Case("c++-header", IK_CXX) 1137 .Case("objective-c++-header", IK_ObjCXX) 1138 .Cases("ast", "pcm", IK_AST) 1139 .Case("ir", IK_LLVM_IR) 1140 .Default(IK_None); 1141 if (DashX == IK_None) 1142 Diags.Report(diag::err_drv_invalid_value) 1143 << A->getAsString(Args) << A->getValue(); 1144 } 1145 1146 // '-' is the default input if none is given. 1147 std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT); 1148 Opts.Inputs.clear(); 1149 if (Inputs.empty()) 1150 Inputs.push_back("-"); 1151 for (unsigned i = 0, e = Inputs.size(); i != e; ++i) { 1152 InputKind IK = DashX; 1153 if (IK == IK_None) { 1154 IK = FrontendOptions::getInputKindForExtension( 1155 StringRef(Inputs[i]).rsplit('.').second); 1156 // FIXME: Remove this hack. 1157 if (i == 0) 1158 DashX = IK; 1159 } 1160 Opts.Inputs.emplace_back(std::move(Inputs[i]), IK); 1161 } 1162 1163 return DashX; 1164 } 1165 1166 std::string CompilerInvocation::GetResourcesPath(const char *Argv0, 1167 void *MainAddr) { 1168 std::string ClangExecutable = 1169 llvm::sys::fs::getMainExecutable(Argv0, MainAddr); 1170 StringRef Dir = llvm::sys::path::parent_path(ClangExecutable); 1171 1172 // Compute the path to the resource directory. 1173 StringRef ClangResourceDir(CLANG_RESOURCE_DIR); 1174 SmallString<128> P(Dir); 1175 if (ClangResourceDir != "") 1176 llvm::sys::path::append(P, ClangResourceDir); 1177 else 1178 llvm::sys::path::append(P, "..", Twine("lib") + CLANG_LIBDIR_SUFFIX, 1179 "clang", CLANG_VERSION_STRING); 1180 1181 return P.str(); 1182 } 1183 1184 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args) { 1185 using namespace options; 1186 Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/"); 1187 Opts.Verbose = Args.hasArg(OPT_v); 1188 Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc); 1189 Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc); 1190 Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx); 1191 if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ)) 1192 Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0); 1193 Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir); 1194 Opts.ModuleCachePath = Args.getLastArgValue(OPT_fmodules_cache_path); 1195 Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path); 1196 Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash); 1197 Opts.ImplicitModuleMaps = Args.hasArg(OPT_fimplicit_module_maps); 1198 Opts.ModuleMapFileHomeIsCwd = Args.hasArg(OPT_fmodule_map_file_home_is_cwd); 1199 Opts.ModuleCachePruneInterval = 1200 getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60); 1201 Opts.ModuleCachePruneAfter = 1202 getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60); 1203 Opts.ModulesValidateOncePerBuildSession = 1204 Args.hasArg(OPT_fmodules_validate_once_per_build_session); 1205 Opts.BuildSessionTimestamp = 1206 getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0); 1207 Opts.ModulesValidateSystemHeaders = 1208 Args.hasArg(OPT_fmodules_validate_system_headers); 1209 if (const Arg *A = Args.getLastArg(OPT_fmodule_format_EQ)) 1210 Opts.ModuleFormat = A->getValue(); 1211 1212 for (const Arg *A : Args.filtered(OPT_fmodules_ignore_macro)) { 1213 StringRef MacroDef = A->getValue(); 1214 Opts.ModulesIgnoreMacros.insert(MacroDef.split('=').first); 1215 } 1216 1217 // Add -I..., -F..., and -index-header-map options in order. 1218 bool IsIndexHeaderMap = false; 1219 for (const Arg *A : Args.filtered(OPT_I, OPT_F, OPT_index_header_map)) { 1220 if (A->getOption().matches(OPT_index_header_map)) { 1221 // -index-header-map applies to the next -I or -F. 1222 IsIndexHeaderMap = true; 1223 continue; 1224 } 1225 1226 frontend::IncludeDirGroup Group = 1227 IsIndexHeaderMap ? frontend::IndexHeaderMap : frontend::Angled; 1228 1229 Opts.AddPath(A->getValue(), Group, 1230 /*IsFramework=*/A->getOption().matches(OPT_F), true); 1231 IsIndexHeaderMap = false; 1232 } 1233 1234 // Add -iprefix/-iwithprefix/-iwithprefixbefore options. 1235 StringRef Prefix = ""; // FIXME: This isn't the correct default prefix. 1236 for (const Arg *A : 1237 Args.filtered(OPT_iprefix, OPT_iwithprefix, OPT_iwithprefixbefore)) { 1238 if (A->getOption().matches(OPT_iprefix)) 1239 Prefix = A->getValue(); 1240 else if (A->getOption().matches(OPT_iwithprefix)) 1241 Opts.AddPath(Prefix.str() + A->getValue(), frontend::After, false, true); 1242 else 1243 Opts.AddPath(Prefix.str() + A->getValue(), frontend::Angled, false, true); 1244 } 1245 1246 for (const Arg *A : Args.filtered(OPT_idirafter)) 1247 Opts.AddPath(A->getValue(), frontend::After, false, true); 1248 for (const Arg *A : Args.filtered(OPT_iquote)) 1249 Opts.AddPath(A->getValue(), frontend::Quoted, false, true); 1250 for (const Arg *A : Args.filtered(OPT_isystem, OPT_iwithsysroot)) 1251 Opts.AddPath(A->getValue(), frontend::System, false, 1252 !A->getOption().matches(OPT_iwithsysroot)); 1253 for (const Arg *A : Args.filtered(OPT_iframework)) 1254 Opts.AddPath(A->getValue(), frontend::System, true, true); 1255 1256 // Add the paths for the various language specific isystem flags. 1257 for (const Arg *A : Args.filtered(OPT_c_isystem)) 1258 Opts.AddPath(A->getValue(), frontend::CSystem, false, true); 1259 for (const Arg *A : Args.filtered(OPT_cxx_isystem)) 1260 Opts.AddPath(A->getValue(), frontend::CXXSystem, false, true); 1261 for (const Arg *A : Args.filtered(OPT_objc_isystem)) 1262 Opts.AddPath(A->getValue(), frontend::ObjCSystem, false,true); 1263 for (const Arg *A : Args.filtered(OPT_objcxx_isystem)) 1264 Opts.AddPath(A->getValue(), frontend::ObjCXXSystem, false, true); 1265 1266 // Add the internal paths from a driver that detects standard include paths. 1267 for (const Arg *A : 1268 Args.filtered(OPT_internal_isystem, OPT_internal_externc_isystem)) { 1269 frontend::IncludeDirGroup Group = frontend::System; 1270 if (A->getOption().matches(OPT_internal_externc_isystem)) 1271 Group = frontend::ExternCSystem; 1272 Opts.AddPath(A->getValue(), Group, false, true); 1273 } 1274 1275 // Add the path prefixes which are implicitly treated as being system headers. 1276 for (const Arg *A : 1277 Args.filtered(OPT_system_header_prefix, OPT_no_system_header_prefix)) 1278 Opts.AddSystemHeaderPrefix( 1279 A->getValue(), A->getOption().matches(OPT_system_header_prefix)); 1280 1281 for (const Arg *A : Args.filtered(OPT_ivfsoverlay)) 1282 Opts.AddVFSOverlayFile(A->getValue()); 1283 } 1284 1285 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK, 1286 LangStandard::Kind LangStd) { 1287 // Set some properties which depend solely on the input kind; it would be nice 1288 // to move these to the language standard, and have the driver resolve the 1289 // input kind + language standard. 1290 if (IK == IK_Asm) { 1291 Opts.AsmPreprocessor = 1; 1292 } else if (IK == IK_ObjC || 1293 IK == IK_ObjCXX || 1294 IK == IK_PreprocessedObjC || 1295 IK == IK_PreprocessedObjCXX) { 1296 Opts.ObjC1 = Opts.ObjC2 = 1; 1297 } 1298 1299 if (LangStd == LangStandard::lang_unspecified) { 1300 // Based on the base language, pick one. 1301 switch (IK) { 1302 case IK_None: 1303 case IK_AST: 1304 case IK_LLVM_IR: 1305 llvm_unreachable("Invalid input kind!"); 1306 case IK_OpenCL: 1307 LangStd = LangStandard::lang_opencl; 1308 break; 1309 case IK_CUDA: 1310 case IK_PreprocessedCuda: 1311 LangStd = LangStandard::lang_cuda; 1312 break; 1313 case IK_Asm: 1314 case IK_C: 1315 case IK_PreprocessedC: 1316 case IK_ObjC: 1317 case IK_PreprocessedObjC: 1318 LangStd = LangStandard::lang_gnu11; 1319 break; 1320 case IK_CXX: 1321 case IK_PreprocessedCXX: 1322 case IK_ObjCXX: 1323 case IK_PreprocessedObjCXX: 1324 LangStd = LangStandard::lang_gnucxx98; 1325 break; 1326 } 1327 } 1328 1329 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 1330 Opts.LineComment = Std.hasLineComments(); 1331 Opts.C99 = Std.isC99(); 1332 Opts.C11 = Std.isC11(); 1333 Opts.CPlusPlus = Std.isCPlusPlus(); 1334 Opts.CPlusPlus11 = Std.isCPlusPlus11(); 1335 Opts.CPlusPlus14 = Std.isCPlusPlus14(); 1336 Opts.CPlusPlus1z = Std.isCPlusPlus1z(); 1337 Opts.Digraphs = Std.hasDigraphs(); 1338 Opts.GNUMode = Std.isGNUMode(); 1339 Opts.GNUInline = Std.isC89(); 1340 Opts.HexFloats = Std.hasHexFloats(); 1341 Opts.ImplicitInt = Std.hasImplicitInt(); 1342 1343 // Set OpenCL Version. 1344 Opts.OpenCL = LangStd == LangStandard::lang_opencl || IK == IK_OpenCL; 1345 if (LangStd == LangStandard::lang_opencl) 1346 Opts.OpenCLVersion = 100; 1347 else if (LangStd == LangStandard::lang_opencl11) 1348 Opts.OpenCLVersion = 110; 1349 else if (LangStd == LangStandard::lang_opencl12) 1350 Opts.OpenCLVersion = 120; 1351 else if (LangStd == LangStandard::lang_opencl20) 1352 Opts.OpenCLVersion = 200; 1353 1354 // OpenCL has some additional defaults. 1355 if (Opts.OpenCL) { 1356 Opts.AltiVec = 0; 1357 Opts.ZVector = 0; 1358 Opts.CXXOperatorNames = 1; 1359 Opts.LaxVectorConversions = 0; 1360 Opts.DefaultFPContract = 1; 1361 Opts.NativeHalfType = 1; 1362 } 1363 1364 Opts.CUDA = IK == IK_CUDA || IK == IK_PreprocessedCuda || 1365 LangStd == LangStandard::lang_cuda; 1366 1367 // OpenCL and C++ both have bool, true, false keywords. 1368 Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; 1369 1370 // OpenCL has half keyword 1371 Opts.Half = Opts.OpenCL; 1372 1373 // C++ has wchar_t keyword. 1374 Opts.WChar = Opts.CPlusPlus; 1375 1376 Opts.GNUKeywords = Opts.GNUMode; 1377 Opts.CXXOperatorNames = Opts.CPlusPlus; 1378 1379 Opts.DollarIdents = !Opts.AsmPreprocessor; 1380 } 1381 1382 /// Attempt to parse a visibility value out of the given argument. 1383 static Visibility parseVisibility(Arg *arg, ArgList &args, 1384 DiagnosticsEngine &diags) { 1385 StringRef value = arg->getValue(); 1386 if (value == "default") { 1387 return DefaultVisibility; 1388 } else if (value == "hidden" || value == "internal") { 1389 return HiddenVisibility; 1390 } else if (value == "protected") { 1391 // FIXME: diagnose if target does not support protected visibility 1392 return ProtectedVisibility; 1393 } 1394 1395 diags.Report(diag::err_drv_invalid_value) 1396 << arg->getAsString(args) << value; 1397 return DefaultVisibility; 1398 } 1399 1400 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK, 1401 DiagnosticsEngine &Diags) { 1402 // FIXME: Cleanup per-file based stuff. 1403 LangStandard::Kind LangStd = LangStandard::lang_unspecified; 1404 if (const Arg *A = Args.getLastArg(OPT_std_EQ)) { 1405 LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 1406 #define LANGSTANDARD(id, name, desc, features) \ 1407 .Case(name, LangStandard::lang_##id) 1408 #include "clang/Frontend/LangStandards.def" 1409 .Default(LangStandard::lang_unspecified); 1410 if (LangStd == LangStandard::lang_unspecified) 1411 Diags.Report(diag::err_drv_invalid_value) 1412 << A->getAsString(Args) << A->getValue(); 1413 else { 1414 // Valid standard, check to make sure language and standard are 1415 // compatible. 1416 const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); 1417 switch (IK) { 1418 case IK_C: 1419 case IK_ObjC: 1420 case IK_PreprocessedC: 1421 case IK_PreprocessedObjC: 1422 if (!(Std.isC89() || Std.isC99())) 1423 Diags.Report(diag::err_drv_argument_not_allowed_with) 1424 << A->getAsString(Args) << "C/ObjC"; 1425 break; 1426 case IK_CXX: 1427 case IK_ObjCXX: 1428 case IK_PreprocessedCXX: 1429 case IK_PreprocessedObjCXX: 1430 if (!Std.isCPlusPlus()) 1431 Diags.Report(diag::err_drv_argument_not_allowed_with) 1432 << A->getAsString(Args) << "C++/ObjC++"; 1433 break; 1434 case IK_OpenCL: 1435 if (!Std.isC99()) 1436 Diags.Report(diag::err_drv_argument_not_allowed_with) 1437 << A->getAsString(Args) << "OpenCL"; 1438 break; 1439 case IK_CUDA: 1440 case IK_PreprocessedCuda: 1441 if (!Std.isCPlusPlus()) 1442 Diags.Report(diag::err_drv_argument_not_allowed_with) 1443 << A->getAsString(Args) << "CUDA"; 1444 break; 1445 default: 1446 break; 1447 } 1448 } 1449 } 1450 1451 // -cl-std only applies for OpenCL language standards. 1452 // Override the -std option in this case. 1453 if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) { 1454 LangStandard::Kind OpenCLLangStd 1455 = llvm::StringSwitch<LangStandard::Kind>(A->getValue()) 1456 .Case("CL", LangStandard::lang_opencl) 1457 .Case("CL1.1", LangStandard::lang_opencl11) 1458 .Case("CL1.2", LangStandard::lang_opencl12) 1459 .Case("CL2.0", LangStandard::lang_opencl20) 1460 .Default(LangStandard::lang_unspecified); 1461 1462 if (OpenCLLangStd == LangStandard::lang_unspecified) { 1463 Diags.Report(diag::err_drv_invalid_value) 1464 << A->getAsString(Args) << A->getValue(); 1465 } 1466 else 1467 LangStd = OpenCLLangStd; 1468 } 1469 1470 CompilerInvocation::setLangDefaults(Opts, IK, LangStd); 1471 1472 // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension 1473 // keywords. This behavior is provided by GCC's poorly named '-fasm' flag, 1474 // while a subset (the non-C++ GNU keywords) is provided by GCC's 1475 // '-fgnu-keywords'. Clang conflates the two for simplicity under the single 1476 // name, as it doesn't seem a useful distinction. 1477 Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords, 1478 Opts.GNUKeywords); 1479 1480 if (Args.hasArg(OPT_fno_operator_names)) 1481 Opts.CXXOperatorNames = 0; 1482 1483 if (Args.hasArg(OPT_fcuda_is_device)) 1484 Opts.CUDAIsDevice = 1; 1485 1486 if (Args.hasArg(OPT_fcuda_allow_host_calls_from_host_device)) 1487 Opts.CUDAAllowHostCallsFromHostDevice = 1; 1488 1489 if (Args.hasArg(OPT_fcuda_disable_target_call_checks)) 1490 Opts.CUDADisableTargetCallChecks = 1; 1491 1492 if (Args.hasArg(OPT_fcuda_target_overloads)) 1493 Opts.CUDATargetOverloads = 1; 1494 1495 if (Opts.ObjC1) { 1496 if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) { 1497 StringRef value = arg->getValue(); 1498 if (Opts.ObjCRuntime.tryParse(value)) 1499 Diags.Report(diag::err_drv_unknown_objc_runtime) << value; 1500 } 1501 1502 if (Args.hasArg(OPT_fobjc_gc_only)) 1503 Opts.setGC(LangOptions::GCOnly); 1504 else if (Args.hasArg(OPT_fobjc_gc)) 1505 Opts.setGC(LangOptions::HybridGC); 1506 else if (Args.hasArg(OPT_fobjc_arc)) { 1507 Opts.ObjCAutoRefCount = 1; 1508 if (!Opts.ObjCRuntime.allowsARC()) 1509 Diags.Report(diag::err_arc_unsupported_on_runtime); 1510 } 1511 1512 // ObjCWeakRuntime tracks whether the runtime supports __weak, not 1513 // whether the feature is actually enabled. This is predominantly 1514 // determined by -fobjc-runtime, but we allow it to be overridden 1515 // from the command line for testing purposes. 1516 if (Args.hasArg(OPT_fobjc_runtime_has_weak)) 1517 Opts.ObjCWeakRuntime = 1; 1518 else 1519 Opts.ObjCWeakRuntime = Opts.ObjCRuntime.allowsWeak(); 1520 1521 // ObjCWeak determines whether __weak is actually enabled. 1522 // Note that we allow -fno-objc-weak to disable this even in ARC mode. 1523 if (auto weakArg = Args.getLastArg(OPT_fobjc_weak, OPT_fno_objc_weak)) { 1524 if (!weakArg->getOption().matches(OPT_fobjc_weak)) { 1525 assert(!Opts.ObjCWeak); 1526 } else if (Opts.getGC() != LangOptions::NonGC) { 1527 Diags.Report(diag::err_objc_weak_with_gc); 1528 } else if (!Opts.ObjCWeakRuntime) { 1529 Diags.Report(diag::err_objc_weak_unsupported); 1530 } else { 1531 Opts.ObjCWeak = 1; 1532 } 1533 } else if (Opts.ObjCAutoRefCount) { 1534 Opts.ObjCWeak = Opts.ObjCWeakRuntime; 1535 } 1536 1537 if (Args.hasArg(OPT_fno_objc_infer_related_result_type)) 1538 Opts.ObjCInferRelatedResultType = 0; 1539 1540 if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime)) 1541 Opts.ObjCSubscriptingLegacyRuntime = 1542 (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX); 1543 } 1544 1545 if (Args.hasArg(OPT_fgnu89_inline)) { 1546 if (Opts.CPlusPlus) 1547 Diags.Report(diag::err_drv_argument_not_allowed_with) << "-fgnu89-inline" 1548 << "C++/ObjC++"; 1549 else 1550 Opts.GNUInline = 1; 1551 } 1552 1553 if (Args.hasArg(OPT_fapple_kext)) { 1554 if (!Opts.CPlusPlus) 1555 Diags.Report(diag::warn_c_kext); 1556 else 1557 Opts.AppleKext = 1; 1558 } 1559 1560 if (Args.hasArg(OPT_print_ivar_layout)) 1561 Opts.ObjCGCBitmapPrint = 1; 1562 if (Args.hasArg(OPT_fno_constant_cfstrings)) 1563 Opts.NoConstantCFStrings = 1; 1564 1565 if (Args.hasArg(OPT_faltivec)) 1566 Opts.AltiVec = 1; 1567 1568 if (Args.hasArg(OPT_fzvector)) 1569 Opts.ZVector = 1; 1570 1571 if (Args.hasArg(OPT_pthread)) 1572 Opts.POSIXThreads = 1; 1573 1574 // The value-visibility mode defaults to "default". 1575 if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) { 1576 Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags)); 1577 } else { 1578 Opts.setValueVisibilityMode(DefaultVisibility); 1579 } 1580 1581 // The type-visibility mode defaults to the value-visibility mode. 1582 if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) { 1583 Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags)); 1584 } else { 1585 Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode()); 1586 } 1587 1588 if (Args.hasArg(OPT_fvisibility_inlines_hidden)) 1589 Opts.InlineVisibilityHidden = 1; 1590 1591 if (Args.hasArg(OPT_ftrapv)) { 1592 Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping); 1593 // Set the handler, if one is specified. 1594 Opts.OverflowHandler = 1595 Args.getLastArgValue(OPT_ftrapv_handler); 1596 } 1597 else if (Args.hasArg(OPT_fwrapv)) 1598 Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined); 1599 1600 Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility); 1601 Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions); 1602 Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt; 1603 Opts.MSCompatibilityVersion = 0; 1604 if (const Arg *A = Args.getLastArg(OPT_fms_compatibility_version)) { 1605 VersionTuple VT; 1606 if (VT.tryParse(A->getValue())) 1607 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) 1608 << A->getValue(); 1609 Opts.MSCompatibilityVersion = VT.getMajor() * 10000000 + 1610 VT.getMinor().getValueOr(0) * 100000 + 1611 VT.getSubminor().getValueOr(0); 1612 } 1613 1614 // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs 1615 // is specified, or -std is set to a conforming mode. 1616 // Trigraphs are disabled by default in c++1z onwards. 1617 Opts.Trigraphs = !Opts.GNUMode && !Opts.MSVCCompat && !Opts.CPlusPlus1z; 1618 Opts.Trigraphs = 1619 Args.hasFlag(OPT_ftrigraphs, OPT_fno_trigraphs, Opts.Trigraphs); 1620 1621 Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers, 1622 OPT_fno_dollars_in_identifiers, 1623 Opts.DollarIdents); 1624 Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings); 1625 Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags); 1626 Opts.Borland = Args.hasArg(OPT_fborland_extensions); 1627 Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings); 1628 Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings, 1629 Opts.ConstStrings); 1630 if (Args.hasArg(OPT_fno_lax_vector_conversions)) 1631 Opts.LaxVectorConversions = 0; 1632 if (Args.hasArg(OPT_fno_threadsafe_statics)) 1633 Opts.ThreadsafeStatics = 0; 1634 Opts.Exceptions = Args.hasArg(OPT_fexceptions); 1635 Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions); 1636 Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions); 1637 Opts.SjLjExceptions = Args.hasArg(OPT_fsjlj_exceptions); 1638 Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp); 1639 1640 Opts.RTTI = !Args.hasArg(OPT_fno_rtti); 1641 Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data); 1642 Opts.Blocks = Args.hasArg(OPT_fblocks); 1643 Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional); 1644 Opts.Coroutines = Args.hasArg(OPT_fcoroutines); 1645 Opts.Modules = Args.hasArg(OPT_fmodules); 1646 Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse); 1647 Opts.ModulesDeclUse = 1648 Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse; 1649 Opts.ModulesLocalVisibility = 1650 Args.hasArg(OPT_fmodules_local_submodule_visibility); 1651 Opts.ModulesSearchAll = Opts.Modules && 1652 !Args.hasArg(OPT_fno_modules_search_all) && 1653 Args.hasArg(OPT_fmodules_search_all); 1654 Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery); 1655 Opts.ImplicitModules = !Args.hasArg(OPT_fno_implicit_modules); 1656 Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char); 1657 Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar); 1658 Opts.ShortWChar = Args.hasFlag(OPT_fshort_wchar, OPT_fno_short_wchar, false); 1659 Opts.ShortEnums = Args.hasArg(OPT_fshort_enums); 1660 Opts.Freestanding = Args.hasArg(OPT_ffreestanding); 1661 Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding; 1662 Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin); 1663 Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new); 1664 Opts.SizedDeallocation = Args.hasArg(OPT_fsized_deallocation); 1665 Opts.ConceptsTS = Args.hasArg(OPT_fconcepts_ts); 1666 Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions); 1667 Opts.AccessControl = !Args.hasArg(OPT_fno_access_control); 1668 Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors); 1669 Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno); 1670 Opts.InstantiationDepth = 1671 getLastArgIntValue(Args, OPT_ftemplate_depth, 256, Diags); 1672 Opts.ArrowDepth = 1673 getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags); 1674 Opts.ConstexprCallDepth = 1675 getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags); 1676 Opts.ConstexprStepLimit = 1677 getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags); 1678 Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags); 1679 Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing); 1680 Opts.NumLargeByValueCopy = 1681 getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags); 1682 Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields); 1683 Opts.ObjCConstantStringClass = 1684 Args.getLastArgValue(OPT_fconstant_string_class); 1685 Opts.ObjCDefaultSynthProperties = 1686 !Args.hasArg(OPT_disable_objc_default_synthesize_properties); 1687 Opts.EncodeExtendedBlockSig = 1688 Args.hasArg(OPT_fencode_extended_block_signature); 1689 Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls); 1690 Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags); 1691 Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags); 1692 Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags); 1693 Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags); 1694 Opts.Static = Args.hasArg(OPT_static_define); 1695 Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple); 1696 Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple 1697 || Args.hasArg(OPT_fdump_record_layouts); 1698 Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts); 1699 Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking); 1700 Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align); 1701 Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant); 1702 Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math); 1703 Opts.MRTD = Args.hasArg(OPT_mrtd); 1704 Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat); 1705 Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map); 1706 Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype); 1707 Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support); 1708 Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id); 1709 Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal); 1710 Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack); 1711 Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name); 1712 Opts.AppExt = Args.hasArg(OPT_fapplication_extension); 1713 Opts.ImplementationOfModule = 1714 Args.getLastArgValue(OPT_fmodule_implementation_of); 1715 Opts.ModuleFeatures = Args.getAllArgValues(OPT_fmodule_feature); 1716 std::sort(Opts.ModuleFeatures.begin(), Opts.ModuleFeatures.end()); 1717 Opts.NativeHalfType |= Args.hasArg(OPT_fnative_half_type); 1718 Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns); 1719 Opts.GNUAsm = !Args.hasArg(OPT_fno_gnu_inline_asm); 1720 1721 // __declspec is enabled by default for the PS4 by the driver, and also 1722 // enabled for Microsoft Extensions or Borland Extensions, here. 1723 // 1724 // FIXME: __declspec is also currently enabled for CUDA, but isn't really a 1725 // CUDA extension, however it is required for supporting cuda_builtin_vars.h, 1726 // which uses __declspec(property). Once that has been rewritten in terms of 1727 // something more generic, remove the Opts.CUDA term here. 1728 Opts.DeclSpecKeyword = 1729 Args.hasFlag(OPT_fdeclspec, OPT_fno_declspec, 1730 (Opts.MicrosoftExt || Opts.Borland || Opts.CUDA)); 1731 1732 if (!Opts.CurrentModule.empty() && !Opts.ImplementationOfModule.empty() && 1733 Opts.CurrentModule != Opts.ImplementationOfModule) { 1734 Diags.Report(diag::err_conflicting_module_names) 1735 << Opts.CurrentModule << Opts.ImplementationOfModule; 1736 } 1737 1738 // For now, we only support local submodule visibility in C++ (because we 1739 // heavily depend on the ODR for merging redefinitions). 1740 if (Opts.ModulesLocalVisibility && !Opts.CPlusPlus) 1741 Diags.Report(diag::err_drv_argument_not_allowed_with) 1742 << "-fmodules-local-submodule-visibility" << "C"; 1743 1744 if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) { 1745 switch (llvm::StringSwitch<unsigned>(A->getValue()) 1746 .Case("target", LangOptions::ASMM_Target) 1747 .Case("no", LangOptions::ASMM_Off) 1748 .Case("yes", LangOptions::ASMM_On) 1749 .Default(255)) { 1750 default: 1751 Diags.Report(diag::err_drv_invalid_value) 1752 << "-faddress-space-map-mangling=" << A->getValue(); 1753 break; 1754 case LangOptions::ASMM_Target: 1755 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target); 1756 break; 1757 case LangOptions::ASMM_On: 1758 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On); 1759 break; 1760 case LangOptions::ASMM_Off: 1761 Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off); 1762 break; 1763 } 1764 } 1765 1766 if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) { 1767 LangOptions::PragmaMSPointersToMembersKind InheritanceModel = 1768 llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>( 1769 A->getValue()) 1770 .Case("single", 1771 LangOptions::PPTMK_FullGeneralitySingleInheritance) 1772 .Case("multiple", 1773 LangOptions::PPTMK_FullGeneralityMultipleInheritance) 1774 .Case("virtual", 1775 LangOptions::PPTMK_FullGeneralityVirtualInheritance) 1776 .Default(LangOptions::PPTMK_BestCase); 1777 if (InheritanceModel == LangOptions::PPTMK_BestCase) 1778 Diags.Report(diag::err_drv_invalid_value) 1779 << "-fms-memptr-rep=" << A->getValue(); 1780 1781 Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel); 1782 } 1783 1784 // Check if -fopenmp is specified. 1785 Opts.OpenMP = Args.hasArg(options::OPT_fopenmp); 1786 Opts.OpenMPUseTLS = 1787 Opts.OpenMP && !Args.hasArg(options::OPT_fnoopenmp_use_tls); 1788 1789 // Record whether the __DEPRECATED define was requested. 1790 Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro, 1791 OPT_fno_deprecated_macro, 1792 Opts.Deprecated); 1793 1794 // FIXME: Eliminate this dependency. 1795 unsigned Opt = getOptimizationLevel(Args, IK, Diags), 1796 OptSize = getOptimizationLevelSize(Args); 1797 Opts.Optimize = Opt != 0; 1798 Opts.OptimizeSize = OptSize != 0; 1799 1800 // This is the __NO_INLINE__ define, which just depends on things like the 1801 // optimization level and -fno-inline, not actually whether the backend has 1802 // inlining enabled. 1803 Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline); 1804 1805 Opts.FastMath = Args.hasArg(OPT_ffast_math) || 1806 Args.hasArg(OPT_cl_fast_relaxed_math); 1807 Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only) || 1808 Args.hasArg(OPT_cl_finite_math_only) || 1809 Args.hasArg(OPT_cl_fast_relaxed_math); 1810 Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) || 1811 Args.hasArg(OPT_cl_unsafe_math_optimizations) || 1812 Args.hasArg(OPT_cl_fast_relaxed_math); 1813 1814 Opts.RetainCommentsFromSystemHeaders = 1815 Args.hasArg(OPT_fretain_comments_from_system_headers); 1816 1817 unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags); 1818 switch (SSP) { 1819 default: 1820 Diags.Report(diag::err_drv_invalid_value) 1821 << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP; 1822 break; 1823 case 0: Opts.setStackProtector(LangOptions::SSPOff); break; 1824 case 1: Opts.setStackProtector(LangOptions::SSPOn); break; 1825 case 2: Opts.setStackProtector(LangOptions::SSPStrong); break; 1826 case 3: Opts.setStackProtector(LangOptions::SSPReq); break; 1827 } 1828 1829 // Parse -fsanitize= arguments. 1830 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 1831 Diags, Opts.Sanitize); 1832 // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here. 1833 Opts.SanitizeAddressFieldPadding = 1834 getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags); 1835 Opts.SanitizerBlacklistFiles = Args.getAllArgValues(OPT_fsanitize_blacklist); 1836 } 1837 1838 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args, 1839 FileManager &FileMgr, 1840 DiagnosticsEngine &Diags) { 1841 using namespace options; 1842 Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch); 1843 Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth); 1844 if (const Arg *A = Args.getLastArg(OPT_token_cache)) 1845 Opts.TokenCache = A->getValue(); 1846 else 1847 Opts.TokenCache = Opts.ImplicitPTHInclude; 1848 Opts.UsePredefines = !Args.hasArg(OPT_undef); 1849 Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record); 1850 Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch); 1851 1852 Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls); 1853 for (const Arg *A : Args.filtered(OPT_error_on_deserialized_pch_decl)) 1854 Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue()); 1855 1856 if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) { 1857 StringRef Value(A->getValue()); 1858 size_t Comma = Value.find(','); 1859 unsigned Bytes = 0; 1860 unsigned EndOfLine = 0; 1861 1862 if (Comma == StringRef::npos || 1863 Value.substr(0, Comma).getAsInteger(10, Bytes) || 1864 Value.substr(Comma + 1).getAsInteger(10, EndOfLine)) 1865 Diags.Report(diag::err_drv_preamble_format); 1866 else { 1867 Opts.PrecompiledPreambleBytes.first = Bytes; 1868 Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0); 1869 } 1870 } 1871 1872 // Add macros from the command line. 1873 for (const Arg *A : Args.filtered(OPT_D, OPT_U)) { 1874 if (A->getOption().matches(OPT_D)) 1875 Opts.addMacroDef(A->getValue()); 1876 else 1877 Opts.addMacroUndef(A->getValue()); 1878 } 1879 1880 Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros); 1881 1882 // Add the ordered list of -includes. 1883 for (const Arg *A : Args.filtered(OPT_include)) 1884 Opts.Includes.emplace_back(A->getValue()); 1885 1886 for (const Arg *A : Args.filtered(OPT_chain_include)) 1887 Opts.ChainedIncludes.emplace_back(A->getValue()); 1888 1889 // Include 'altivec.h' if -faltivec option present 1890 if (Args.hasArg(OPT_faltivec)) 1891 Opts.Includes.emplace_back("altivec.h"); 1892 1893 for (const Arg *A : Args.filtered(OPT_remap_file)) { 1894 std::pair<StringRef, StringRef> Split = StringRef(A->getValue()).split(';'); 1895 1896 if (Split.second.empty()) { 1897 Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args); 1898 continue; 1899 } 1900 1901 Opts.addRemappedFile(Split.first, Split.second); 1902 } 1903 1904 if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) { 1905 StringRef Name = A->getValue(); 1906 unsigned Library = llvm::StringSwitch<unsigned>(Name) 1907 .Case("libc++", ARCXX_libcxx) 1908 .Case("libstdc++", ARCXX_libstdcxx) 1909 .Case("none", ARCXX_nolib) 1910 .Default(~0U); 1911 if (Library == ~0U) 1912 Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name; 1913 else 1914 Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library; 1915 } 1916 } 1917 1918 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts, 1919 ArgList &Args, 1920 frontend::ActionKind Action) { 1921 using namespace options; 1922 1923 switch (Action) { 1924 case frontend::ASTDeclList: 1925 case frontend::ASTDump: 1926 case frontend::ASTPrint: 1927 case frontend::ASTView: 1928 case frontend::EmitAssembly: 1929 case frontend::EmitBC: 1930 case frontend::EmitHTML: 1931 case frontend::EmitLLVM: 1932 case frontend::EmitLLVMOnly: 1933 case frontend::EmitCodeGenOnly: 1934 case frontend::EmitObj: 1935 case frontend::FixIt: 1936 case frontend::GenerateModule: 1937 case frontend::GeneratePCH: 1938 case frontend::GeneratePTH: 1939 case frontend::ParseSyntaxOnly: 1940 case frontend::ModuleFileInfo: 1941 case frontend::VerifyPCH: 1942 case frontend::PluginAction: 1943 case frontend::PrintDeclContext: 1944 case frontend::RewriteObjC: 1945 case frontend::RewriteTest: 1946 case frontend::RunAnalysis: 1947 case frontend::MigrateSource: 1948 Opts.ShowCPP = 0; 1949 break; 1950 1951 case frontend::DumpRawTokens: 1952 case frontend::DumpTokens: 1953 case frontend::InitOnly: 1954 case frontend::PrintPreamble: 1955 case frontend::PrintPreprocessedInput: 1956 case frontend::RewriteMacros: 1957 case frontend::RunPreprocessorOnly: 1958 Opts.ShowCPP = !Args.hasArg(OPT_dM); 1959 break; 1960 } 1961 1962 Opts.ShowComments = Args.hasArg(OPT_C); 1963 Opts.ShowLineMarkers = !Args.hasArg(OPT_P); 1964 Opts.ShowMacroComments = Args.hasArg(OPT_CC); 1965 Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD); 1966 Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes); 1967 Opts.UseLineDirectives = Args.hasArg(OPT_fuse_line_directives); 1968 } 1969 1970 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) { 1971 using namespace options; 1972 Opts.ABI = Args.getLastArgValue(OPT_target_abi); 1973 Opts.CPU = Args.getLastArgValue(OPT_target_cpu); 1974 Opts.FPMath = Args.getLastArgValue(OPT_mfpmath); 1975 Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature); 1976 Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version); 1977 Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple)); 1978 Opts.Reciprocals = Args.getAllArgValues(OPT_mrecip_EQ); 1979 // Use the default target triple if unspecified. 1980 if (Opts.Triple.empty()) 1981 Opts.Triple = llvm::sys::getDefaultTargetTriple(); 1982 } 1983 1984 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res, 1985 const char *const *ArgBegin, 1986 const char *const *ArgEnd, 1987 DiagnosticsEngine &Diags) { 1988 bool Success = true; 1989 1990 // Parse the arguments. 1991 std::unique_ptr<OptTable> Opts(createDriverOptTable()); 1992 const unsigned IncludedFlagsBitmask = options::CC1Option; 1993 unsigned MissingArgIndex, MissingArgCount; 1994 InputArgList Args = 1995 Opts->ParseArgs(llvm::makeArrayRef(ArgBegin, ArgEnd), MissingArgIndex, 1996 MissingArgCount, IncludedFlagsBitmask); 1997 1998 // Check for missing argument error. 1999 if (MissingArgCount) { 2000 Diags.Report(diag::err_drv_missing_argument) 2001 << Args.getArgString(MissingArgIndex) << MissingArgCount; 2002 Success = false; 2003 } 2004 2005 // Issue errors on unknown arguments. 2006 for (const Arg *A : Args.filtered(OPT_UNKNOWN)) { 2007 Diags.Report(diag::err_drv_unknown_argument) << A->getAsString(Args); 2008 Success = false; 2009 } 2010 2011 Success &= ParseAnalyzerArgs(*Res.getAnalyzerOpts(), Args, Diags); 2012 Success &= ParseMigratorArgs(Res.getMigratorOpts(), Args); 2013 ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), Args); 2014 Success &= ParseDiagnosticArgs(Res.getDiagnosticOpts(), Args, &Diags); 2015 ParseCommentArgs(Res.getLangOpts()->CommentOpts, Args); 2016 ParseFileSystemArgs(Res.getFileSystemOpts(), Args); 2017 // FIXME: We shouldn't have to pass the DashX option around here 2018 InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), Args, Diags); 2019 ParseTargetArgs(Res.getTargetOpts(), Args); 2020 Success &= ParseCodeGenArgs(Res.getCodeGenOpts(), Args, DashX, Diags, 2021 Res.getTargetOpts()); 2022 ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), Args); 2023 if (DashX == IK_AST || DashX == IK_LLVM_IR) { 2024 // ObjCAAutoRefCount and Sanitize LangOpts are used to setup the 2025 // PassManager in BackendUtil.cpp. They need to be initializd no matter 2026 // what the input type is. 2027 if (Args.hasArg(OPT_fobjc_arc)) 2028 Res.getLangOpts()->ObjCAutoRefCount = 1; 2029 parseSanitizerKinds("-fsanitize=", Args.getAllArgValues(OPT_fsanitize_EQ), 2030 Diags, Res.getLangOpts()->Sanitize); 2031 } else { 2032 // Other LangOpts are only initialzed when the input is not AST or LLVM IR. 2033 ParseLangArgs(*Res.getLangOpts(), Args, DashX, Diags); 2034 if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC) 2035 Res.getLangOpts()->ObjCExceptions = 1; 2036 } 2037 // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of 2038 // PCH file and find the original header name. Remove the need to do that in 2039 // ParsePreprocessorArgs and remove the FileManager 2040 // parameters from the function and the "FileManager.h" #include. 2041 FileManager FileMgr(Res.getFileSystemOpts()); 2042 ParsePreprocessorArgs(Res.getPreprocessorOpts(), Args, FileMgr, Diags); 2043 ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), Args, 2044 Res.getFrontendOpts().ProgramAction); 2045 return Success; 2046 } 2047 2048 namespace { 2049 2050 class ModuleSignature { 2051 SmallVector<uint64_t, 16> Data; 2052 unsigned CurBit; 2053 uint64_t CurValue; 2054 2055 public: 2056 ModuleSignature() : CurBit(0), CurValue(0) { } 2057 2058 void add(uint64_t Value, unsigned Bits); 2059 void add(StringRef Value); 2060 void flush(); 2061 2062 llvm::APInt getAsInteger() const; 2063 }; 2064 } 2065 2066 void ModuleSignature::add(uint64_t Value, unsigned int NumBits) { 2067 CurValue |= Value << CurBit; 2068 if (CurBit + NumBits < 64) { 2069 CurBit += NumBits; 2070 return; 2071 } 2072 2073 // Add the current word. 2074 Data.push_back(CurValue); 2075 2076 if (CurBit) 2077 CurValue = Value >> (64-CurBit); 2078 else 2079 CurValue = 0; 2080 CurBit = (CurBit+NumBits) & 63; 2081 } 2082 2083 void ModuleSignature::flush() { 2084 if (CurBit == 0) 2085 return; 2086 2087 Data.push_back(CurValue); 2088 CurBit = 0; 2089 CurValue = 0; 2090 } 2091 2092 void ModuleSignature::add(StringRef Value) { 2093 for (auto &c : Value) 2094 add(c, 8); 2095 } 2096 2097 llvm::APInt ModuleSignature::getAsInteger() const { 2098 return llvm::APInt(Data.size() * 64, Data); 2099 } 2100 2101 std::string CompilerInvocation::getModuleHash() const { 2102 // Note: For QoI reasons, the things we use as a hash here should all be 2103 // dumped via the -module-info flag. 2104 using llvm::hash_code; 2105 using llvm::hash_value; 2106 using llvm::hash_combine; 2107 2108 // Start the signature with the compiler version. 2109 // FIXME: We'd rather use something more cryptographically sound than 2110 // CityHash, but this will do for now. 2111 hash_code code = hash_value(getClangFullRepositoryVersion()); 2112 2113 // Extend the signature with the language options 2114 #define LANGOPT(Name, Bits, Default, Description) \ 2115 code = hash_combine(code, LangOpts->Name); 2116 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \ 2117 code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name())); 2118 #define BENIGN_LANGOPT(Name, Bits, Default, Description) 2119 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description) 2120 #include "clang/Basic/LangOptions.def" 2121 2122 for (StringRef Feature : LangOpts->ModuleFeatures) 2123 code = hash_combine(code, Feature); 2124 2125 // Extend the signature with the target options. 2126 code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU, 2127 TargetOpts->ABI); 2128 for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i) 2129 code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]); 2130 2131 // Extend the signature with preprocessor options. 2132 const PreprocessorOptions &ppOpts = getPreprocessorOpts(); 2133 const HeaderSearchOptions &hsOpts = getHeaderSearchOpts(); 2134 code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord); 2135 2136 for (std::vector<std::pair<std::string, bool/*isUndef*/>>::const_iterator 2137 I = getPreprocessorOpts().Macros.begin(), 2138 IEnd = getPreprocessorOpts().Macros.end(); 2139 I != IEnd; ++I) { 2140 // If we're supposed to ignore this macro for the purposes of modules, 2141 // don't put it into the hash. 2142 if (!hsOpts.ModulesIgnoreMacros.empty()) { 2143 // Check whether we're ignoring this macro. 2144 StringRef MacroDef = I->first; 2145 if (hsOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first)) 2146 continue; 2147 } 2148 2149 code = hash_combine(code, I->first, I->second); 2150 } 2151 2152 // Extend the signature with the sysroot. 2153 code = hash_combine(code, hsOpts.Sysroot, hsOpts.UseBuiltinIncludes, 2154 hsOpts.UseStandardSystemIncludes, 2155 hsOpts.UseStandardCXXIncludes, 2156 hsOpts.UseLibcxx); 2157 code = hash_combine(code, hsOpts.ResourceDir); 2158 2159 // Extend the signature with the user build path. 2160 code = hash_combine(code, hsOpts.ModuleUserBuildPath); 2161 2162 // Extend the signature with the module file extensions. 2163 const FrontendOptions &frontendOpts = getFrontendOpts(); 2164 for (auto ext : frontendOpts.ModuleFileExtensions) { 2165 code = ext->hashExtension(code); 2166 } 2167 2168 // Darwin-specific hack: if we have a sysroot, use the contents and 2169 // modification time of 2170 // $sysroot/System/Library/CoreServices/SystemVersion.plist 2171 // as part of the module hash. 2172 if (!hsOpts.Sysroot.empty()) { 2173 SmallString<128> systemVersionFile; 2174 systemVersionFile += hsOpts.Sysroot; 2175 llvm::sys::path::append(systemVersionFile, "System"); 2176 llvm::sys::path::append(systemVersionFile, "Library"); 2177 llvm::sys::path::append(systemVersionFile, "CoreServices"); 2178 llvm::sys::path::append(systemVersionFile, "SystemVersion.plist"); 2179 2180 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer = 2181 llvm::MemoryBuffer::getFile(systemVersionFile); 2182 if (buffer) { 2183 code = hash_combine(code, buffer.get()->getBuffer()); 2184 2185 struct stat statBuf; 2186 if (stat(systemVersionFile.c_str(), &statBuf) == 0) 2187 code = hash_combine(code, statBuf.st_mtime); 2188 } 2189 } 2190 2191 return llvm::APInt(64, code).toString(36, /*Signed=*/false); 2192 } 2193 2194 namespace clang { 2195 2196 template<typename IntTy> 2197 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id, 2198 IntTy Default, 2199 DiagnosticsEngine *Diags) { 2200 IntTy Res = Default; 2201 if (Arg *A = Args.getLastArg(Id)) { 2202 if (StringRef(A->getValue()).getAsInteger(10, Res)) { 2203 if (Diags) 2204 Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args) 2205 << A->getValue(); 2206 } 2207 } 2208 return Res; 2209 } 2210 2211 2212 // Declared in clang/Frontend/Utils.h. 2213 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default, 2214 DiagnosticsEngine *Diags) { 2215 return getLastArgIntValueImpl<int>(Args, Id, Default, Diags); 2216 } 2217 2218 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id, 2219 uint64_t Default, 2220 DiagnosticsEngine *Diags) { 2221 return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags); 2222 } 2223 2224 void BuryPointer(const void *Ptr) { 2225 // This function may be called only a small fixed amount of times per each 2226 // invocation, otherwise we do actually have a leak which we want to report. 2227 // If this function is called more than kGraveYardMaxSize times, the pointers 2228 // will not be properly buried and a leak detector will report a leak, which 2229 // is what we want in such case. 2230 static const size_t kGraveYardMaxSize = 16; 2231 LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize]; 2232 static std::atomic<unsigned> GraveYardSize; 2233 unsigned Idx = GraveYardSize++; 2234 if (Idx >= kGraveYardMaxSize) 2235 return; 2236 GraveYard[Idx] = Ptr; 2237 } 2238 2239 IntrusiveRefCntPtr<vfs::FileSystem> 2240 createVFSFromCompilerInvocation(const CompilerInvocation &CI, 2241 DiagnosticsEngine &Diags) { 2242 if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty()) 2243 return vfs::getRealFileSystem(); 2244 2245 IntrusiveRefCntPtr<vfs::OverlayFileSystem> 2246 Overlay(new vfs::OverlayFileSystem(vfs::getRealFileSystem())); 2247 // earlier vfs files are on the bottom 2248 for (const std::string &File : CI.getHeaderSearchOpts().VFSOverlayFiles) { 2249 llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer = 2250 llvm::MemoryBuffer::getFile(File); 2251 if (!Buffer) { 2252 Diags.Report(diag::err_missing_vfs_overlay_file) << File; 2253 return IntrusiveRefCntPtr<vfs::FileSystem>(); 2254 } 2255 2256 IntrusiveRefCntPtr<vfs::FileSystem> FS = 2257 vfs::getVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr); 2258 if (!FS.get()) { 2259 Diags.Report(diag::err_invalid_vfs_overlay) << File; 2260 return IntrusiveRefCntPtr<vfs::FileSystem>(); 2261 } 2262 Overlay->pushOverlay(FS); 2263 } 2264 return Overlay; 2265 } 2266 } // end namespace clang 2267