clang API Documentation

CompilerInvocation.cpp
Go to the documentation of this file.
00001 //===--- CompilerInvocation.cpp -------------------------------------------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 
00010 #include "clang/Frontend/CompilerInvocation.h"
00011 #include "clang/Basic/FileManager.h"
00012 #include "clang/Basic/Version.h"
00013 #include "clang/Driver/DriverDiagnostic.h"
00014 #include "clang/Driver/Options.h"
00015 #include "clang/Driver/Util.h"
00016 #include "clang/Frontend/FrontendDiagnostic.h"
00017 #include "clang/Frontend/LangStandard.h"
00018 #include "clang/Frontend/Utils.h"
00019 #include "clang/Lex/HeaderSearchOptions.h"
00020 #include "clang/Serialization/ASTReader.h"
00021 #include "llvm/ADT/Hashing.h"
00022 #include "llvm/ADT/SmallVector.h"
00023 #include "llvm/ADT/STLExtras.h"
00024 #include "llvm/ADT/StringExtras.h"
00025 #include "llvm/ADT/StringSwitch.h"
00026 #include "llvm/ADT/Triple.h"
00027 #include "llvm/Option/Arg.h"
00028 #include "llvm/Option/ArgList.h"
00029 #include "llvm/Option/OptTable.h"
00030 #include "llvm/Option/Option.h"
00031 #include "llvm/Support/CodeGen.h"
00032 #include "llvm/Support/ErrorHandling.h"
00033 #include "llvm/Support/FileSystem.h"
00034 #include "llvm/Support/Host.h"
00035 #include "llvm/Support/Path.h"
00036 #include "llvm/Support/Process.h"
00037 #include <atomic>
00038 #include <memory>
00039 #include <sys/stat.h>
00040 #include <system_error>
00041 using namespace clang;
00042 
00043 //===----------------------------------------------------------------------===//
00044 // Initialization.
00045 //===----------------------------------------------------------------------===//
00046 
00047 CompilerInvocationBase::CompilerInvocationBase()
00048   : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
00049     DiagnosticOpts(new DiagnosticOptions()),
00050     HeaderSearchOpts(new HeaderSearchOptions()),
00051     PreprocessorOpts(new PreprocessorOptions()) {}
00052 
00053 CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
00054   : RefCountedBase<CompilerInvocation>(),
00055     LangOpts(new LangOptions(*X.getLangOpts())), 
00056     TargetOpts(new TargetOptions(X.getTargetOpts())),
00057     DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
00058     HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
00059     PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
00060 
00061 CompilerInvocationBase::~CompilerInvocationBase() {}
00062 
00063 //===----------------------------------------------------------------------===//
00064 // Deserialization (from args)
00065 //===----------------------------------------------------------------------===//
00066 
00067 using namespace clang::driver;
00068 using namespace clang::driver::options;
00069 using namespace llvm::opt;
00070 
00071 //
00072 
00073 static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
00074                                      DiagnosticsEngine &Diags) {
00075   unsigned DefaultOpt = 0;
00076   if (IK == IK_OpenCL && !Args.hasArg(OPT_cl_opt_disable))
00077     DefaultOpt = 2;
00078 
00079   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
00080     if (A->getOption().matches(options::OPT_O0))
00081       return 0;
00082 
00083     if (A->getOption().matches(options::OPT_Ofast))
00084       return 3;
00085 
00086     assert (A->getOption().matches(options::OPT_O));
00087 
00088     StringRef S(A->getValue());
00089     if (S == "s" || S == "z" || S.empty())
00090       return 2;
00091 
00092     return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
00093   }
00094 
00095   return DefaultOpt;
00096 }
00097 
00098 static unsigned getOptimizationLevelSize(ArgList &Args) {
00099   if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
00100     if (A->getOption().matches(options::OPT_O)) {
00101       switch (A->getValue()[0]) {
00102       default:
00103         return 0;
00104       case 's':
00105         return 1;
00106       case 'z':
00107         return 2;
00108       }
00109     }
00110   }
00111   return 0;
00112 }
00113 
00114 static void addDiagnosticArgs(ArgList &Args, OptSpecifier Group,
00115                               OptSpecifier GroupWithValue,
00116                               std::vector<std::string> &Diagnostics) {
00117   for (Arg *A : Args.filtered(Group)) {
00118     if (A->getOption().getKind() == Option::FlagClass) {
00119       // The argument is a pure flag (such as OPT_Wall or OPT_Wdeprecated). Add
00120       // its name (minus the "W" or "R" at the beginning) to the warning list.
00121       Diagnostics.push_back(A->getOption().getName().drop_front(1));
00122     } else if (A->getOption().matches(GroupWithValue)) {
00123       // This is -Wfoo= or -Rfoo=, where foo is the name of the diagnostic group.
00124       Diagnostics.push_back(A->getOption().getName().drop_front(1).rtrim("=-"));
00125     } else {
00126       // Otherwise, add its value (for OPT_W_Joined and similar).
00127       for (const char *Arg : A->getValues())
00128         Diagnostics.push_back(Arg);
00129     }
00130   }
00131 }
00132 
00133 static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
00134                               DiagnosticsEngine &Diags) {
00135   using namespace options;
00136   bool Success = true;
00137   if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
00138     StringRef Name = A->getValue();
00139     AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
00140 #define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
00141       .Case(CMDFLAG, NAME##Model)
00142 #include "clang/StaticAnalyzer/Core/Analyses.def"
00143       .Default(NumStores);
00144     if (Value == NumStores) {
00145       Diags.Report(diag::err_drv_invalid_value)
00146         << A->getAsString(Args) << Name;
00147       Success = false;
00148     } else {
00149       Opts.AnalysisStoreOpt = Value;
00150     }
00151   }
00152 
00153   if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
00154     StringRef Name = A->getValue();
00155     AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
00156 #define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
00157       .Case(CMDFLAG, NAME##Model)
00158 #include "clang/StaticAnalyzer/Core/Analyses.def"
00159       .Default(NumConstraints);
00160     if (Value == NumConstraints) {
00161       Diags.Report(diag::err_drv_invalid_value)
00162         << A->getAsString(Args) << Name;
00163       Success = false;
00164     } else {
00165       Opts.AnalysisConstraintsOpt = Value;
00166     }
00167   }
00168 
00169   if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
00170     StringRef Name = A->getValue();
00171     AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
00172 #define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN) \
00173       .Case(CMDFLAG, PD_##NAME)
00174 #include "clang/StaticAnalyzer/Core/Analyses.def"
00175       .Default(NUM_ANALYSIS_DIAG_CLIENTS);
00176     if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
00177       Diags.Report(diag::err_drv_invalid_value)
00178         << A->getAsString(Args) << Name;
00179       Success = false;
00180     } else {
00181       Opts.AnalysisDiagOpt = Value;
00182     }
00183   }
00184 
00185   if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
00186     StringRef Name = A->getValue();
00187     AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
00188 #define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
00189       .Case(CMDFLAG, NAME)
00190 #include "clang/StaticAnalyzer/Core/Analyses.def"
00191       .Default(NumPurgeModes);
00192     if (Value == NumPurgeModes) {
00193       Diags.Report(diag::err_drv_invalid_value)
00194         << A->getAsString(Args) << Name;
00195       Success = false;
00196     } else {
00197       Opts.AnalysisPurgeOpt = Value;
00198     }
00199   }
00200 
00201   if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
00202     StringRef Name = A->getValue();
00203     AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
00204 #define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
00205       .Case(CMDFLAG, NAME)
00206 #include "clang/StaticAnalyzer/Core/Analyses.def"
00207       .Default(NumInliningModes);
00208     if (Value == NumInliningModes) {
00209       Diags.Report(diag::err_drv_invalid_value)
00210         << A->getAsString(Args) << Name;
00211       Success = false;
00212     } else {
00213       Opts.InliningMode = Value;
00214     }
00215   }
00216 
00217   Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
00218   Opts.DisableAllChecks = Args.hasArg(OPT_analyzer_disable_all_checks);
00219 
00220   Opts.visualizeExplodedGraphWithGraphViz =
00221     Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
00222   Opts.visualizeExplodedGraphWithUbiGraph =
00223     Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
00224   Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
00225   Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
00226   Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
00227   Opts.AnalyzeNestedBlocks =
00228     Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
00229   Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
00230   Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
00231   Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
00232   Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
00233   Opts.maxBlockVisitOnPath =
00234       getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
00235   Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
00236   Opts.InlineMaxStackDepth =
00237       getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
00238                          Opts.InlineMaxStackDepth, Diags);
00239 
00240   Opts.CheckersControlList.clear();
00241   for (arg_iterator it = Args.filtered_begin(OPT_analyzer_checker,
00242                                              OPT_analyzer_disable_checker),
00243          ie = Args.filtered_end(); it != ie; ++it) {
00244     const Arg *A = *it;
00245     A->claim();
00246     bool enable = (A->getOption().getID() == OPT_analyzer_checker);
00247     // We can have a list of comma separated checker names, e.g:
00248     // '-analyzer-checker=cocoa,unix'
00249     StringRef checkerList = A->getValue();
00250     SmallVector<StringRef, 4> checkers;
00251     checkerList.split(checkers, ",");
00252     for (unsigned i = 0, e = checkers.size(); i != e; ++i)
00253       Opts.CheckersControlList.push_back(std::make_pair(checkers[i], enable));
00254   }
00255   
00256   // Go through the analyzer configuration options.
00257   for (arg_iterator it = Args.filtered_begin(OPT_analyzer_config),
00258        ie = Args.filtered_end(); it != ie; ++it) {
00259     const Arg *A = *it;
00260     A->claim();
00261     // We can have a list of comma separated config names, e.g:
00262     // '-analyzer-config key1=val1,key2=val2'
00263     StringRef configList = A->getValue();
00264     SmallVector<StringRef, 4> configVals;
00265     configList.split(configVals, ",");
00266     for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
00267       StringRef key, val;
00268       std::tie(key, val) = configVals[i].split("=");
00269       if (val.empty()) {
00270         Diags.Report(SourceLocation(),
00271                      diag::err_analyzer_config_no_value) << configVals[i];
00272         Success = false;
00273         break;
00274       }
00275       if (val.find('=') != StringRef::npos) {
00276         Diags.Report(SourceLocation(),
00277                      diag::err_analyzer_config_multiple_values)
00278           << configVals[i];
00279         Success = false;
00280         break;
00281       }
00282       Opts.Config[key] = val;
00283     }
00284   }
00285 
00286   return Success;
00287 }
00288 
00289 static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
00290   Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
00291   Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
00292   return true;
00293 }
00294 
00295 static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
00296   Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
00297   Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
00298 }
00299 
00300 static StringRef getCodeModel(ArgList &Args, DiagnosticsEngine &Diags) {
00301   if (Arg *A = Args.getLastArg(OPT_mcode_model)) {
00302     StringRef Value = A->getValue();
00303     if (Value == "small" || Value == "kernel" || Value == "medium" ||
00304         Value == "large")
00305       return Value;
00306     Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Value;
00307   }
00308   return "default";
00309 }
00310 
00311 /// \brief Create a new Regex instance out of the string value in \p RpassArg.
00312 /// It returns a pointer to the newly generated Regex instance.
00313 static std::shared_ptr<llvm::Regex>
00314 GenerateOptimizationRemarkRegex(DiagnosticsEngine &Diags, ArgList &Args,
00315                                 Arg *RpassArg) {
00316   StringRef Val = RpassArg->getValue();
00317   std::string RegexError;
00318   std::shared_ptr<llvm::Regex> Pattern = std::make_shared<llvm::Regex>(Val);
00319   if (!Pattern->isValid(RegexError)) {
00320     Diags.Report(diag::err_drv_optimization_remark_pattern)
00321         << RegexError << RpassArg->getAsString(Args);
00322     Pattern.reset();
00323   }
00324   return Pattern;
00325 }
00326 
00327 static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
00328                              DiagnosticsEngine &Diags,
00329                              const TargetOptions &TargetOpts) {
00330   using namespace options;
00331   bool Success = true;
00332 
00333   Opts.OptimizationLevel = getOptimizationLevel(Args, IK, Diags);
00334   // TODO: This could be done in Driver
00335   unsigned MaxOptLevel = 3;
00336   if (Opts.OptimizationLevel > MaxOptLevel) {
00337     // If the optimization level is not supported, fall back on the default optimization
00338     Diags.Report(diag::warn_drv_optimization_value)
00339         << Args.getLastArg(OPT_O)->getAsString(Args) << "-O" << MaxOptLevel;
00340     Opts.OptimizationLevel = MaxOptLevel;
00341   }
00342 
00343   // We must always run at least the always inlining pass.
00344   Opts.setInlining(
00345     (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalInlining
00346                                  : CodeGenOptions::OnlyAlwaysInlining);
00347   // -fno-inline-functions overrides OptimizationLevel > 1.
00348   Opts.NoInline = Args.hasArg(OPT_fno_inline);
00349   Opts.setInlining(Args.hasArg(OPT_fno_inline_functions) ?
00350                      CodeGenOptions::OnlyAlwaysInlining : Opts.getInlining());
00351 
00352   if (Args.hasArg(OPT_gline_tables_only)) {
00353     Opts.setDebugInfo(CodeGenOptions::DebugLineTablesOnly);
00354   } else if (Args.hasArg(OPT_g_Flag) || Args.hasArg(OPT_gdwarf_2) ||
00355              Args.hasArg(OPT_gdwarf_3) || Args.hasArg(OPT_gdwarf_4)) {
00356     bool Default = false;
00357     // Until dtrace (via CTF) and LLDB can deal with distributed debug info,
00358     // Darwin and FreeBSD default to standalone/full debug info.
00359     if (llvm::Triple(TargetOpts.Triple).isOSDarwin() ||
00360         llvm::Triple(TargetOpts.Triple).isOSFreeBSD())
00361       Default = true;
00362 
00363     if (Args.hasFlag(OPT_fstandalone_debug, OPT_fno_standalone_debug, Default))
00364       Opts.setDebugInfo(CodeGenOptions::FullDebugInfo);
00365     else
00366       Opts.setDebugInfo(CodeGenOptions::LimitedDebugInfo);
00367   }
00368   Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
00369   Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
00370   if (Args.hasArg(OPT_gdwarf_2))
00371     Opts.DwarfVersion = 2;
00372   else if (Args.hasArg(OPT_gdwarf_3))
00373     Opts.DwarfVersion = 3;
00374   else if (Args.hasArg(OPT_gdwarf_4))
00375     Opts.DwarfVersion = 4;
00376   else if (Opts.getDebugInfo() != CodeGenOptions::NoDebugInfo)
00377     // Default Dwarf version is 4 if we are generating debug information.
00378     Opts.DwarfVersion = 4;
00379 
00380   Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns);
00381   Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
00382   Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
00383   Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
00384     OPT_fuse_register_sized_bitfield_access);
00385   Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
00386   Opts.StructPathTBAA = !Args.hasArg(OPT_no_struct_path_tbaa);
00387   Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
00388   Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants);
00389   Opts.NoCommon = Args.hasArg(OPT_fno_common);
00390   Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
00391   Opts.OptimizeSize = getOptimizationLevelSize(Args);
00392   Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
00393                             Args.hasArg(OPT_ffreestanding));
00394   Opts.UnrollLoops =
00395       Args.hasFlag(OPT_funroll_loops, OPT_fno_unroll_loops,
00396                    (Opts.OptimizationLevel > 1 && !Opts.OptimizeSize));
00397   Opts.RerollLoops = Args.hasArg(OPT_freroll_loops);
00398 
00399   Opts.DisableIntegratedAS = Args.hasArg(OPT_fno_integrated_as);
00400   Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
00401   Opts.SampleProfileFile = Args.getLastArgValue(OPT_fprofile_sample_use_EQ);
00402   Opts.ProfileInstrGenerate = Args.hasArg(OPT_fprofile_instr_generate);
00403   Opts.InstrProfileInput = Args.getLastArgValue(OPT_fprofile_instr_use_EQ);
00404   Opts.CoverageMapping = Args.hasArg(OPT_fcoverage_mapping);
00405   Opts.DumpCoverageMapping = Args.hasArg(OPT_dump_coverage_mapping);
00406   Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
00407   Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
00408   Opts.CUDAIsDevice = Args.hasArg(OPT_fcuda_is_device);
00409   Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
00410   Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
00411   Opts.CodeModel = getCodeModel(Args, Diags);
00412   Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
00413   Opts.DisableFPElim = Args.hasArg(OPT_mdisable_fp_elim);
00414   Opts.DisableFree = Args.hasArg(OPT_disable_free);
00415   Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
00416   Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
00417   Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable);
00418   Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
00419   Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
00420                        Args.hasArg(OPT_cl_finite_math_only)||
00421                        Args.hasArg(OPT_cl_fast_relaxed_math));
00422   Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
00423                        Args.hasArg(OPT_cl_finite_math_only)||
00424                        Args.hasArg(OPT_cl_fast_relaxed_math));
00425   Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
00426   Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
00427   Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
00428   Opts.NoGlobalMerge = Args.hasArg(OPT_mno_global_merge);
00429   Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
00430   Opts.FatalWarnings = Args.hasArg(OPT_massembler_fatal_warnings);
00431   Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
00432   Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
00433   Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
00434   Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
00435   Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
00436   Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
00437   Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
00438   Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
00439                       Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
00440                       Args.hasArg(OPT_cl_fast_relaxed_math);
00441   Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
00442   Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
00443   Opts.ThreadModel = Args.getLastArgValue(OPT_mthread_model, "posix");
00444   if (Opts.ThreadModel != "posix" && Opts.ThreadModel != "single")
00445     Diags.Report(diag::err_drv_invalid_value)
00446         << Args.getLastArg(OPT_mthread_model)->getAsString(Args)
00447         << Opts.ThreadModel;
00448   Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
00449   Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
00450 
00451   Opts.FunctionSections = Args.hasFlag(OPT_ffunction_sections,
00452                                        OPT_fno_function_sections, false);
00453   Opts.DataSections = Args.hasFlag(OPT_fdata_sections,
00454                                    OPT_fno_data_sections, false);
00455   Opts.MergeFunctions = Args.hasArg(OPT_fmerge_functions);
00456 
00457   Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive);
00458   Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
00459   Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
00460 
00461   Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
00462   Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
00463   Opts.SanitizeRecover = !Args.hasArg(OPT_fno_sanitize_recover);
00464 
00465   Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
00466   Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
00467   Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
00468   if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
00469     Opts.CoverageFile = Args.getLastArgValue(OPT_coverage_file);
00470     Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
00471     Opts.CoverageNoFunctionNamesInData =
00472         Args.hasArg(OPT_coverage_no_function_names_in_data);
00473     if (Args.hasArg(OPT_coverage_version_EQ)) {
00474       StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
00475       if (CoverageVersion.size() != 4) {
00476         Diags.Report(diag::err_drv_invalid_value)
00477             << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
00478             << CoverageVersion;
00479       } else {
00480         memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
00481       }
00482     }
00483   }
00484 
00485   Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
00486   Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
00487   Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
00488   Opts.CompressDebugSections = Args.hasArg(OPT_compress_debug_sections);
00489   Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
00490   Opts.LinkBitcodeFile = Args.getLastArgValue(OPT_mlink_bitcode_file);
00491   Opts.SanitizeCoverage =
00492       getLastArgIntValue(Args, OPT_fsanitize_coverage, 0, Diags);
00493   Opts.SanitizeMemoryTrackOrigins =
00494       getLastArgIntValue(Args, OPT_fsanitize_memory_track_origins_EQ, 0, Diags);
00495   Opts.SanitizeUndefinedTrapOnError =
00496       Args.hasArg(OPT_fsanitize_undefined_trap_on_error);
00497   Opts.SSPBufferSize =
00498       getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
00499   Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
00500   if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
00501     StringRef Val = A->getValue();
00502     unsigned StackAlignment = Opts.StackAlignment;
00503     Val.getAsInteger(10, StackAlignment);
00504     Opts.StackAlignment = StackAlignment;
00505   }
00506 
00507   if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
00508     StringRef Name = A->getValue();
00509     unsigned Method = llvm::StringSwitch<unsigned>(Name)
00510       .Case("legacy", CodeGenOptions::Legacy)
00511       .Case("non-legacy", CodeGenOptions::NonLegacy)
00512       .Case("mixed", CodeGenOptions::Mixed)
00513       .Default(~0U);
00514     if (Method == ~0U) {
00515       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
00516       Success = false;
00517     } else {
00518       Opts.setObjCDispatchMethod(
00519         static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
00520     }
00521   }
00522 
00523   if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
00524     StringRef Name = A->getValue();
00525     unsigned Model = llvm::StringSwitch<unsigned>(Name)
00526         .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
00527         .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
00528         .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
00529         .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
00530         .Default(~0U);
00531     if (Model == ~0U) {
00532       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
00533       Success = false;
00534     } else {
00535       Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
00536     }
00537   }
00538 
00539   if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
00540     StringRef Val = A->getValue();
00541     if (Val == "fast")
00542       Opts.setFPContractMode(CodeGenOptions::FPC_Fast);
00543     else if (Val == "on")
00544       Opts.setFPContractMode(CodeGenOptions::FPC_On);
00545     else if (Val == "off")
00546       Opts.setFPContractMode(CodeGenOptions::FPC_Off);
00547     else
00548       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
00549   }
00550 
00551   if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
00552     if (A->getOption().matches(OPT_fpcc_struct_return)) {
00553       Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
00554     } else {
00555       assert(A->getOption().matches(OPT_freg_struct_return));
00556       Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
00557     }
00558   }
00559 
00560   Opts.DependentLibraries = Args.getAllArgValues(OPT_dependent_lib);
00561   bool NeedLocTracking = false;
00562 
00563   if (Arg *A = Args.getLastArg(OPT_Rpass_EQ)) {
00564     Opts.OptimizationRemarkPattern =
00565         GenerateOptimizationRemarkRegex(Diags, Args, A);
00566     NeedLocTracking = true;
00567   }
00568 
00569   if (Arg *A = Args.getLastArg(OPT_Rpass_missed_EQ)) {
00570     Opts.OptimizationRemarkMissedPattern =
00571         GenerateOptimizationRemarkRegex(Diags, Args, A);
00572     NeedLocTracking = true;
00573   }
00574 
00575   if (Arg *A = Args.getLastArg(OPT_Rpass_analysis_EQ)) {
00576     Opts.OptimizationRemarkAnalysisPattern =
00577         GenerateOptimizationRemarkRegex(Diags, Args, A);
00578     NeedLocTracking = true;
00579   }
00580 
00581   // If the user requested to use a sample profile for PGO, then the
00582   // backend will need to track source location information so the profile
00583   // can be incorporated into the IR.
00584   if (!Opts.SampleProfileFile.empty())
00585     NeedLocTracking = true;
00586 
00587   // If the user requested a flag that requires source locations available in
00588   // the backend, make sure that the backend tracks source location information.
00589   if (NeedLocTracking && Opts.getDebugInfo() == CodeGenOptions::NoDebugInfo)
00590     Opts.setDebugInfo(CodeGenOptions::LocTrackingOnly);
00591 
00592   return Success;
00593 }
00594 
00595 static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
00596                                       ArgList &Args) {
00597   using namespace options;
00598   Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
00599   Opts.Targets = Args.getAllArgValues(OPT_MT);
00600   Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
00601   Opts.IncludeModuleFiles = Args.hasArg(OPT_module_file_deps);
00602   Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
00603   Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
00604   Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
00605   Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
00606   Opts.PrintShowIncludes = Args.hasArg(OPT_show_includes);
00607   Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
00608   Opts.ModuleDependencyOutputDir =
00609       Args.getLastArgValue(OPT_module_dependency_dir);
00610 }
00611 
00612 bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
00613                                 DiagnosticsEngine *Diags) {
00614   using namespace options;
00615   bool Success = true;
00616 
00617   Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
00618   if (Arg *A =
00619           Args.getLastArg(OPT_diagnostic_serialized_file, OPT__serialize_diags))
00620     Opts.DiagnosticSerializationFile = A->getValue();
00621   Opts.IgnoreWarnings = Args.hasArg(OPT_w);
00622   Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
00623   Opts.Pedantic = Args.hasArg(OPT_pedantic);
00624   Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
00625   Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
00626   Opts.ShowColors = Args.hasArg(OPT_fcolor_diagnostics);
00627   Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
00628                                  OPT_fno_show_column,
00629                                  /*Default=*/true);
00630   Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
00631   Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
00632   Opts.ShowOptionNames = Args.hasArg(OPT_fdiagnostics_show_option);
00633 
00634   llvm::sys::Process::UseANSIEscapeCodes(Args.hasArg(OPT_fansi_escape_codes));
00635 
00636   // Default behavior is to not to show note include stacks.
00637   Opts.ShowNoteIncludeStack = false;
00638   if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
00639                                OPT_fno_diagnostics_show_note_include_stack))
00640     if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
00641       Opts.ShowNoteIncludeStack = true;
00642 
00643   StringRef ShowOverloads =
00644     Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
00645   if (ShowOverloads == "best")
00646     Opts.setShowOverloads(Ovl_Best);
00647   else if (ShowOverloads == "all")
00648     Opts.setShowOverloads(Ovl_All);
00649   else {
00650     Success = false;
00651     if (Diags)
00652       Diags->Report(diag::err_drv_invalid_value)
00653       << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
00654       << ShowOverloads;
00655   }
00656 
00657   StringRef ShowCategory =
00658     Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
00659   if (ShowCategory == "none")
00660     Opts.ShowCategories = 0;
00661   else if (ShowCategory == "id")
00662     Opts.ShowCategories = 1;
00663   else if (ShowCategory == "name")
00664     Opts.ShowCategories = 2;
00665   else {
00666     Success = false;
00667     if (Diags)
00668       Diags->Report(diag::err_drv_invalid_value)
00669       << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
00670       << ShowCategory;
00671   }
00672 
00673   StringRef Format =
00674     Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
00675   if (Format == "clang")
00676     Opts.setFormat(DiagnosticOptions::Clang);
00677   else if (Format == "msvc")
00678     Opts.setFormat(DiagnosticOptions::Msvc);
00679   else if (Format == "msvc-fallback") {
00680     Opts.setFormat(DiagnosticOptions::Msvc);
00681     Opts.CLFallbackMode = true;
00682   } else if (Format == "vi")
00683     Opts.setFormat(DiagnosticOptions::Vi);
00684   else {
00685     Success = false;
00686     if (Diags)
00687       Diags->Report(diag::err_drv_invalid_value)
00688       << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
00689       << Format;
00690   }
00691   
00692   Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
00693   Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
00694   Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
00695   Opts.VerifyDiagnostics = Args.hasArg(OPT_verify);
00696   Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
00697   Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
00698   Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
00699   Opts.MacroBacktraceLimit =
00700       getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
00701                          DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
00702   Opts.TemplateBacktraceLimit = getLastArgIntValue(
00703       Args, OPT_ftemplate_backtrace_limit,
00704       DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
00705   Opts.ConstexprBacktraceLimit = getLastArgIntValue(
00706       Args, OPT_fconstexpr_backtrace_limit,
00707       DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
00708   Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
00709                                     DiagnosticOptions::DefaultTabStop, Diags);
00710   if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
00711     Opts.TabStop = DiagnosticOptions::DefaultTabStop;
00712     if (Diags)
00713       Diags->Report(diag::warn_ignoring_ftabstop_value)
00714       << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
00715   }
00716   Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
00717   addDiagnosticArgs(Args, OPT_W_Group, OPT_W_value_Group, Opts.Warnings);
00718   addDiagnosticArgs(Args, OPT_R_Group, OPT_R_value_Group, Opts.Remarks);
00719 
00720   return Success;
00721 }
00722 
00723 static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
00724   Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
00725 }
00726 
00727 static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
00728                                    DiagnosticsEngine &Diags) {
00729   using namespace options;
00730   Opts.ProgramAction = frontend::ParseSyntaxOnly;
00731   if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
00732     switch (A->getOption().getID()) {
00733     default:
00734       llvm_unreachable("Invalid option in group!");
00735     case OPT_ast_list:
00736       Opts.ProgramAction = frontend::ASTDeclList; break;
00737     case OPT_ast_dump:
00738     case OPT_ast_dump_lookups:
00739       Opts.ProgramAction = frontend::ASTDump; break;
00740     case OPT_ast_print:
00741       Opts.ProgramAction = frontend::ASTPrint; break;
00742     case OPT_ast_view:
00743       Opts.ProgramAction = frontend::ASTView; break;
00744     case OPT_dump_raw_tokens:
00745       Opts.ProgramAction = frontend::DumpRawTokens; break;
00746     case OPT_dump_tokens:
00747       Opts.ProgramAction = frontend::DumpTokens; break;
00748     case OPT_S:
00749       Opts.ProgramAction = frontend::EmitAssembly; break;
00750     case OPT_emit_llvm_bc:
00751       Opts.ProgramAction = frontend::EmitBC; break;
00752     case OPT_emit_html:
00753       Opts.ProgramAction = frontend::EmitHTML; break;
00754     case OPT_emit_llvm:
00755       Opts.ProgramAction = frontend::EmitLLVM; break;
00756     case OPT_emit_llvm_only:
00757       Opts.ProgramAction = frontend::EmitLLVMOnly; break;
00758     case OPT_emit_codegen_only:
00759       Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
00760     case OPT_emit_obj:
00761       Opts.ProgramAction = frontend::EmitObj; break;
00762     case OPT_fixit_EQ:
00763       Opts.FixItSuffix = A->getValue();
00764       // fall-through!
00765     case OPT_fixit:
00766       Opts.ProgramAction = frontend::FixIt; break;
00767     case OPT_emit_module:
00768       Opts.ProgramAction = frontend::GenerateModule; break;
00769     case OPT_emit_pch:
00770       Opts.ProgramAction = frontend::GeneratePCH; break;
00771     case OPT_emit_pth:
00772       Opts.ProgramAction = frontend::GeneratePTH; break;
00773     case OPT_init_only:
00774       Opts.ProgramAction = frontend::InitOnly; break;
00775     case OPT_fsyntax_only:
00776       Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
00777     case OPT_module_file_info:
00778       Opts.ProgramAction = frontend::ModuleFileInfo; break;
00779     case OPT_verify_pch:
00780       Opts.ProgramAction = frontend::VerifyPCH; break;
00781     case OPT_print_decl_contexts:
00782       Opts.ProgramAction = frontend::PrintDeclContext; break;
00783     case OPT_print_preamble:
00784       Opts.ProgramAction = frontend::PrintPreamble; break;
00785     case OPT_E:
00786       Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
00787     case OPT_rewrite_macros:
00788       Opts.ProgramAction = frontend::RewriteMacros; break;
00789     case OPT_rewrite_objc:
00790       Opts.ProgramAction = frontend::RewriteObjC; break;
00791     case OPT_rewrite_test:
00792       Opts.ProgramAction = frontend::RewriteTest; break;
00793     case OPT_analyze:
00794       Opts.ProgramAction = frontend::RunAnalysis; break;
00795     case OPT_migrate:
00796       Opts.ProgramAction = frontend::MigrateSource; break;
00797     case OPT_Eonly:
00798       Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
00799     }
00800   }
00801 
00802   if (const Arg* A = Args.getLastArg(OPT_plugin)) {
00803     Opts.Plugins.push_back(A->getValue(0));
00804     Opts.ProgramAction = frontend::PluginAction;
00805     Opts.ActionName = A->getValue();
00806 
00807     for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
00808            end = Args.filtered_end(); it != end; ++it) {
00809       if ((*it)->getValue(0) == Opts.ActionName)
00810         Opts.PluginArgs.push_back((*it)->getValue(1));
00811     }
00812   }
00813 
00814   Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
00815   Opts.AddPluginArgs.resize(Opts.AddPluginActions.size());
00816   for (int i = 0, e = Opts.AddPluginActions.size(); i != e; ++i) {
00817     for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
00818            end = Args.filtered_end(); it != end; ++it) {
00819       if ((*it)->getValue(0) == Opts.AddPluginActions[i])
00820         Opts.AddPluginArgs[i].push_back((*it)->getValue(1));
00821     }
00822   }
00823 
00824   if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
00825     Opts.CodeCompletionAt =
00826       ParsedSourceLocation::FromString(A->getValue());
00827     if (Opts.CodeCompletionAt.FileName.empty())
00828       Diags.Report(diag::err_drv_invalid_value)
00829         << A->getAsString(Args) << A->getValue();
00830   }
00831   Opts.DisableFree = Args.hasArg(OPT_disable_free);
00832 
00833   Opts.OutputFile = Args.getLastArgValue(OPT_o);
00834   Opts.Plugins = Args.getAllArgValues(OPT_load);
00835   Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
00836   Opts.ShowHelp = Args.hasArg(OPT_help);
00837   Opts.ShowStats = Args.hasArg(OPT_print_stats);
00838   Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
00839   Opts.ShowVersion = Args.hasArg(OPT_version);
00840   Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
00841   Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
00842   Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
00843   Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
00844   Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
00845   Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
00846   Opts.ASTDumpDecls = Args.hasArg(OPT_ast_dump);
00847   Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
00848   Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
00849   Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
00850   Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
00851   Opts.ModuleFiles = Args.getAllArgValues(OPT_fmodule_file);
00852 
00853   Opts.CodeCompleteOpts.IncludeMacros
00854     = Args.hasArg(OPT_code_completion_macros);
00855   Opts.CodeCompleteOpts.IncludeCodePatterns
00856     = Args.hasArg(OPT_code_completion_patterns);
00857   Opts.CodeCompleteOpts.IncludeGlobals
00858     = !Args.hasArg(OPT_no_code_completion_globals);
00859   Opts.CodeCompleteOpts.IncludeBriefComments
00860     = Args.hasArg(OPT_code_completion_brief_comments);
00861 
00862   Opts.OverrideRecordLayoutsFile
00863     = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
00864   if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
00865                                      OPT_arcmt_modify,
00866                                      OPT_arcmt_migrate)) {
00867     switch (A->getOption().getID()) {
00868     default:
00869       llvm_unreachable("missed a case");
00870     case OPT_arcmt_check:
00871       Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
00872       break;
00873     case OPT_arcmt_modify:
00874       Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
00875       break;
00876     case OPT_arcmt_migrate:
00877       Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
00878       break;
00879     }
00880   }
00881   Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
00882   Opts.ARCMTMigrateReportOut
00883     = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
00884   Opts.ARCMTMigrateEmitARCErrors
00885     = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
00886 
00887   if (Args.hasArg(OPT_objcmt_migrate_literals))
00888     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
00889   if (Args.hasArg(OPT_objcmt_migrate_subscripting))
00890     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
00891   if (Args.hasArg(OPT_objcmt_migrate_property_dot_syntax))
00892     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_PropertyDotSyntax;
00893   if (Args.hasArg(OPT_objcmt_migrate_property))
00894     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
00895   if (Args.hasArg(OPT_objcmt_migrate_readonly_property))
00896     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadonlyProperty;
00897   if (Args.hasArg(OPT_objcmt_migrate_readwrite_property))
00898     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReadwriteProperty;
00899   if (Args.hasArg(OPT_objcmt_migrate_annotation))
00900     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Annotation;
00901   if (Args.hasArg(OPT_objcmt_returns_innerpointer_property))
00902     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ReturnsInnerPointerProperty;
00903   if (Args.hasArg(OPT_objcmt_migrate_instancetype))
00904     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Instancetype;
00905   if (Args.hasArg(OPT_objcmt_migrate_nsmacros))
00906     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsMacros;
00907   if (Args.hasArg(OPT_objcmt_migrate_protocol_conformance))
00908     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_ProtocolConformance;
00909   if (Args.hasArg(OPT_objcmt_atomic_property))
00910     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_AtomicProperty;
00911   if (Args.hasArg(OPT_objcmt_ns_nonatomic_iosonly))
00912     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_NsAtomicIOSOnlyProperty;
00913   if (Args.hasArg(OPT_objcmt_migrate_designated_init))
00914     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_DesignatedInitializer;
00915   if (Args.hasArg(OPT_objcmt_migrate_all))
00916     Opts.ObjCMTAction |= FrontendOptions::ObjCMT_MigrateDecls;
00917 
00918   Opts.ObjCMTWhiteListPath = Args.getLastArgValue(OPT_objcmt_whitelist_dir_path);
00919 
00920   if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
00921       Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
00922     Diags.Report(diag::err_drv_argument_not_allowed_with)
00923       << "ARC migration" << "ObjC migration";
00924   }
00925 
00926   InputKind DashX = IK_None;
00927   if (const Arg *A = Args.getLastArg(OPT_x)) {
00928     DashX = llvm::StringSwitch<InputKind>(A->getValue())
00929       .Case("c", IK_C)
00930       .Case("cl", IK_OpenCL)
00931       .Case("cuda", IK_CUDA)
00932       .Case("c++", IK_CXX)
00933       .Case("objective-c", IK_ObjC)
00934       .Case("objective-c++", IK_ObjCXX)
00935       .Case("cpp-output", IK_PreprocessedC)
00936       .Case("assembler-with-cpp", IK_Asm)
00937       .Case("c++-cpp-output", IK_PreprocessedCXX)
00938       .Case("objective-c-cpp-output", IK_PreprocessedObjC)
00939       .Case("objc-cpp-output", IK_PreprocessedObjC)
00940       .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX)
00941       .Case("objc++-cpp-output", IK_PreprocessedObjCXX)
00942       .Case("c-header", IK_C)
00943       .Case("cl-header", IK_OpenCL)
00944       .Case("objective-c-header", IK_ObjC)
00945       .Case("c++-header", IK_CXX)
00946       .Case("objective-c++-header", IK_ObjCXX)
00947       .Cases("ast", "pcm", IK_AST)
00948       .Case("ir", IK_LLVM_IR)
00949       .Default(IK_None);
00950     if (DashX == IK_None)
00951       Diags.Report(diag::err_drv_invalid_value)
00952         << A->getAsString(Args) << A->getValue();
00953   }
00954 
00955   // '-' is the default input if none is given.
00956   std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
00957   Opts.Inputs.clear();
00958   if (Inputs.empty())
00959     Inputs.push_back("-");
00960   for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
00961     InputKind IK = DashX;
00962     if (IK == IK_None) {
00963       IK = FrontendOptions::getInputKindForExtension(
00964         StringRef(Inputs[i]).rsplit('.').second);
00965       // FIXME: Remove this hack.
00966       if (i == 0)
00967         DashX = IK;
00968     }
00969     Opts.Inputs.push_back(FrontendInputFile(Inputs[i], IK));
00970   }
00971 
00972   return DashX;
00973 }
00974 
00975 std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
00976                                                  void *MainAddr) {
00977   SmallString<128> P(llvm::sys::fs::getMainExecutable(Argv0, MainAddr));
00978 
00979   if (!P.empty()) {
00980     llvm::sys::path::remove_filename(P); // Remove /clang from foo/bin/clang
00981     llvm::sys::path::remove_filename(P); // Remove /bin   from foo/bin
00982 
00983     // Get foo/lib/clang/<version>/include
00984     llvm::sys::path::append(P, "lib", "clang", CLANG_VERSION_STRING);
00985   }
00986 
00987   return P.str();
00988 }
00989 
00990 static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args) {
00991   using namespace options;
00992   Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
00993   Opts.Verbose = Args.hasArg(OPT_v);
00994   Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
00995   Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
00996   Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
00997   if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
00998     Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
00999   Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
01000   Opts.ModuleCachePath = Args.getLastArgValue(OPT_fmodules_cache_path);
01001   Opts.ModuleUserBuildPath = Args.getLastArgValue(OPT_fmodules_user_build_path);
01002   Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
01003   // -fmodules implies -fmodule-maps
01004   Opts.ModuleMaps = Args.hasArg(OPT_fmodule_maps) || Args.hasArg(OPT_fmodules);
01005   Opts.ModuleCachePruneInterval =
01006       getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
01007   Opts.ModuleCachePruneAfter =
01008       getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
01009   Opts.ModulesValidateOncePerBuildSession =
01010       Args.hasArg(OPT_fmodules_validate_once_per_build_session);
01011   Opts.BuildSessionTimestamp =
01012       getLastArgUInt64Value(Args, OPT_fbuild_session_timestamp, 0);
01013   Opts.ModulesValidateSystemHeaders =
01014       Args.hasArg(OPT_fmodules_validate_system_headers);
01015 
01016   for (arg_iterator it = Args.filtered_begin(OPT_fmodules_ignore_macro),
01017                     ie = Args.filtered_end();
01018        it != ie; ++it) {
01019     StringRef MacroDef = (*it)->getValue();
01020     Opts.ModulesIgnoreMacros.insert(MacroDef.split('=').first);
01021   }
01022   std::vector<std::string> ModuleMapFiles =
01023       Args.getAllArgValues(OPT_fmodule_map_file);
01024   Opts.ModuleMapFiles.insert(ModuleMapFiles.begin(), ModuleMapFiles.end());
01025 
01026   // Add -I..., -F..., and -index-header-map options in order.
01027   bool IsIndexHeaderMap = false;
01028   for (arg_iterator it = Args.filtered_begin(OPT_I, OPT_F, 
01029                                              OPT_index_header_map),
01030        ie = Args.filtered_end(); it != ie; ++it) {
01031     if ((*it)->getOption().matches(OPT_index_header_map)) {
01032       // -index-header-map applies to the next -I or -F.
01033       IsIndexHeaderMap = true;
01034       continue;
01035     }
01036         
01037     frontend::IncludeDirGroup Group 
01038       = IsIndexHeaderMap? frontend::IndexHeaderMap : frontend::Angled;
01039     
01040     Opts.AddPath((*it)->getValue(), Group,
01041                  /*IsFramework=*/ (*it)->getOption().matches(OPT_F), true);
01042     IsIndexHeaderMap = false;
01043   }
01044 
01045   // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
01046   StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
01047   for (arg_iterator it = Args.filtered_begin(OPT_iprefix, OPT_iwithprefix,
01048                                              OPT_iwithprefixbefore),
01049          ie = Args.filtered_end(); it != ie; ++it) {
01050     const Arg *A = *it;
01051     if (A->getOption().matches(OPT_iprefix))
01052       Prefix = A->getValue();
01053     else if (A->getOption().matches(OPT_iwithprefix))
01054       Opts.AddPath(Prefix.str() + A->getValue(),
01055                    frontend::After, false, true);
01056     else
01057       Opts.AddPath(Prefix.str() + A->getValue(),
01058                    frontend::Angled, false, true);
01059   }
01060 
01061   for (arg_iterator it = Args.filtered_begin(OPT_idirafter),
01062          ie = Args.filtered_end(); it != ie; ++it)
01063     Opts.AddPath((*it)->getValue(), frontend::After, false, true);
01064   for (arg_iterator it = Args.filtered_begin(OPT_iquote),
01065          ie = Args.filtered_end(); it != ie; ++it)
01066     Opts.AddPath((*it)->getValue(), frontend::Quoted, false, true);
01067   for (arg_iterator it = Args.filtered_begin(OPT_isystem,
01068          OPT_iwithsysroot), ie = Args.filtered_end(); it != ie; ++it)
01069     Opts.AddPath((*it)->getValue(), frontend::System, false,
01070                  !(*it)->getOption().matches(OPT_iwithsysroot));
01071   for (arg_iterator it = Args.filtered_begin(OPT_iframework),
01072          ie = Args.filtered_end(); it != ie; ++it)
01073     Opts.AddPath((*it)->getValue(), frontend::System, true, true);
01074 
01075   // Add the paths for the various language specific isystem flags.
01076   for (arg_iterator it = Args.filtered_begin(OPT_c_isystem),
01077        ie = Args.filtered_end(); it != ie; ++it)
01078     Opts.AddPath((*it)->getValue(), frontend::CSystem, false, true);
01079   for (arg_iterator it = Args.filtered_begin(OPT_cxx_isystem),
01080        ie = Args.filtered_end(); it != ie; ++it)
01081     Opts.AddPath((*it)->getValue(), frontend::CXXSystem, false, true);
01082   for (arg_iterator it = Args.filtered_begin(OPT_objc_isystem),
01083        ie = Args.filtered_end(); it != ie; ++it)
01084     Opts.AddPath((*it)->getValue(), frontend::ObjCSystem, false,true);
01085   for (arg_iterator it = Args.filtered_begin(OPT_objcxx_isystem),
01086        ie = Args.filtered_end(); it != ie; ++it)
01087     Opts.AddPath((*it)->getValue(), frontend::ObjCXXSystem, false, true);
01088 
01089   // Add the internal paths from a driver that detects standard include paths.
01090   for (arg_iterator I = Args.filtered_begin(OPT_internal_isystem,
01091                                             OPT_internal_externc_isystem),
01092                     E = Args.filtered_end();
01093        I != E; ++I) {
01094     frontend::IncludeDirGroup Group = frontend::System;
01095     if ((*I)->getOption().matches(OPT_internal_externc_isystem))
01096       Group = frontend::ExternCSystem;
01097     Opts.AddPath((*I)->getValue(), Group, false, true);
01098   }
01099 
01100   // Add the path prefixes which are implicitly treated as being system headers.
01101   for (arg_iterator I = Args.filtered_begin(OPT_system_header_prefix,
01102                                             OPT_no_system_header_prefix),
01103                     E = Args.filtered_end();
01104        I != E; ++I)
01105     Opts.AddSystemHeaderPrefix(
01106         (*I)->getValue(), (*I)->getOption().matches(OPT_system_header_prefix));
01107 
01108   for (arg_iterator I = Args.filtered_begin(OPT_ivfsoverlay),
01109        E = Args.filtered_end(); I != E; ++I)
01110     Opts.AddVFSOverlayFile((*I)->getValue());
01111 }
01112 
01113 void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
01114                                          LangStandard::Kind LangStd) {
01115   // Set some properties which depend solely on the input kind; it would be nice
01116   // to move these to the language standard, and have the driver resolve the
01117   // input kind + language standard.
01118   if (IK == IK_Asm) {
01119     Opts.AsmPreprocessor = 1;
01120   } else if (IK == IK_ObjC ||
01121              IK == IK_ObjCXX ||
01122              IK == IK_PreprocessedObjC ||
01123              IK == IK_PreprocessedObjCXX) {
01124     Opts.ObjC1 = Opts.ObjC2 = 1;
01125   }
01126 
01127   if (LangStd == LangStandard::lang_unspecified) {
01128     // Based on the base language, pick one.
01129     switch (IK) {
01130     case IK_None:
01131     case IK_AST:
01132     case IK_LLVM_IR:
01133       llvm_unreachable("Invalid input kind!");
01134     case IK_OpenCL:
01135       LangStd = LangStandard::lang_opencl;
01136       break;
01137     case IK_CUDA:
01138       LangStd = LangStandard::lang_cuda;
01139       break;
01140     case IK_Asm:
01141     case IK_C:
01142     case IK_PreprocessedC:
01143     case IK_ObjC:
01144     case IK_PreprocessedObjC:
01145       LangStd = LangStandard::lang_gnu11;
01146       break;
01147     case IK_CXX:
01148     case IK_PreprocessedCXX:
01149     case IK_ObjCXX:
01150     case IK_PreprocessedObjCXX:
01151       LangStd = LangStandard::lang_gnucxx98;
01152       break;
01153     }
01154   }
01155 
01156   const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
01157   Opts.LineComment = Std.hasLineComments();
01158   Opts.C99 = Std.isC99();
01159   Opts.C11 = Std.isC11();
01160   Opts.CPlusPlus = Std.isCPlusPlus();
01161   Opts.CPlusPlus11 = Std.isCPlusPlus11();
01162   Opts.CPlusPlus14 = Std.isCPlusPlus14();
01163   Opts.CPlusPlus1z = Std.isCPlusPlus1z();
01164   Opts.Digraphs = Std.hasDigraphs();
01165   Opts.GNUMode = Std.isGNUMode();
01166   Opts.GNUInline = !Std.isC99();
01167   Opts.HexFloats = Std.hasHexFloats();
01168   Opts.ImplicitInt = Std.hasImplicitInt();
01169 
01170   // Set OpenCL Version.
01171   Opts.OpenCL = LangStd == LangStandard::lang_opencl || IK == IK_OpenCL;
01172   if (LangStd == LangStandard::lang_opencl)
01173     Opts.OpenCLVersion = 100;
01174   else if (LangStd == LangStandard::lang_opencl11)
01175       Opts.OpenCLVersion = 110;
01176   else if (LangStd == LangStandard::lang_opencl12)
01177     Opts.OpenCLVersion = 120;
01178   
01179   // OpenCL has some additional defaults.
01180   if (Opts.OpenCL) {
01181     Opts.AltiVec = 0;
01182     Opts.CXXOperatorNames = 1;
01183     Opts.LaxVectorConversions = 0;
01184     Opts.DefaultFPContract = 1;
01185     Opts.NativeHalfType = 1;
01186   }
01187 
01188   Opts.CUDA = LangStd == LangStandard::lang_cuda || IK == IK_CUDA;
01189 
01190   // OpenCL and C++ both have bool, true, false keywords.
01191   Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
01192 
01193   // OpenCL has half keyword
01194   Opts.Half = Opts.OpenCL;
01195 
01196   // C++ has wchar_t keyword.
01197   Opts.WChar = Opts.CPlusPlus;
01198 
01199   Opts.GNUKeywords = Opts.GNUMode;
01200   Opts.CXXOperatorNames = Opts.CPlusPlus;
01201 
01202   // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
01203   // is specified, or -std is set to a conforming mode.
01204   // Trigraphs are disabled by default in c++1z onwards.
01205   Opts.Trigraphs = !Opts.GNUMode && !Opts.CPlusPlus1z;
01206 
01207   Opts.DollarIdents = !Opts.AsmPreprocessor;
01208 
01209   // C++14 onwards has sized global deallocation functions.
01210   Opts.SizedDeallocation = Opts.CPlusPlus14;
01211 }
01212 
01213 /// Attempt to parse a visibility value out of the given argument.
01214 static Visibility parseVisibility(Arg *arg, ArgList &args,
01215                                   DiagnosticsEngine &diags) {
01216   StringRef value = arg->getValue();
01217   if (value == "default") {
01218     return DefaultVisibility;
01219   } else if (value == "hidden") {
01220     return HiddenVisibility;
01221   } else if (value == "protected") {
01222     // FIXME: diagnose if target does not support protected visibility
01223     return ProtectedVisibility;
01224   }
01225 
01226   diags.Report(diag::err_drv_invalid_value)
01227     << arg->getAsString(args) << value;
01228   return DefaultVisibility;
01229 }
01230 
01231 static unsigned parseMSCVersion(ArgList &Args, DiagnosticsEngine &Diags) {
01232   auto Arg = Args.getLastArg(OPT_fms_compatibility_version);
01233   if (!Arg)
01234     return 0;
01235 
01236   // The MSC versioning scheme involves four versioning components:
01237   //  - Major
01238   //  - Minor
01239   //  - Build
01240   //  - Patch
01241   //
01242   // We accept either the old style (_MSC_VER) value, or a _MSC_FULL_VER value.
01243   // Additionally, the value may be provided in the form of a more readable
01244   // MM.mm.bbbbb.pp version.
01245   //
01246   // Unfortunately, due to the bit-width limitations, we cannot currently encode
01247   // the value for the patch level.
01248 
01249   unsigned VC[4] = {0};
01250   StringRef Value = Arg->getValue();
01251   SmallVector<StringRef, 4> Components;
01252 
01253   Value.split(Components, ".", llvm::array_lengthof(VC));
01254   for (unsigned CI = 0,
01255                 CE = std::min(Components.size(), llvm::array_lengthof(VC));
01256        CI < CE; ++CI) {
01257     if (Components[CI].getAsInteger(10, VC[CI])) {
01258       Diags.Report(diag::err_drv_invalid_value)
01259         << Arg->getAsString(Args) << Value;
01260       return 0;
01261     }
01262   }
01263 
01264   // FIXME we cannot encode the patch level
01265   return VC[0] * 10000000 + VC[1] * 100000 + VC[2];
01266 }
01267 
01268 static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
01269                           DiagnosticsEngine &Diags) {
01270   // FIXME: Cleanup per-file based stuff.
01271   LangStandard::Kind LangStd = LangStandard::lang_unspecified;
01272   if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
01273     LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
01274 #define LANGSTANDARD(id, name, desc, features) \
01275       .Case(name, LangStandard::lang_##id)
01276 #include "clang/Frontend/LangStandards.def"
01277       .Default(LangStandard::lang_unspecified);
01278     if (LangStd == LangStandard::lang_unspecified)
01279       Diags.Report(diag::err_drv_invalid_value)
01280         << A->getAsString(Args) << A->getValue();
01281     else {
01282       // Valid standard, check to make sure language and standard are
01283       // compatible.
01284       const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
01285       switch (IK) {
01286       case IK_C:
01287       case IK_ObjC:
01288       case IK_PreprocessedC:
01289       case IK_PreprocessedObjC:
01290         if (!(Std.isC89() || Std.isC99()))
01291           Diags.Report(diag::err_drv_argument_not_allowed_with)
01292             << A->getAsString(Args) << "C/ObjC";
01293         break;
01294       case IK_CXX:
01295       case IK_ObjCXX:
01296       case IK_PreprocessedCXX:
01297       case IK_PreprocessedObjCXX:
01298         if (!Std.isCPlusPlus())
01299           Diags.Report(diag::err_drv_argument_not_allowed_with)
01300             << A->getAsString(Args) << "C++/ObjC++";
01301         break;
01302       case IK_OpenCL:
01303         if (!Std.isC99())
01304           Diags.Report(diag::err_drv_argument_not_allowed_with)
01305             << A->getAsString(Args) << "OpenCL";
01306         break;
01307       case IK_CUDA:
01308         if (!Std.isCPlusPlus())
01309           Diags.Report(diag::err_drv_argument_not_allowed_with)
01310             << A->getAsString(Args) << "CUDA";
01311         break;
01312       default:
01313         break;
01314       }
01315     }
01316   }
01317 
01318   // -cl-std only applies for OpenCL language standards.
01319   // Override the -std option in this case.
01320   if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
01321     LangStandard::Kind OpenCLLangStd
01322     = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
01323     .Case("CL", LangStandard::lang_opencl)
01324     .Case("CL1.1", LangStandard::lang_opencl11)
01325     .Case("CL1.2", LangStandard::lang_opencl12)
01326     .Default(LangStandard::lang_unspecified);
01327     
01328     if (OpenCLLangStd == LangStandard::lang_unspecified) {
01329       Diags.Report(diag::err_drv_invalid_value)
01330       << A->getAsString(Args) << A->getValue();
01331     }
01332     else
01333       LangStd = OpenCLLangStd;
01334   }
01335   
01336   CompilerInvocation::setLangDefaults(Opts, IK, LangStd);
01337 
01338   // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
01339   // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
01340   // while a subset (the non-C++ GNU keywords) is provided by GCC's
01341   // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
01342   // name, as it doesn't seem a useful distinction.
01343   Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
01344                                   Opts.GNUKeywords);
01345 
01346   if (Args.hasArg(OPT_fno_operator_names))
01347     Opts.CXXOperatorNames = 0;
01348 
01349   if (Opts.ObjC1) {
01350     if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
01351       StringRef value = arg->getValue();
01352       if (Opts.ObjCRuntime.tryParse(value))
01353         Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
01354     }
01355 
01356     if (Args.hasArg(OPT_fobjc_gc_only))
01357       Opts.setGC(LangOptions::GCOnly);
01358     else if (Args.hasArg(OPT_fobjc_gc))
01359       Opts.setGC(LangOptions::HybridGC);
01360     else if (Args.hasArg(OPT_fobjc_arc)) {
01361       Opts.ObjCAutoRefCount = 1;
01362       if (!Opts.ObjCRuntime.allowsARC())
01363         Diags.Report(diag::err_arc_unsupported_on_runtime);
01364 
01365       // Only set ObjCARCWeak if ARC is enabled.
01366       if (Args.hasArg(OPT_fobjc_runtime_has_weak))
01367         Opts.ObjCARCWeak = 1;
01368       else
01369         Opts.ObjCARCWeak = Opts.ObjCRuntime.allowsWeak();
01370     }
01371 
01372     if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
01373       Opts.ObjCInferRelatedResultType = 0;
01374     
01375     if (Args.hasArg(OPT_fobjc_subscripting_legacy_runtime))
01376       Opts.ObjCSubscriptingLegacyRuntime =
01377         (Opts.ObjCRuntime.getKind() == ObjCRuntime::FragileMacOSX);
01378   }
01379     
01380   if (Args.hasArg(OPT_fgnu89_inline))
01381     Opts.GNUInline = 1;
01382 
01383   if (Args.hasArg(OPT_fapple_kext)) {
01384     if (!Opts.CPlusPlus)
01385       Diags.Report(diag::warn_c_kext);
01386     else
01387       Opts.AppleKext = 1;
01388   }
01389 
01390   if (Args.hasArg(OPT_print_ivar_layout))
01391     Opts.ObjCGCBitmapPrint = 1;
01392   if (Args.hasArg(OPT_fno_constant_cfstrings))
01393     Opts.NoConstantCFStrings = 1;
01394 
01395   if (Args.hasArg(OPT_faltivec))
01396     Opts.AltiVec = 1;
01397 
01398   if (Args.hasArg(OPT_pthread))
01399     Opts.POSIXThreads = 1;
01400 
01401   // The value-visibility mode defaults to "default".
01402   if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
01403     Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
01404   } else {
01405     Opts.setValueVisibilityMode(DefaultVisibility);
01406   }
01407 
01408   // The type-visibility mode defaults to the value-visibility mode.
01409   if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
01410     Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
01411   } else {
01412     Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
01413   }
01414 
01415   if (Args.hasArg(OPT_fvisibility_inlines_hidden))
01416     Opts.InlineVisibilityHidden = 1;
01417 
01418   if (Args.hasArg(OPT_ftrapv)) {
01419     Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
01420     // Set the handler, if one is specified.
01421     Opts.OverflowHandler =
01422         Args.getLastArgValue(OPT_ftrapv_handler);
01423   }
01424   else if (Args.hasArg(OPT_fwrapv))
01425     Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
01426 
01427   if (Args.hasArg(OPT_trigraphs))
01428     Opts.Trigraphs = 1;
01429 
01430   Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
01431                                    OPT_fno_dollars_in_identifiers,
01432                                    Opts.DollarIdents);
01433   Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
01434   Opts.MSVCCompat = Args.hasArg(OPT_fms_compatibility);
01435   Opts.MicrosoftExt = Opts.MSVCCompat || Args.hasArg(OPT_fms_extensions);
01436   Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
01437   Opts.MSCompatibilityVersion = parseMSCVersion(Args, Diags);
01438   Opts.VtorDispMode = getLastArgIntValue(Args, OPT_vtordisp_mode_EQ, 1, Diags);
01439   Opts.Borland = Args.hasArg(OPT_fborland_extensions);
01440   Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
01441   Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
01442                                    Opts.ConstStrings);
01443   if (Args.hasArg(OPT_fno_lax_vector_conversions))
01444     Opts.LaxVectorConversions = 0;
01445   if (Args.hasArg(OPT_fno_threadsafe_statics))
01446     Opts.ThreadsafeStatics = 0;
01447   Opts.Exceptions = Args.hasArg(OPT_fexceptions);
01448   Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
01449   Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
01450   Opts.SjLjExceptions = Args.hasArg(OPT_fsjlj_exceptions);
01451   Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
01452 
01453   Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
01454   Opts.RTTIData = Opts.RTTI && !Args.hasArg(OPT_fno_rtti_data);
01455   Opts.Blocks = Args.hasArg(OPT_fblocks);
01456   Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
01457   Opts.Modules = Args.hasArg(OPT_fmodules);
01458   Opts.ModulesStrictDeclUse = Args.hasArg(OPT_fmodules_strict_decluse);
01459   Opts.ModulesDeclUse =
01460       Args.hasArg(OPT_fmodules_decluse) || Opts.ModulesStrictDeclUse;
01461   Opts.ModulesSearchAll = Opts.Modules &&
01462     !Args.hasArg(OPT_fno_modules_search_all) &&
01463     Args.hasArg(OPT_fmodules_search_all);
01464   Opts.ModulesErrorRecovery = !Args.hasArg(OPT_fno_modules_error_recovery);
01465   Opts.CharIsSigned = Opts.OpenCL || !Args.hasArg(OPT_fno_signed_char);
01466   Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
01467   Opts.ShortWChar = Args.hasFlag(OPT_fshort_wchar, OPT_fno_short_wchar, false);
01468   Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
01469   Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
01470   Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
01471   Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
01472   Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
01473   Opts.SizedDeallocation |= Args.hasArg(OPT_fsized_deallocation);
01474   Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
01475   Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
01476   Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
01477   Opts.MathErrno = !Opts.OpenCL && Args.hasArg(OPT_fmath_errno);
01478   Opts.InstantiationDepth =
01479       getLastArgIntValue(Args, OPT_ftemplate_depth, 256, Diags);
01480   Opts.ArrowDepth =
01481       getLastArgIntValue(Args, OPT_foperator_arrow_depth, 256, Diags);
01482   Opts.ConstexprCallDepth =
01483       getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
01484   Opts.ConstexprStepLimit =
01485       getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
01486   Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
01487   Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
01488   Opts.NumLargeByValueCopy =
01489       getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
01490   Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
01491   Opts.ObjCConstantStringClass =
01492     Args.getLastArgValue(OPT_fconstant_string_class);
01493   Opts.ObjCDefaultSynthProperties =
01494     !Args.hasArg(OPT_disable_objc_default_synthesize_properties);
01495   Opts.EncodeExtendedBlockSig =
01496     Args.hasArg(OPT_fencode_extended_block_signature);
01497   Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
01498   Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
01499   Opts.MaxTypeAlign = getLastArgIntValue(Args, OPT_fmax_type_align_EQ, 0, Diags);
01500   Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
01501   Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags);
01502   Opts.Static = Args.hasArg(OPT_static_define);
01503   Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
01504   Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple 
01505                         || Args.hasArg(OPT_fdump_record_layouts);
01506   Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
01507   Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
01508   Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
01509   Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
01510   Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
01511   Opts.MRTD = Args.hasArg(OPT_mrtd);
01512   Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
01513   Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
01514   Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
01515   Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
01516   Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
01517   Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
01518   Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
01519   Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name);
01520   Opts.ImplementationOfModule =
01521       Args.getLastArgValue(OPT_fmodule_implementation_of);
01522   Opts.NativeHalfType = Opts.NativeHalfType;
01523   Opts.HalfArgsAndReturns = Args.hasArg(OPT_fallow_half_arguments_and_returns);
01524 
01525   if (!Opts.CurrentModule.empty() && !Opts.ImplementationOfModule.empty() &&
01526       Opts.CurrentModule != Opts.ImplementationOfModule) {
01527     Diags.Report(diag::err_conflicting_module_names)
01528         << Opts.CurrentModule << Opts.ImplementationOfModule;
01529   }
01530 
01531   if (Arg *A = Args.getLastArg(OPT_faddress_space_map_mangling_EQ)) {
01532     switch (llvm::StringSwitch<unsigned>(A->getValue())
01533       .Case("target", LangOptions::ASMM_Target)
01534       .Case("no", LangOptions::ASMM_Off)
01535       .Case("yes", LangOptions::ASMM_On)
01536       .Default(255)) {
01537     default:
01538       Diags.Report(diag::err_drv_invalid_value) 
01539         << "-faddress-space-map-mangling=" << A->getValue();
01540       break;
01541     case LangOptions::ASMM_Target:
01542       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Target);
01543       break;
01544     case LangOptions::ASMM_On:
01545       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_On);
01546       break;
01547     case LangOptions::ASMM_Off:
01548       Opts.setAddressSpaceMapMangling(LangOptions::ASMM_Off);
01549       break;
01550     }
01551   }
01552 
01553   if (Arg *A = Args.getLastArg(OPT_fms_memptr_rep_EQ)) {
01554     LangOptions::PragmaMSPointersToMembersKind InheritanceModel =
01555         llvm::StringSwitch<LangOptions::PragmaMSPointersToMembersKind>(
01556             A->getValue())
01557             .Case("single",
01558                   LangOptions::PPTMK_FullGeneralitySingleInheritance)
01559             .Case("multiple",
01560                   LangOptions::PPTMK_FullGeneralityMultipleInheritance)
01561             .Case("virtual",
01562                   LangOptions::PPTMK_FullGeneralityVirtualInheritance)
01563             .Default(LangOptions::PPTMK_BestCase);
01564     if (InheritanceModel == LangOptions::PPTMK_BestCase)
01565       Diags.Report(diag::err_drv_invalid_value)
01566           << "-fms-memptr-rep=" << A->getValue();
01567 
01568     Opts.setMSPointerToMemberRepresentationMethod(InheritanceModel);
01569   }
01570 
01571   // Check if -fopenmp= is specified.
01572   if (const Arg *A = Args.getLastArg(options::OPT_fopenmp_EQ)) {
01573     Opts.OpenMP = llvm::StringSwitch<bool>(A->getValue())
01574         .Case("libiomp5", true)
01575         .Default(false);
01576   }
01577 
01578   // Record whether the __DEPRECATED define was requested.
01579   Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
01580                                  OPT_fno_deprecated_macro,
01581                                  Opts.Deprecated);
01582 
01583   // FIXME: Eliminate this dependency.
01584   unsigned Opt = getOptimizationLevel(Args, IK, Diags),
01585        OptSize = getOptimizationLevelSize(Args);
01586   Opts.Optimize = Opt != 0;
01587   Opts.OptimizeSize = OptSize != 0;
01588 
01589   // This is the __NO_INLINE__ define, which just depends on things like the
01590   // optimization level and -fno-inline, not actually whether the backend has
01591   // inlining enabled.
01592   Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline);
01593 
01594   Opts.FastMath = Args.hasArg(OPT_ffast_math);
01595   Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only);
01596 
01597   Opts.RetainCommentsFromSystemHeaders =
01598       Args.hasArg(OPT_fretain_comments_from_system_headers);
01599 
01600   unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
01601   switch (SSP) {
01602   default:
01603     Diags.Report(diag::err_drv_invalid_value)
01604       << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
01605     break;
01606   case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
01607   case 1: Opts.setStackProtector(LangOptions::SSPOn);  break;
01608   case 2: Opts.setStackProtector(LangOptions::SSPStrong); break;
01609   case 3: Opts.setStackProtector(LangOptions::SSPReq); break;
01610   }
01611 
01612   // Parse -fsanitize= arguments.
01613   std::vector<std::string> Sanitizers = Args.getAllArgValues(OPT_fsanitize_EQ);
01614   for (const auto &Sanitizer : Sanitizers) {
01615     SanitizerKind K = llvm::StringSwitch<SanitizerKind>(Sanitizer)
01616 #define SANITIZER(NAME, ID) .Case(NAME, SanitizerKind::ID)
01617 #include "clang/Basic/Sanitizers.def"
01618         .Default(SanitizerKind::Unknown);
01619     if (K == SanitizerKind::Unknown)
01620       Diags.Report(diag::err_drv_invalid_value)
01621         << "-fsanitize=" << Sanitizer;
01622     else
01623       Opts.Sanitize.set(K, true);
01624   }
01625   // -fsanitize-address-field-padding=N has to be a LangOpt, parse it here.
01626   Opts.SanitizeAddressFieldPadding =
01627       getLastArgIntValue(Args, OPT_fsanitize_address_field_padding, 0, Diags);
01628   Opts.SanitizerBlacklistFile = Args.getLastArgValue(OPT_fsanitize_blacklist);
01629 }
01630 
01631 static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
01632                                   FileManager &FileMgr,
01633                                   DiagnosticsEngine &Diags) {
01634   using namespace options;
01635   Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
01636   Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
01637   if (const Arg *A = Args.getLastArg(OPT_token_cache))
01638       Opts.TokenCache = A->getValue();
01639   else
01640     Opts.TokenCache = Opts.ImplicitPTHInclude;
01641   Opts.UsePredefines = !Args.hasArg(OPT_undef);
01642   Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
01643   Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
01644 
01645   Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
01646   for (arg_iterator it = Args.filtered_begin(OPT_error_on_deserialized_pch_decl),
01647          ie = Args.filtered_end(); it != ie; ++it) {
01648     const Arg *A = *it;
01649     Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
01650   }
01651 
01652   if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
01653     StringRef Value(A->getValue());
01654     size_t Comma = Value.find(',');
01655     unsigned Bytes = 0;
01656     unsigned EndOfLine = 0;
01657 
01658     if (Comma == StringRef::npos ||
01659         Value.substr(0, Comma).getAsInteger(10, Bytes) ||
01660         Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
01661       Diags.Report(diag::err_drv_preamble_format);
01662     else {
01663       Opts.PrecompiledPreambleBytes.first = Bytes;
01664       Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
01665     }
01666   }
01667 
01668   // Add macros from the command line.
01669   for (arg_iterator it = Args.filtered_begin(OPT_D, OPT_U),
01670          ie = Args.filtered_end(); it != ie; ++it) {
01671     if ((*it)->getOption().matches(OPT_D))
01672       Opts.addMacroDef((*it)->getValue());
01673     else
01674       Opts.addMacroUndef((*it)->getValue());
01675   }
01676 
01677   Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
01678 
01679   // Add the ordered list of -includes.
01680   for (arg_iterator it = Args.filtered_begin(OPT_include),
01681          ie = Args.filtered_end(); it != ie; ++it) {
01682     const Arg *A = *it;
01683     Opts.Includes.push_back(A->getValue());
01684   }
01685 
01686   for (arg_iterator it = Args.filtered_begin(OPT_chain_include),
01687          ie = Args.filtered_end(); it != ie; ++it) {
01688     const Arg *A = *it;
01689     Opts.ChainedIncludes.push_back(A->getValue());
01690   }
01691 
01692   // Include 'altivec.h' if -faltivec option present
01693   if (Args.hasArg(OPT_faltivec))
01694     Opts.Includes.push_back("altivec.h");
01695 
01696   for (arg_iterator it = Args.filtered_begin(OPT_remap_file),
01697          ie = Args.filtered_end(); it != ie; ++it) {
01698     const Arg *A = *it;
01699     std::pair<StringRef,StringRef> Split =
01700       StringRef(A->getValue()).split(';');
01701 
01702     if (Split.second.empty()) {
01703       Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
01704       continue;
01705     }
01706 
01707     Opts.addRemappedFile(Split.first, Split.second);
01708   }
01709   
01710   if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
01711     StringRef Name = A->getValue();
01712     unsigned Library = llvm::StringSwitch<unsigned>(Name)
01713       .Case("libc++", ARCXX_libcxx)
01714       .Case("libstdc++", ARCXX_libstdcxx)
01715       .Case("none", ARCXX_nolib)
01716       .Default(~0U);
01717     if (Library == ~0U)
01718       Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
01719     else
01720       Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
01721   }
01722 }
01723 
01724 static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
01725                                         ArgList &Args,
01726                                         frontend::ActionKind Action) {
01727   using namespace options;
01728 
01729   switch (Action) {
01730   case frontend::ASTDeclList:
01731   case frontend::ASTDump:
01732   case frontend::ASTPrint:
01733   case frontend::ASTView:
01734   case frontend::EmitAssembly:
01735   case frontend::EmitBC:
01736   case frontend::EmitHTML:
01737   case frontend::EmitLLVM:
01738   case frontend::EmitLLVMOnly:
01739   case frontend::EmitCodeGenOnly:
01740   case frontend::EmitObj:
01741   case frontend::FixIt:
01742   case frontend::GenerateModule:
01743   case frontend::GeneratePCH:
01744   case frontend::GeneratePTH:
01745   case frontend::ParseSyntaxOnly:
01746   case frontend::ModuleFileInfo:
01747   case frontend::VerifyPCH:
01748   case frontend::PluginAction:
01749   case frontend::PrintDeclContext:
01750   case frontend::RewriteObjC:
01751   case frontend::RewriteTest:
01752   case frontend::RunAnalysis:
01753   case frontend::MigrateSource:
01754     Opts.ShowCPP = 0;
01755     break;
01756 
01757   case frontend::DumpRawTokens:
01758   case frontend::DumpTokens:
01759   case frontend::InitOnly:
01760   case frontend::PrintPreamble:
01761   case frontend::PrintPreprocessedInput:
01762   case frontend::RewriteMacros:
01763   case frontend::RunPreprocessorOnly:
01764     Opts.ShowCPP = !Args.hasArg(OPT_dM);
01765     break;
01766   }
01767 
01768   Opts.ShowComments = Args.hasArg(OPT_C);
01769   Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
01770   Opts.ShowMacroComments = Args.hasArg(OPT_CC);
01771   Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
01772   Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
01773 }
01774 
01775 static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) {
01776   using namespace options;
01777   Opts.ABI = Args.getLastArgValue(OPT_target_abi);
01778   Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
01779   Opts.FPMath = Args.getLastArgValue(OPT_mfpmath);
01780   Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
01781   Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
01782   Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
01783 
01784   // Use the default target triple if unspecified.
01785   if (Opts.Triple.empty())
01786     Opts.Triple = llvm::sys::getDefaultTargetTriple();
01787 }
01788 
01789 bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
01790                                         const char *const *ArgBegin,
01791                                         const char *const *ArgEnd,
01792                                         DiagnosticsEngine &Diags) {
01793   bool Success = true;
01794 
01795   // Parse the arguments.
01796   std::unique_ptr<OptTable> Opts(createDriverOptTable());
01797   const unsigned IncludedFlagsBitmask = options::CC1Option;
01798   unsigned MissingArgIndex, MissingArgCount;
01799   std::unique_ptr<InputArgList> Args(
01800       Opts->ParseArgs(ArgBegin, ArgEnd, MissingArgIndex, MissingArgCount,
01801                       IncludedFlagsBitmask));
01802 
01803   // Check for missing argument error.
01804   if (MissingArgCount) {
01805     Diags.Report(diag::err_drv_missing_argument)
01806       << Args->getArgString(MissingArgIndex) << MissingArgCount;
01807     Success = false;
01808   }
01809 
01810   // Issue errors on unknown arguments.
01811   for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
01812          ie = Args->filtered_end(); it != ie; ++it) {
01813     Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Args);
01814     Success = false;
01815   }
01816 
01817   Success = ParseAnalyzerArgs(*Res.getAnalyzerOpts(), *Args, Diags) && Success;
01818   Success = ParseMigratorArgs(Res.getMigratorOpts(), *Args) && Success;
01819   ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), *Args);
01820   Success = ParseDiagnosticArgs(Res.getDiagnosticOpts(), *Args, &Diags)
01821             && Success;
01822   ParseCommentArgs(Res.getLangOpts()->CommentOpts, *Args);
01823   ParseFileSystemArgs(Res.getFileSystemOpts(), *Args);
01824   // FIXME: We shouldn't have to pass the DashX option around here
01825   InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), *Args, Diags);
01826   ParseTargetArgs(Res.getTargetOpts(), *Args);
01827   Success = ParseCodeGenArgs(Res.getCodeGenOpts(), *Args, DashX, Diags,
01828                              Res.getTargetOpts()) && Success;
01829   ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), *Args);
01830   if (DashX != IK_AST && DashX != IK_LLVM_IR) {
01831     ParseLangArgs(*Res.getLangOpts(), *Args, DashX, Diags);
01832     if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
01833       Res.getLangOpts()->ObjCExceptions = 1;
01834   }
01835   // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of
01836   // PCH file and find the original header name. Remove the need to do that in
01837   // ParsePreprocessorArgs and remove the FileManager 
01838   // parameters from the function and the "FileManager.h" #include.
01839   FileManager FileMgr(Res.getFileSystemOpts());
01840   ParsePreprocessorArgs(Res.getPreprocessorOpts(), *Args, FileMgr, Diags);
01841   ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), *Args,
01842                               Res.getFrontendOpts().ProgramAction);
01843   return Success;
01844 }
01845 
01846 namespace {
01847 
01848   class ModuleSignature {
01849     SmallVector<uint64_t, 16> Data;
01850     unsigned CurBit;
01851     uint64_t CurValue;
01852     
01853   public:
01854     ModuleSignature() : CurBit(0), CurValue(0) { }
01855     
01856     void add(uint64_t Value, unsigned Bits);
01857     void add(StringRef Value);
01858     void flush();
01859     
01860     llvm::APInt getAsInteger() const;
01861   };
01862 }
01863 
01864 void ModuleSignature::add(uint64_t Value, unsigned int NumBits) {
01865   CurValue |= Value << CurBit;
01866   if (CurBit + NumBits < 64) {
01867     CurBit += NumBits;
01868     return;
01869   }
01870   
01871   // Add the current word.
01872   Data.push_back(CurValue);
01873   
01874   if (CurBit)
01875     CurValue = Value >> (64-CurBit);
01876   else
01877     CurValue = 0;
01878   CurBit = (CurBit+NumBits) & 63;
01879 }
01880 
01881 void ModuleSignature::flush() {
01882   if (CurBit == 0)
01883     return;
01884   
01885   Data.push_back(CurValue);
01886   CurBit = 0;
01887   CurValue = 0;
01888 }
01889 
01890 void ModuleSignature::add(StringRef Value) {
01891   for (StringRef::iterator I = Value.begin(), IEnd = Value.end(); I != IEnd;++I)
01892     add(*I, 8);
01893 }
01894 
01895 llvm::APInt ModuleSignature::getAsInteger() const {
01896   return llvm::APInt(Data.size() * 64, Data);
01897 }
01898 
01899 std::string CompilerInvocation::getModuleHash() const {
01900   // Note: For QoI reasons, the things we use as a hash here should all be
01901   // dumped via the -module-info flag.
01902   using llvm::hash_code;
01903   using llvm::hash_value;
01904   using llvm::hash_combine;
01905 
01906   // Start the signature with the compiler version.
01907   // FIXME: We'd rather use something more cryptographically sound than
01908   // CityHash, but this will do for now.
01909   hash_code code = hash_value(getClangFullRepositoryVersion());
01910 
01911   // Extend the signature with the language options
01912 #define LANGOPT(Name, Bits, Default, Description) \
01913    code = hash_combine(code, LangOpts->Name);
01914 #define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
01915   code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
01916 #define BENIGN_LANGOPT(Name, Bits, Default, Description)
01917 #define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
01918 #include "clang/Basic/LangOptions.def"
01919   
01920   // Extend the signature with the target options.
01921   code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
01922                       TargetOpts->ABI);
01923   for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i)
01924     code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]);
01925 
01926   // Extend the signature with preprocessor options.
01927   const PreprocessorOptions &ppOpts = getPreprocessorOpts();
01928   const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
01929   code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
01930 
01931   for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator 
01932             I = getPreprocessorOpts().Macros.begin(),
01933          IEnd = getPreprocessorOpts().Macros.end();
01934        I != IEnd; ++I) {
01935     // If we're supposed to ignore this macro for the purposes of modules,
01936     // don't put it into the hash.
01937     if (!hsOpts.ModulesIgnoreMacros.empty()) {
01938       // Check whether we're ignoring this macro.
01939       StringRef MacroDef = I->first;
01940       if (hsOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first))
01941         continue;
01942     }
01943 
01944     code = hash_combine(code, I->first, I->second);
01945   }
01946 
01947   // Extend the signature with the sysroot.
01948   code = hash_combine(code, hsOpts.Sysroot, hsOpts.UseBuiltinIncludes,
01949                       hsOpts.UseStandardSystemIncludes,
01950                       hsOpts.UseStandardCXXIncludes,
01951                       hsOpts.UseLibcxx);
01952   code = hash_combine(code, hsOpts.ResourceDir);
01953 
01954   // Extend the signature with the user build path.
01955   code = hash_combine(code, hsOpts.ModuleUserBuildPath);
01956 
01957   // Darwin-specific hack: if we have a sysroot, use the contents and
01958   // modification time of
01959   //   $sysroot/System/Library/CoreServices/SystemVersion.plist
01960   // as part of the module hash.
01961   if (!hsOpts.Sysroot.empty()) {
01962     SmallString<128> systemVersionFile;
01963     systemVersionFile += hsOpts.Sysroot;
01964     llvm::sys::path::append(systemVersionFile, "System");
01965     llvm::sys::path::append(systemVersionFile, "Library");
01966     llvm::sys::path::append(systemVersionFile, "CoreServices");
01967     llvm::sys::path::append(systemVersionFile, "SystemVersion.plist");
01968 
01969     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> buffer =
01970         llvm::MemoryBuffer::getFile(systemVersionFile.str());
01971     if (buffer) {
01972       code = hash_combine(code, buffer.get()->getBuffer());
01973 
01974       struct stat statBuf;
01975       if (stat(systemVersionFile.c_str(), &statBuf) == 0)
01976         code = hash_combine(code, statBuf.st_mtime);
01977     }
01978   }
01979 
01980   return llvm::APInt(64, code).toString(36, /*Signed=*/false);
01981 }
01982 
01983 namespace clang {
01984 
01985 template<typename IntTy>
01986 static IntTy getLastArgIntValueImpl(const ArgList &Args, OptSpecifier Id,
01987                                     IntTy Default,
01988                                     DiagnosticsEngine *Diags) {
01989   IntTy Res = Default;
01990   if (Arg *A = Args.getLastArg(Id)) {
01991     if (StringRef(A->getValue()).getAsInteger(10, Res)) {
01992       if (Diags)
01993         Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
01994                                                        << A->getValue();
01995     }
01996   }
01997   return Res;
01998 }
01999 
02000 
02001 // Declared in clang/Frontend/Utils.h.
02002 int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
02003                        DiagnosticsEngine *Diags) {
02004   return getLastArgIntValueImpl<int>(Args, Id, Default, Diags);
02005 }
02006 
02007 uint64_t getLastArgUInt64Value(const ArgList &Args, OptSpecifier Id,
02008                                uint64_t Default,
02009                                DiagnosticsEngine *Diags) {
02010   return getLastArgIntValueImpl<uint64_t>(Args, Id, Default, Diags);
02011 }
02012 
02013 void BuryPointer(const void *Ptr) {
02014   // This function may be called only a small fixed amount of times per each
02015   // invocation, otherwise we do actually have a leak which we want to report.
02016   // If this function is called more than kGraveYardMaxSize times, the pointers
02017   // will not be properly buried and a leak detector will report a leak, which
02018   // is what we want in such case.
02019   static const size_t kGraveYardMaxSize = 16;
02020   LLVM_ATTRIBUTE_UNUSED static const void *GraveYard[kGraveYardMaxSize];
02021   static std::atomic<unsigned> GraveYardSize;
02022   unsigned Idx = GraveYardSize++;
02023   if (Idx >= kGraveYardMaxSize)
02024     return;
02025   GraveYard[Idx] = Ptr;
02026 }
02027 
02028 IntrusiveRefCntPtr<vfs::FileSystem>
02029 createVFSFromCompilerInvocation(const CompilerInvocation &CI,
02030                                 DiagnosticsEngine &Diags) {
02031   if (CI.getHeaderSearchOpts().VFSOverlayFiles.empty())
02032     return vfs::getRealFileSystem();
02033 
02034   IntrusiveRefCntPtr<vfs::OverlayFileSystem>
02035     Overlay(new vfs::OverlayFileSystem(vfs::getRealFileSystem()));
02036   // earlier vfs files are on the bottom
02037   for (const std::string &File : CI.getHeaderSearchOpts().VFSOverlayFiles) {
02038     llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Buffer =
02039         llvm::MemoryBuffer::getFile(File);
02040     if (!Buffer) {
02041       Diags.Report(diag::err_missing_vfs_overlay_file) << File;
02042       return IntrusiveRefCntPtr<vfs::FileSystem>();
02043     }
02044 
02045     IntrusiveRefCntPtr<vfs::FileSystem> FS =
02046         vfs::getVFSFromYAML(std::move(Buffer.get()), /*DiagHandler*/ nullptr);
02047     if (!FS.get()) {
02048       Diags.Report(diag::err_invalid_vfs_overlay) << File;
02049       return IntrusiveRefCntPtr<vfs::FileSystem>();
02050     }
02051     Overlay->pushOverlay(FS);
02052   }
02053   return Overlay;
02054 }
02055 } // end namespace clang