1//===--- CompilerInvocation.cpp -------------------------------------------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "clang/Frontend/CompilerInvocation.h"
11#include "clang/Basic/Diagnostic.h"
12#include "clang/Basic/FileManager.h"
13#include "clang/Basic/Version.h"
14#include "clang/Driver/DriverDiagnostic.h"
15#include "clang/Driver/Options.h"
16#include "clang/Driver/Util.h"
17#include "clang/Frontend/LangStandard.h"
18#include "clang/Frontend/Utils.h"
19#include "clang/Lex/HeaderSearchOptions.h"
20#include "clang/Serialization/ASTReader.h"
21#include "llvm/ADT/Hashing.h"
22#include "llvm/ADT/OwningPtr.h"
23#include "llvm/ADT/SmallVector.h"
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/ADT/Triple.h"
27#include "llvm/Option/Arg.h"
28#include "llvm/Option/ArgList.h"
29#include "llvm/Option/OptTable.h"
30#include "llvm/Option/Option.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/FileSystem.h"
33#include "llvm/Support/Host.h"
34#include "llvm/Support/Path.h"
35#include "llvm/Support/system_error.h"
36#include <sys/stat.h>
37using namespace clang;
38
39//===----------------------------------------------------------------------===//
40// Initialization.
41//===----------------------------------------------------------------------===//
42
43CompilerInvocationBase::CompilerInvocationBase()
44  : LangOpts(new LangOptions()), TargetOpts(new TargetOptions()),
45    DiagnosticOpts(new DiagnosticOptions()),
46    HeaderSearchOpts(new HeaderSearchOptions()),
47    PreprocessorOpts(new PreprocessorOptions()) {}
48
49CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
50  : RefCountedBase<CompilerInvocation>(),
51    LangOpts(new LangOptions(*X.getLangOpts())),
52    TargetOpts(new TargetOptions(X.getTargetOpts())),
53    DiagnosticOpts(new DiagnosticOptions(X.getDiagnosticOpts())),
54    HeaderSearchOpts(new HeaderSearchOptions(X.getHeaderSearchOpts())),
55    PreprocessorOpts(new PreprocessorOptions(X.getPreprocessorOpts())) {}
56
57//===----------------------------------------------------------------------===//
58// Deserialization (from args)
59//===----------------------------------------------------------------------===//
60
61using namespace clang::driver;
62using namespace clang::driver::options;
63using namespace llvm::opt;
64
65//
66
67static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
68                                     DiagnosticsEngine &Diags) {
69  unsigned DefaultOpt = 0;
70  if (IK == IK_OpenCL && !Args.hasArg(OPT_cl_opt_disable))
71    DefaultOpt = 2;
72
73  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
74    if (A->getOption().matches(options::OPT_O0))
75      return 0;
76
77    if (A->getOption().matches(options::OPT_Ofast))
78      return 3;
79
80    assert (A->getOption().matches(options::OPT_O));
81
82    StringRef S(A->getValue());
83    if (S == "s" || S == "z" || S.empty())
84      return 2;
85
86    return getLastArgIntValue(Args, OPT_O, DefaultOpt, Diags);
87  }
88
89  return DefaultOpt;
90}
91
92static unsigned getOptimizationLevelSize(ArgList &Args) {
93  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
94    if (A->getOption().matches(options::OPT_O)) {
95      switch (A->getValue()[0]) {
96      default:
97        return 0;
98      case 's':
99        return 1;
100      case 'z':
101        return 2;
102      }
103    }
104  }
105  return 0;
106}
107
108static void addWarningArgs(ArgList &Args, std::vector<std::string> &Warnings) {
109  for (arg_iterator I = Args.filtered_begin(OPT_W_Group),
110         E = Args.filtered_end(); I != E; ++I) {
111    Arg *A = *I;
112    // If the argument is a pure flag, add its name (minus the "W" at the beginning)
113    // to the warning list. Else, add its value (for the OPT_W case).
114    if (A->getOption().getKind() == Option::FlagClass) {
115      Warnings.push_back(A->getOption().getName().substr(1));
116    } else {
117      for (unsigned Idx = 0, End = A->getNumValues();
118           Idx < End; ++Idx) {
119        StringRef V = A->getValue(Idx);
120        // "-Wl," and such are not warning options.
121        // FIXME: Should be handled by putting these in separate flags.
122        if (V.startswith("l,") || V.startswith("a,") || V.startswith("p,"))
123          continue;
124
125        Warnings.push_back(V);
126      }
127    }
128  }
129}
130
131static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
132                              DiagnosticsEngine &Diags) {
133  using namespace options;
134  bool Success = true;
135  if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
136    StringRef Name = A->getValue();
137    AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
138#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
139      .Case(CMDFLAG, NAME##Model)
140#include "clang/StaticAnalyzer/Core/Analyses.def"
141      .Default(NumStores);
142    if (Value == NumStores) {
143      Diags.Report(diag::err_drv_invalid_value)
144        << A->getAsString(Args) << Name;
145      Success = false;
146    } else {
147      Opts.AnalysisStoreOpt = Value;
148    }
149  }
150
151  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
152    StringRef Name = A->getValue();
153    AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
154#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
155      .Case(CMDFLAG, NAME##Model)
156#include "clang/StaticAnalyzer/Core/Analyses.def"
157      .Default(NumConstraints);
158    if (Value == NumConstraints) {
159      Diags.Report(diag::err_drv_invalid_value)
160        << A->getAsString(Args) << Name;
161      Success = false;
162    } else {
163      Opts.AnalysisConstraintsOpt = Value;
164    }
165  }
166
167  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
168    StringRef Name = A->getValue();
169    AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
170#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREAT) \
171      .Case(CMDFLAG, PD_##NAME)
172#include "clang/StaticAnalyzer/Core/Analyses.def"
173      .Default(NUM_ANALYSIS_DIAG_CLIENTS);
174    if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
175      Diags.Report(diag::err_drv_invalid_value)
176        << A->getAsString(Args) << Name;
177      Success = false;
178    } else {
179      Opts.AnalysisDiagOpt = Value;
180    }
181  }
182
183  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
184    StringRef Name = A->getValue();
185    AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
186#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
187      .Case(CMDFLAG, NAME)
188#include "clang/StaticAnalyzer/Core/Analyses.def"
189      .Default(NumPurgeModes);
190    if (Value == NumPurgeModes) {
191      Diags.Report(diag::err_drv_invalid_value)
192        << A->getAsString(Args) << Name;
193      Success = false;
194    } else {
195      Opts.AnalysisPurgeOpt = Value;
196    }
197  }
198
199  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
200    StringRef Name = A->getValue();
201    AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
202#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
203      .Case(CMDFLAG, NAME)
204#include "clang/StaticAnalyzer/Core/Analyses.def"
205      .Default(NumInliningModes);
206    if (Value == NumInliningModes) {
207      Diags.Report(diag::err_drv_invalid_value)
208        << A->getAsString(Args) << Name;
209      Success = false;
210    } else {
211      Opts.InliningMode = Value;
212    }
213  }
214
215  Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
216  Opts.visualizeExplodedGraphWithGraphViz =
217    Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
218  Opts.visualizeExplodedGraphWithUbiGraph =
219    Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
220  Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
221  Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
222  Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
223  Opts.AnalyzeNestedBlocks =
224    Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
225  Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
226  Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
227  Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
228  Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
229  Opts.maxBlockVisitOnPath =
230      getLastArgIntValue(Args, OPT_analyzer_max_loop, 4, Diags);
231  Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
232  Opts.InlineMaxStackDepth =
233      getLastArgIntValue(Args, OPT_analyzer_inline_max_stack_depth,
234                         Opts.InlineMaxStackDepth, Diags);
235
236  Opts.CheckersControlList.clear();
237  for (arg_iterator it = Args.filtered_begin(OPT_analyzer_checker,
238                                             OPT_analyzer_disable_checker),
239         ie = Args.filtered_end(); it != ie; ++it) {
240    const Arg *A = *it;
241    A->claim();
242    bool enable = (A->getOption().getID() == OPT_analyzer_checker);
243    // We can have a list of comma separated checker names, e.g:
244    // '-analyzer-checker=cocoa,unix'
245    StringRef checkerList = A->getValue();
246    SmallVector<StringRef, 4> checkers;
247    checkerList.split(checkers, ",");
248    for (unsigned i = 0, e = checkers.size(); i != e; ++i)
249      Opts.CheckersControlList.push_back(std::make_pair(checkers[i], enable));
250  }
251
252  // Go through the analyzer configuration options.
253  for (arg_iterator it = Args.filtered_begin(OPT_analyzer_config),
254       ie = Args.filtered_end(); it != ie; ++it) {
255    const Arg *A = *it;
256    A->claim();
257    // We can have a list of comma separated config names, e.g:
258    // '-analyzer-config key1=val1,key2=val2'
259    StringRef configList = A->getValue();
260    SmallVector<StringRef, 4> configVals;
261    configList.split(configVals, ",");
262    for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
263      StringRef key, val;
264      llvm::tie(key, val) = configVals[i].split("=");
265      if (val.empty()) {
266        Diags.Report(SourceLocation(),
267                     diag::err_analyzer_config_no_value) << configVals[i];
268        Success = false;
269        break;
270      }
271      if (val.find('=') != StringRef::npos) {
272        Diags.Report(SourceLocation(),
273                     diag::err_analyzer_config_multiple_values)
274          << configVals[i];
275        Success = false;
276        break;
277      }
278      Opts.Config[key] = val;
279    }
280  }
281
282  return Success;
283}
284
285static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
286  Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
287  Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
288  return true;
289}
290
291static void ParseCommentArgs(CommentOptions &Opts, ArgList &Args) {
292  Opts.BlockCommandNames = Args.getAllArgValues(OPT_fcomment_block_commands);
293  Opts.ParseAllComments = Args.hasArg(OPT_fparse_all_comments);
294}
295
296static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
297                             DiagnosticsEngine &Diags) {
298  using namespace options;
299  bool Success = true;
300
301  unsigned OptLevel = getOptimizationLevel(Args, IK, Diags);
302  if (OptLevel > 3) {
303    Diags.Report(diag::err_drv_invalid_value)
304      << Args.getLastArg(OPT_O)->getAsString(Args) << OptLevel;
305    OptLevel = 3;
306    Success = false;
307  }
308  Opts.OptimizationLevel = OptLevel;
309
310  // We must always run at least the always inlining pass.
311  Opts.setInlining(
312    (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalInlining
313                                 : CodeGenOptions::OnlyAlwaysInlining);
314  // -fno-inline-functions overrides OptimizationLevel > 1.
315  Opts.NoInline = Args.hasArg(OPT_fno_inline);
316  Opts.setInlining(Args.hasArg(OPT_fno_inline_functions) ?
317                     CodeGenOptions::OnlyAlwaysInlining : Opts.getInlining());
318
319  if (Args.hasArg(OPT_gline_tables_only)) {
320    Opts.setDebugInfo(CodeGenOptions::DebugLineTablesOnly);
321  } else if (Args.hasArg(OPT_g_Flag) || Args.hasArg(OPT_gdwarf_2) ||
322             Args.hasArg(OPT_gdwarf_3) || Args.hasArg(OPT_gdwarf_4)) {
323    if (Args.hasFlag(OPT_flimit_debug_info, OPT_fno_limit_debug_info, true))
324      Opts.setDebugInfo(CodeGenOptions::LimitedDebugInfo);
325    else
326      Opts.setDebugInfo(CodeGenOptions::FullDebugInfo);
327  }
328  Opts.DebugColumnInfo = Args.hasArg(OPT_dwarf_column_info);
329  Opts.SplitDwarfFile = Args.getLastArgValue(OPT_split_dwarf_file);
330  if (Args.hasArg(OPT_gdwarf_2))
331    Opts.DwarfVersion = 2;
332  else if (Args.hasArg(OPT_gdwarf_3))
333    Opts.DwarfVersion = 3;
334  else if (Args.hasArg(OPT_gdwarf_4))
335    Opts.DwarfVersion = 4;
336  else if (Opts.getDebugInfo() != CodeGenOptions::NoDebugInfo)
337    // Default Dwarf version is 3 if we are generating debug information.
338    Opts.DwarfVersion = 3;
339
340  Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns);
341  Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
342  Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
343  Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
344    OPT_fuse_register_sized_bitfield_access);
345  Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
346  Opts.StructPathTBAA = Args.hasArg(OPT_struct_path_tbaa);
347  Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
348  Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants);
349  Opts.NoCommon = Args.hasArg(OPT_fno_common);
350  Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
351  Opts.OptimizeSize = getOptimizationLevelSize(Args);
352  Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
353                            Args.hasArg(OPT_ffreestanding));
354  Opts.UnrollLoops = Args.hasArg(OPT_funroll_loops) ||
355                     (Opts.OptimizationLevel > 1 && !Opts.OptimizeSize);
356
357  Opts.Autolink = !Args.hasArg(OPT_fno_autolink);
358  Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
359  Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
360  Opts.CUDAIsDevice = Args.hasArg(OPT_fcuda_is_device);
361  Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
362  Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
363  Opts.CodeModel = Args.getLastArgValue(OPT_mcode_model);
364  Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
365  Opts.DisableFPElim = Args.hasArg(OPT_mdisable_fp_elim);
366  Opts.DisableFree = Args.hasArg(OPT_disable_free);
367  Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
368  Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
369  Opts.HiddenWeakVTables = Args.hasArg(OPT_fhidden_weak_vtables);
370  Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable);
371  Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
372  Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
373                       Args.hasArg(OPT_cl_finite_math_only)||
374                       Args.hasArg(OPT_cl_fast_relaxed_math));
375  Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
376                       Args.hasArg(OPT_cl_finite_math_only)||
377                       Args.hasArg(OPT_cl_fast_relaxed_math));
378  Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
379  Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
380  Opts.NumRegisterParameters = getLastArgIntValue(Args, OPT_mregparm, 0, Diags);
381  Opts.NoGlobalMerge = Args.hasArg(OPT_mno_global_merge);
382  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
383  Opts.EnableSegmentedStacks = Args.hasArg(OPT_split_stacks);
384  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
385  Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
386  Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
387  Opts.NoDwarf2CFIAsm = Args.hasArg(OPT_fno_dwarf2_cfi_asm);
388  Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
389  Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
390  Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
391  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
392                      Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
393                      Args.hasArg(OPT_cl_fast_relaxed_math);
394  Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
395  Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
396  Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
397  Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
398
399  Opts.FunctionSections = Args.hasArg(OPT_ffunction_sections);
400  Opts.DataSections = Args.hasArg(OPT_fdata_sections);
401
402  Opts.VectorizeBB = Args.hasArg(OPT_vectorize_slp_aggressive);
403  Opts.VectorizeLoop = Args.hasArg(OPT_vectorize_loops);
404  Opts.VectorizeSLP = Args.hasArg(OPT_vectorize_slp);
405
406  Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
407  Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
408  Opts.SanitizeRecover = !Args.hasArg(OPT_fno_sanitize_recover);
409
410  Opts.DisableGCov = Args.hasArg(OPT_test_coverage);
411  Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
412  Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
413  if (Opts.EmitGcovArcs || Opts.EmitGcovNotes) {
414  Opts.CoverageFile = Args.getLastArgValue(OPT_coverage_file);
415    Opts.CoverageExtraChecksum = Args.hasArg(OPT_coverage_cfg_checksum);
416    Opts.CoverageNoFunctionNamesInData =
417        Args.hasArg(OPT_coverage_no_function_names_in_data);
418    if (Args.hasArg(OPT_coverage_version_EQ)) {
419      StringRef CoverageVersion = Args.getLastArgValue(OPT_coverage_version_EQ);
420      if (CoverageVersion.size() != 4) {
421        Diags.Report(diag::err_drv_invalid_value)
422            << Args.getLastArg(OPT_coverage_version_EQ)->getAsString(Args)
423            << CoverageVersion;
424      } else {
425        memcpy(Opts.CoverageVersion, CoverageVersion.data(), 4);
426      }
427    }
428  }
429
430  Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
431  Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
432  Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
433  Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
434  Opts.LinkBitcodeFile = Args.getLastArgValue(OPT_mlink_bitcode_file);
435  Opts.SanitizerBlacklistFile = Args.getLastArgValue(OPT_fsanitize_blacklist);
436  Opts.SanitizeMemoryTrackOrigins =
437    Args.hasArg(OPT_fsanitize_memory_track_origins);
438  Opts.SanitizeAddressZeroBaseShadow =
439    Args.hasArg(OPT_fsanitize_address_zero_base_shadow);
440  Opts.SanitizeUndefinedTrapOnError =
441    Args.hasArg(OPT_fsanitize_undefined_trap_on_error);
442  Opts.SSPBufferSize =
443      getLastArgIntValue(Args, OPT_stack_protector_buffer_size, 8, Diags);
444  Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
445  if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
446    StringRef Val = A->getValue();
447    unsigned StackAlignment = Opts.StackAlignment;
448    Val.getAsInteger(10, StackAlignment);
449    Opts.StackAlignment = StackAlignment;
450  }
451
452  if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
453    StringRef Name = A->getValue();
454    unsigned Method = llvm::StringSwitch<unsigned>(Name)
455      .Case("legacy", CodeGenOptions::Legacy)
456      .Case("non-legacy", CodeGenOptions::NonLegacy)
457      .Case("mixed", CodeGenOptions::Mixed)
458      .Default(~0U);
459    if (Method == ~0U) {
460      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
461      Success = false;
462    } else {
463      Opts.setObjCDispatchMethod(
464        static_cast<CodeGenOptions::ObjCDispatchMethodKind>(Method));
465    }
466  }
467
468  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
469    StringRef Name = A->getValue();
470    unsigned Model = llvm::StringSwitch<unsigned>(Name)
471        .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
472        .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
473        .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
474        .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
475        .Default(~0U);
476    if (Model == ~0U) {
477      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
478      Success = false;
479    } else {
480      Opts.setDefaultTLSModel(static_cast<CodeGenOptions::TLSModel>(Model));
481    }
482  }
483
484  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
485    StringRef Val = A->getValue();
486    if (Val == "fast")
487      Opts.setFPContractMode(CodeGenOptions::FPC_Fast);
488    else if (Val == "on")
489      Opts.setFPContractMode(CodeGenOptions::FPC_On);
490    else if (Val == "off")
491      Opts.setFPContractMode(CodeGenOptions::FPC_Off);
492    else
493      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
494  }
495
496  if (Arg *A = Args.getLastArg(OPT_fpcc_struct_return, OPT_freg_struct_return)) {
497    if (A->getOption().matches(OPT_fpcc_struct_return)) {
498      Opts.setStructReturnConvention(CodeGenOptions::SRCK_OnStack);
499    } else {
500      assert(A->getOption().matches(OPT_freg_struct_return));
501      Opts.setStructReturnConvention(CodeGenOptions::SRCK_InRegs);
502    }
503  }
504
505  return Success;
506}
507
508static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
509                                      ArgList &Args) {
510  using namespace options;
511  Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
512  Opts.Targets = Args.getAllArgValues(OPT_MT);
513  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
514  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
515  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
516  Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
517  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
518  Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
519}
520
521bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
522                                DiagnosticsEngine *Diags) {
523  using namespace options;
524  bool Success = true;
525
526  Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
527  Opts.DiagnosticSerializationFile =
528    Args.getLastArgValue(OPT_diagnostic_serialized_file);
529  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
530  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
531  Opts.Pedantic = Args.hasArg(OPT_pedantic);
532  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
533  Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
534  Opts.ShowColors = Args.hasArg(OPT_fcolor_diagnostics);
535  Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
536                                 OPT_fno_show_column,
537                                 /*Default=*/true);
538  Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
539  Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
540  Opts.ShowOptionNames = Args.hasArg(OPT_fdiagnostics_show_option);
541
542  // Default behavior is to not to show note include stacks.
543  Opts.ShowNoteIncludeStack = false;
544  if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
545                               OPT_fno_diagnostics_show_note_include_stack))
546    if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
547      Opts.ShowNoteIncludeStack = true;
548
549  StringRef ShowOverloads =
550    Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
551  if (ShowOverloads == "best")
552    Opts.setShowOverloads(Ovl_Best);
553  else if (ShowOverloads == "all")
554    Opts.setShowOverloads(Ovl_All);
555  else {
556    Success = false;
557    if (Diags)
558      Diags->Report(diag::err_drv_invalid_value)
559      << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
560      << ShowOverloads;
561  }
562
563  StringRef ShowCategory =
564    Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
565  if (ShowCategory == "none")
566    Opts.ShowCategories = 0;
567  else if (ShowCategory == "id")
568    Opts.ShowCategories = 1;
569  else if (ShowCategory == "name")
570    Opts.ShowCategories = 2;
571  else {
572    Success = false;
573    if (Diags)
574      Diags->Report(diag::err_drv_invalid_value)
575      << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
576      << ShowCategory;
577  }
578
579  StringRef Format =
580    Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
581  if (Format == "clang")
582    Opts.setFormat(DiagnosticOptions::Clang);
583  else if (Format == "msvc")
584    Opts.setFormat(DiagnosticOptions::Msvc);
585  else if (Format == "vi")
586    Opts.setFormat(DiagnosticOptions::Vi);
587  else {
588    Success = false;
589    if (Diags)
590      Diags->Report(diag::err_drv_invalid_value)
591      << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
592      << Format;
593  }
594
595  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
596  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
597  Opts.ShowPresumedLoc = !Args.hasArg(OPT_fno_diagnostics_use_presumed_location);
598  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify);
599  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
600  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
601  Opts.ErrorLimit = getLastArgIntValue(Args, OPT_ferror_limit, 0, Diags);
602  Opts.MacroBacktraceLimit =
603      getLastArgIntValue(Args, OPT_fmacro_backtrace_limit,
604                         DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
605  Opts.TemplateBacktraceLimit = getLastArgIntValue(
606      Args, OPT_ftemplate_backtrace_limit,
607      DiagnosticOptions::DefaultTemplateBacktraceLimit, Diags);
608  Opts.ConstexprBacktraceLimit = getLastArgIntValue(
609      Args, OPT_fconstexpr_backtrace_limit,
610      DiagnosticOptions::DefaultConstexprBacktraceLimit, Diags);
611  Opts.TabStop = getLastArgIntValue(Args, OPT_ftabstop,
612                                    DiagnosticOptions::DefaultTabStop, Diags);
613  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
614    Opts.TabStop = DiagnosticOptions::DefaultTabStop;
615    if (Diags)
616      Diags->Report(diag::warn_ignoring_ftabstop_value)
617      << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
618  }
619  Opts.MessageLength = getLastArgIntValue(Args, OPT_fmessage_length, 0, Diags);
620  addWarningArgs(Args, Opts.Warnings);
621
622  return Success;
623}
624
625static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
626  Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
627}
628
629static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
630                                   DiagnosticsEngine &Diags) {
631  using namespace options;
632  Opts.ProgramAction = frontend::ParseSyntaxOnly;
633  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
634    switch (A->getOption().getID()) {
635    default:
636      llvm_unreachable("Invalid option in group!");
637    case OPT_ast_list:
638      Opts.ProgramAction = frontend::ASTDeclList; break;
639    case OPT_ast_dump:
640      Opts.ProgramAction = frontend::ASTDump; break;
641    case OPT_ast_dump_xml:
642      Opts.ProgramAction = frontend::ASTDumpXML; break;
643    case OPT_ast_print:
644      Opts.ProgramAction = frontend::ASTPrint; break;
645    case OPT_ast_view:
646      Opts.ProgramAction = frontend::ASTView; break;
647    case OPT_dump_raw_tokens:
648      Opts.ProgramAction = frontend::DumpRawTokens; break;
649    case OPT_dump_tokens:
650      Opts.ProgramAction = frontend::DumpTokens; break;
651    case OPT_S:
652      Opts.ProgramAction = frontend::EmitAssembly; break;
653    case OPT_emit_llvm_bc:
654      Opts.ProgramAction = frontend::EmitBC; break;
655    case OPT_emit_html:
656      Opts.ProgramAction = frontend::EmitHTML; break;
657    case OPT_emit_llvm:
658      Opts.ProgramAction = frontend::EmitLLVM; break;
659    case OPT_emit_llvm_only:
660      Opts.ProgramAction = frontend::EmitLLVMOnly; break;
661    case OPT_emit_codegen_only:
662      Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
663    case OPT_emit_obj:
664      Opts.ProgramAction = frontend::EmitObj; break;
665    case OPT_fixit_EQ:
666      Opts.FixItSuffix = A->getValue();
667      // fall-through!
668    case OPT_fixit:
669      Opts.ProgramAction = frontend::FixIt; break;
670    case OPT_emit_module:
671      Opts.ProgramAction = frontend::GenerateModule; break;
672    case OPT_emit_pch:
673      Opts.ProgramAction = frontend::GeneratePCH; break;
674    case OPT_emit_pth:
675      Opts.ProgramAction = frontend::GeneratePTH; break;
676    case OPT_init_only:
677      Opts.ProgramAction = frontend::InitOnly; break;
678    case OPT_fsyntax_only:
679      Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
680    case OPT_module_file_info:
681      Opts.ProgramAction = frontend::ModuleFileInfo; break;
682    case OPT_print_decl_contexts:
683      Opts.ProgramAction = frontend::PrintDeclContext; break;
684    case OPT_print_preamble:
685      Opts.ProgramAction = frontend::PrintPreamble; break;
686    case OPT_E:
687      Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
688    case OPT_rewrite_macros:
689      Opts.ProgramAction = frontend::RewriteMacros; break;
690    case OPT_rewrite_objc:
691      Opts.ProgramAction = frontend::RewriteObjC; break;
692    case OPT_rewrite_test:
693      Opts.ProgramAction = frontend::RewriteTest; break;
694    case OPT_analyze:
695      Opts.ProgramAction = frontend::RunAnalysis; break;
696    case OPT_migrate:
697      Opts.ProgramAction = frontend::MigrateSource; break;
698    case OPT_Eonly:
699      Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
700    }
701  }
702
703  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
704    Opts.Plugins.push_back(A->getValue(0));
705    Opts.ProgramAction = frontend::PluginAction;
706    Opts.ActionName = A->getValue();
707
708    for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
709           end = Args.filtered_end(); it != end; ++it) {
710      if ((*it)->getValue(0) == Opts.ActionName)
711        Opts.PluginArgs.push_back((*it)->getValue(1));
712    }
713  }
714
715  Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
716  Opts.AddPluginArgs.resize(Opts.AddPluginActions.size());
717  for (int i = 0, e = Opts.AddPluginActions.size(); i != e; ++i) {
718    for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
719           end = Args.filtered_end(); it != end; ++it) {
720      if ((*it)->getValue(0) == Opts.AddPluginActions[i])
721        Opts.AddPluginArgs[i].push_back((*it)->getValue(1));
722    }
723  }
724
725  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
726    Opts.CodeCompletionAt =
727      ParsedSourceLocation::FromString(A->getValue());
728    if (Opts.CodeCompletionAt.FileName.empty())
729      Diags.Report(diag::err_drv_invalid_value)
730        << A->getAsString(Args) << A->getValue();
731  }
732  Opts.DisableFree = Args.hasArg(OPT_disable_free);
733
734  Opts.OutputFile = Args.getLastArgValue(OPT_o);
735  Opts.Plugins = Args.getAllArgValues(OPT_load);
736  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
737  Opts.ShowHelp = Args.hasArg(OPT_help);
738  Opts.ShowStats = Args.hasArg(OPT_print_stats);
739  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
740  Opts.ShowVersion = Args.hasArg(OPT_version);
741  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
742  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
743  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
744  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
745  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
746  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
747  Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
748  Opts.ASTDumpLookups = Args.hasArg(OPT_ast_dump_lookups);
749  Opts.UseGlobalModuleIndex = !Args.hasArg(OPT_fno_modules_global_index);
750  Opts.GenerateGlobalModuleIndex = Opts.UseGlobalModuleIndex;
751
752  Opts.CodeCompleteOpts.IncludeMacros
753    = Args.hasArg(OPT_code_completion_macros);
754  Opts.CodeCompleteOpts.IncludeCodePatterns
755    = Args.hasArg(OPT_code_completion_patterns);
756  Opts.CodeCompleteOpts.IncludeGlobals
757    = !Args.hasArg(OPT_no_code_completion_globals);
758  Opts.CodeCompleteOpts.IncludeBriefComments
759    = Args.hasArg(OPT_code_completion_brief_comments);
760
761  Opts.OverrideRecordLayoutsFile
762    = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
763  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
764                                     OPT_arcmt_modify,
765                                     OPT_arcmt_migrate)) {
766    switch (A->getOption().getID()) {
767    default:
768      llvm_unreachable("missed a case");
769    case OPT_arcmt_check:
770      Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
771      break;
772    case OPT_arcmt_modify:
773      Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
774      break;
775    case OPT_arcmt_migrate:
776      Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
777      break;
778    }
779  }
780  Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
781  Opts.ARCMTMigrateReportOut
782    = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
783  Opts.ARCMTMigrateEmitARCErrors
784    = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
785
786  if (Args.hasArg(OPT_objcmt_migrate_literals))
787    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
788  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
789    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
790  if (Args.hasArg(OPT_objcmt_migrate_property))
791    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Property;
792
793  if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
794      Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
795    Diags.Report(diag::err_drv_argument_not_allowed_with)
796      << "ARC migration" << "ObjC migration";
797  }
798
799  InputKind DashX = IK_None;
800  if (const Arg *A = Args.getLastArg(OPT_x)) {
801    DashX = llvm::StringSwitch<InputKind>(A->getValue())
802      .Case("c", IK_C)
803      .Case("cl", IK_OpenCL)
804      .Case("cuda", IK_CUDA)
805      .Case("c++", IK_CXX)
806      .Case("objective-c", IK_ObjC)
807      .Case("objective-c++", IK_ObjCXX)
808      .Case("cpp-output", IK_PreprocessedC)
809      .Case("assembler-with-cpp", IK_Asm)
810      .Case("c++-cpp-output", IK_PreprocessedCXX)
811      .Case("objective-c-cpp-output", IK_PreprocessedObjC)
812      .Case("objc-cpp-output", IK_PreprocessedObjC)
813      .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX)
814      .Case("objc++-cpp-output", IK_PreprocessedObjCXX)
815      .Case("c-header", IK_C)
816      .Case("cl-header", IK_OpenCL)
817      .Case("objective-c-header", IK_ObjC)
818      .Case("c++-header", IK_CXX)
819      .Case("objective-c++-header", IK_ObjCXX)
820      .Cases("ast", "pcm", IK_AST)
821      .Case("ir", IK_LLVM_IR)
822      .Default(IK_None);
823    if (DashX == IK_None)
824      Diags.Report(diag::err_drv_invalid_value)
825        << A->getAsString(Args) << A->getValue();
826  }
827
828  // '-' is the default input if none is given.
829  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
830  Opts.Inputs.clear();
831  if (Inputs.empty())
832    Inputs.push_back("-");
833  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
834    InputKind IK = DashX;
835    if (IK == IK_None) {
836      IK = FrontendOptions::getInputKindForExtension(
837        StringRef(Inputs[i]).rsplit('.').second);
838      // FIXME: Remove this hack.
839      if (i == 0)
840        DashX = IK;
841    }
842    Opts.Inputs.push_back(FrontendInputFile(Inputs[i], IK));
843  }
844
845  return DashX;
846}
847
848std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
849                                                 void *MainAddr) {
850  SmallString<128> P(llvm::sys::fs::getMainExecutable(Argv0, MainAddr));
851
852  if (!P.empty()) {
853    llvm::sys::path::remove_filename(P); // Remove /clang from foo/bin/clang
854    llvm::sys::path::remove_filename(P); // Remove /bin   from foo/bin
855
856    // Get foo/lib/clang/<version>/include
857    llvm::sys::path::append(P, "lib", "clang", CLANG_VERSION_STRING);
858  }
859
860  return P.str();
861}
862
863static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args) {
864  using namespace options;
865  Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
866  Opts.Verbose = Args.hasArg(OPT_v);
867  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
868  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
869  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
870  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
871    Opts.UseLibcxx = (strcmp(A->getValue(), "libc++") == 0);
872  Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
873  Opts.ModuleCachePath = Args.getLastArgValue(OPT_fmodules_cache_path);
874  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
875  // -fmodules implies -fmodule-maps
876  Opts.ModuleMaps = Args.hasArg(OPT_fmodule_maps) || Args.hasArg(OPT_fmodules);
877  Opts.ModuleCachePruneInterval =
878      getLastArgIntValue(Args, OPT_fmodules_prune_interval, 7 * 24 * 60 * 60);
879  Opts.ModuleCachePruneAfter =
880      getLastArgIntValue(Args, OPT_fmodules_prune_after, 31 * 24 * 60 * 60);
881  for (arg_iterator it = Args.filtered_begin(OPT_fmodules_ignore_macro),
882                    ie = Args.filtered_end();
883       it != ie; ++it) {
884    StringRef MacroDef = (*it)->getValue();
885    Opts.ModulesIgnoreMacros.insert(MacroDef.split('=').first);
886  }
887
888  // Add -I..., -F..., and -index-header-map options in order.
889  bool IsIndexHeaderMap = false;
890  for (arg_iterator it = Args.filtered_begin(OPT_I, OPT_F,
891                                             OPT_index_header_map),
892       ie = Args.filtered_end(); it != ie; ++it) {
893    if ((*it)->getOption().matches(OPT_index_header_map)) {
894      // -index-header-map applies to the next -I or -F.
895      IsIndexHeaderMap = true;
896      continue;
897    }
898
899    frontend::IncludeDirGroup Group
900      = IsIndexHeaderMap? frontend::IndexHeaderMap : frontend::Angled;
901
902    Opts.AddPath((*it)->getValue(), Group,
903                 /*IsFramework=*/ (*it)->getOption().matches(OPT_F), true);
904    IsIndexHeaderMap = false;
905  }
906
907  // Add -iprefix/-iwithprefix/-iwithprefixbefore options.
908  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
909  for (arg_iterator it = Args.filtered_begin(OPT_iprefix, OPT_iwithprefix,
910                                             OPT_iwithprefixbefore),
911         ie = Args.filtered_end(); it != ie; ++it) {
912    const Arg *A = *it;
913    if (A->getOption().matches(OPT_iprefix))
914      Prefix = A->getValue();
915    else if (A->getOption().matches(OPT_iwithprefix))
916      Opts.AddPath(Prefix.str() + A->getValue(),
917                   frontend::After, false, true);
918    else
919      Opts.AddPath(Prefix.str() + A->getValue(),
920                   frontend::Angled, false, true);
921  }
922
923  for (arg_iterator it = Args.filtered_begin(OPT_idirafter),
924         ie = Args.filtered_end(); it != ie; ++it)
925    Opts.AddPath((*it)->getValue(), frontend::After, false, true);
926  for (arg_iterator it = Args.filtered_begin(OPT_iquote),
927         ie = Args.filtered_end(); it != ie; ++it)
928    Opts.AddPath((*it)->getValue(), frontend::Quoted, false, true);
929  for (arg_iterator it = Args.filtered_begin(OPT_isystem,
930         OPT_iwithsysroot), ie = Args.filtered_end(); it != ie; ++it)
931    Opts.AddPath((*it)->getValue(), frontend::System, false,
932                 !(*it)->getOption().matches(OPT_iwithsysroot));
933  for (arg_iterator it = Args.filtered_begin(OPT_iframework),
934         ie = Args.filtered_end(); it != ie; ++it)
935    Opts.AddPath((*it)->getValue(), frontend::System, true, true);
936
937  // Add the paths for the various language specific isystem flags.
938  for (arg_iterator it = Args.filtered_begin(OPT_c_isystem),
939       ie = Args.filtered_end(); it != ie; ++it)
940    Opts.AddPath((*it)->getValue(), frontend::CSystem, false, true);
941  for (arg_iterator it = Args.filtered_begin(OPT_cxx_isystem),
942       ie = Args.filtered_end(); it != ie; ++it)
943    Opts.AddPath((*it)->getValue(), frontend::CXXSystem, false, true);
944  for (arg_iterator it = Args.filtered_begin(OPT_objc_isystem),
945       ie = Args.filtered_end(); it != ie; ++it)
946    Opts.AddPath((*it)->getValue(), frontend::ObjCSystem, false,true);
947  for (arg_iterator it = Args.filtered_begin(OPT_objcxx_isystem),
948       ie = Args.filtered_end(); it != ie; ++it)
949    Opts.AddPath((*it)->getValue(), frontend::ObjCXXSystem, false, true);
950
951  // Add the internal paths from a driver that detects standard include paths.
952  for (arg_iterator I = Args.filtered_begin(OPT_internal_isystem,
953                                            OPT_internal_externc_isystem),
954                    E = Args.filtered_end();
955       I != E; ++I) {
956    frontend::IncludeDirGroup Group = frontend::System;
957    if ((*I)->getOption().matches(OPT_internal_externc_isystem))
958      Group = frontend::ExternCSystem;
959    Opts.AddPath((*I)->getValue(), Group, false, true);
960  }
961
962  // Add the path prefixes which are implicitly treated as being system headers.
963  for (arg_iterator I = Args.filtered_begin(OPT_isystem_prefix,
964                                            OPT_ino_system_prefix),
965                    E = Args.filtered_end();
966       I != E; ++I)
967    Opts.AddSystemHeaderPrefix((*I)->getValue(),
968                               (*I)->getOption().matches(OPT_isystem_prefix));
969}
970
971void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
972                                         LangStandard::Kind LangStd) {
973  // Set some properties which depend solely on the input kind; it would be nice
974  // to move these to the language standard, and have the driver resolve the
975  // input kind + language standard.
976  if (IK == IK_Asm) {
977    Opts.AsmPreprocessor = 1;
978  } else if (IK == IK_ObjC ||
979             IK == IK_ObjCXX ||
980             IK == IK_PreprocessedObjC ||
981             IK == IK_PreprocessedObjCXX) {
982    Opts.ObjC1 = Opts.ObjC2 = 1;
983  }
984
985  if (LangStd == LangStandard::lang_unspecified) {
986    // Based on the base language, pick one.
987    switch (IK) {
988    case IK_None:
989    case IK_AST:
990    case IK_LLVM_IR:
991      llvm_unreachable("Invalid input kind!");
992    case IK_OpenCL:
993      LangStd = LangStandard::lang_opencl;
994      break;
995    case IK_CUDA:
996      LangStd = LangStandard::lang_cuda;
997      break;
998    case IK_Asm:
999    case IK_C:
1000    case IK_PreprocessedC:
1001    case IK_ObjC:
1002    case IK_PreprocessedObjC:
1003      LangStd = LangStandard::lang_gnu99;
1004      break;
1005    case IK_CXX:
1006    case IK_PreprocessedCXX:
1007    case IK_ObjCXX:
1008    case IK_PreprocessedObjCXX:
1009      LangStd = LangStandard::lang_gnucxx98;
1010      break;
1011    }
1012  }
1013
1014  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1015  Opts.LineComment = Std.hasLineComments();
1016  Opts.C99 = Std.isC99();
1017  Opts.C11 = Std.isC11();
1018  Opts.CPlusPlus = Std.isCPlusPlus();
1019  Opts.CPlusPlus11 = Std.isCPlusPlus11();
1020  Opts.CPlusPlus1y = Std.isCPlusPlus1y();
1021  Opts.Digraphs = Std.hasDigraphs();
1022  Opts.GNUMode = Std.isGNUMode();
1023  Opts.GNUInline = !Std.isC99();
1024  Opts.HexFloats = Std.hasHexFloats();
1025  Opts.ImplicitInt = Std.hasImplicitInt();
1026
1027  // Set OpenCL Version.
1028  if (LangStd == LangStandard::lang_opencl) {
1029    Opts.OpenCL = 1;
1030    Opts.OpenCLVersion = 100;
1031  }
1032  else if (LangStd == LangStandard::lang_opencl11) {
1033      Opts.OpenCL = 1;
1034      Opts.OpenCLVersion = 110;
1035  }
1036  else if (LangStd == LangStandard::lang_opencl12) {
1037    Opts.OpenCL = 1;
1038    Opts.OpenCLVersion = 120;
1039  }
1040
1041  // OpenCL has some additional defaults.
1042  if (Opts.OpenCL) {
1043    Opts.AltiVec = 0;
1044    Opts.CXXOperatorNames = 1;
1045    Opts.LaxVectorConversions = 0;
1046    Opts.DefaultFPContract = 1;
1047    Opts.NativeHalfType = 1;
1048  }
1049
1050  if (LangStd == LangStandard::lang_cuda)
1051    Opts.CUDA = 1;
1052
1053  // OpenCL and C++ both have bool, true, false keywords.
1054  Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1055
1056  // C++ has wchar_t keyword.
1057  Opts.WChar = Opts.CPlusPlus;
1058
1059  Opts.GNUKeywords = Opts.GNUMode;
1060  Opts.CXXOperatorNames = Opts.CPlusPlus;
1061
1062  // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
1063  // is specified, or -std is set to a conforming mode.
1064  Opts.Trigraphs = !Opts.GNUMode;
1065
1066  Opts.DollarIdents = !Opts.AsmPreprocessor;
1067}
1068
1069/// Attempt to parse a visibility value out of the given argument.
1070static Visibility parseVisibility(Arg *arg, ArgList &args,
1071                                  DiagnosticsEngine &diags) {
1072  StringRef value = arg->getValue();
1073  if (value == "default") {
1074    return DefaultVisibility;
1075  } else if (value == "hidden") {
1076    return HiddenVisibility;
1077  } else if (value == "protected") {
1078    // FIXME: diagnose if target does not support protected visibility
1079    return ProtectedVisibility;
1080  }
1081
1082  diags.Report(diag::err_drv_invalid_value)
1083    << arg->getAsString(args) << value;
1084  return DefaultVisibility;
1085}
1086
1087static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
1088                          DiagnosticsEngine &Diags) {
1089  // FIXME: Cleanup per-file based stuff.
1090  LangStandard::Kind LangStd = LangStandard::lang_unspecified;
1091  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
1092    LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1093#define LANGSTANDARD(id, name, desc, features) \
1094      .Case(name, LangStandard::lang_##id)
1095#include "clang/Frontend/LangStandards.def"
1096      .Default(LangStandard::lang_unspecified);
1097    if (LangStd == LangStandard::lang_unspecified)
1098      Diags.Report(diag::err_drv_invalid_value)
1099        << A->getAsString(Args) << A->getValue();
1100    else {
1101      // Valid standard, check to make sure language and standard are compatable.
1102      const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1103      switch (IK) {
1104      case IK_C:
1105      case IK_ObjC:
1106      case IK_PreprocessedC:
1107      case IK_PreprocessedObjC:
1108        if (!(Std.isC89() || Std.isC99()))
1109          Diags.Report(diag::err_drv_argument_not_allowed_with)
1110            << A->getAsString(Args) << "C/ObjC";
1111        break;
1112      case IK_CXX:
1113      case IK_ObjCXX:
1114      case IK_PreprocessedCXX:
1115      case IK_PreprocessedObjCXX:
1116        if (!Std.isCPlusPlus())
1117          Diags.Report(diag::err_drv_argument_not_allowed_with)
1118            << A->getAsString(Args) << "C++/ObjC++";
1119        break;
1120      case IK_OpenCL:
1121        if (!Std.isC99())
1122          Diags.Report(diag::err_drv_argument_not_allowed_with)
1123            << A->getAsString(Args) << "OpenCL";
1124        break;
1125      case IK_CUDA:
1126        if (!Std.isCPlusPlus())
1127          Diags.Report(diag::err_drv_argument_not_allowed_with)
1128            << A->getAsString(Args) << "CUDA";
1129        break;
1130      default:
1131        break;
1132      }
1133    }
1134  }
1135
1136  // -cl-std only applies for OpenCL language standards.
1137  // Override the -std option in this case.
1138  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
1139    LangStandard::Kind OpenCLLangStd
1140    = llvm::StringSwitch<LangStandard::Kind>(A->getValue())
1141    .Case("CL", LangStandard::lang_opencl)
1142    .Case("CL1.1", LangStandard::lang_opencl11)
1143    .Case("CL1.2", LangStandard::lang_opencl12)
1144    .Default(LangStandard::lang_unspecified);
1145
1146    if (OpenCLLangStd == LangStandard::lang_unspecified) {
1147      Diags.Report(diag::err_drv_invalid_value)
1148      << A->getAsString(Args) << A->getValue();
1149    }
1150    else
1151      LangStd = OpenCLLangStd;
1152  }
1153
1154  CompilerInvocation::setLangDefaults(Opts, IK, LangStd);
1155
1156  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
1157  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
1158  // while a subset (the non-C++ GNU keywords) is provided by GCC's
1159  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
1160  // name, as it doesn't seem a useful distinction.
1161  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
1162                                  Opts.GNUKeywords);
1163
1164  if (Args.hasArg(OPT_fno_operator_names))
1165    Opts.CXXOperatorNames = 0;
1166
1167  if (Opts.ObjC1) {
1168    if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
1169      StringRef value = arg->getValue();
1170      if (Opts.ObjCRuntime.tryParse(value))
1171        Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
1172    }
1173
1174    if (Args.hasArg(OPT_fobjc_gc_only))
1175      Opts.setGC(LangOptions::GCOnly);
1176    else if (Args.hasArg(OPT_fobjc_gc))
1177      Opts.setGC(LangOptions::HybridGC);
1178    else if (Args.hasArg(OPT_fobjc_arc)) {
1179      Opts.ObjCAutoRefCount = 1;
1180      if (!Opts.ObjCRuntime.allowsARC())
1181        Diags.Report(diag::err_arc_unsupported_on_runtime);
1182
1183      // Only set ObjCARCWeak if ARC is enabled.
1184      if (Args.hasArg(OPT_fobjc_runtime_has_weak))
1185        Opts.ObjCARCWeak = 1;
1186      else
1187        Opts.ObjCARCWeak = Opts.ObjCRuntime.allowsWeak();
1188    }
1189
1190    if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
1191      Opts.ObjCInferRelatedResultType = 0;
1192  }
1193
1194  if (Args.hasArg(OPT_fgnu89_inline))
1195    Opts.GNUInline = 1;
1196
1197  if (Args.hasArg(OPT_fapple_kext)) {
1198    if (!Opts.CPlusPlus)
1199      Diags.Report(diag::warn_c_kext);
1200    else
1201      Opts.AppleKext = 1;
1202  }
1203
1204  if (Args.hasArg(OPT_print_ivar_layout))
1205    Opts.ObjCGCBitmapPrint = 1;
1206  if (Args.hasArg(OPT_fno_constant_cfstrings))
1207    Opts.NoConstantCFStrings = 1;
1208
1209  if (Args.hasArg(OPT_faltivec))
1210    Opts.AltiVec = 1;
1211
1212  if (Args.hasArg(OPT_pthread))
1213    Opts.POSIXThreads = 1;
1214
1215  // The value-visibility mode defaults to "default".
1216  if (Arg *visOpt = Args.getLastArg(OPT_fvisibility)) {
1217    Opts.setValueVisibilityMode(parseVisibility(visOpt, Args, Diags));
1218  } else {
1219    Opts.setValueVisibilityMode(DefaultVisibility);
1220  }
1221
1222  // The type-visibility mode defaults to the value-visibility mode.
1223  if (Arg *typeVisOpt = Args.getLastArg(OPT_ftype_visibility)) {
1224    Opts.setTypeVisibilityMode(parseVisibility(typeVisOpt, Args, Diags));
1225  } else {
1226    Opts.setTypeVisibilityMode(Opts.getValueVisibilityMode());
1227  }
1228
1229  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
1230    Opts.InlineVisibilityHidden = 1;
1231
1232  if (Args.hasArg(OPT_ftrapv)) {
1233    Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
1234    // Set the handler, if one is specified.
1235    Opts.OverflowHandler =
1236        Args.getLastArgValue(OPT_ftrapv_handler);
1237  }
1238  else if (Args.hasArg(OPT_fwrapv))
1239    Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
1240
1241  if (Args.hasArg(OPT_trigraphs))
1242    Opts.Trigraphs = 1;
1243
1244  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
1245                                   OPT_fno_dollars_in_identifiers,
1246                                   Opts.DollarIdents);
1247  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
1248  Opts.MicrosoftExt
1249    = Args.hasArg(OPT_fms_extensions) || Args.hasArg(OPT_fms_compatibility);
1250  Opts.MicrosoftMode = Args.hasArg(OPT_fms_compatibility);
1251  Opts.AsmBlocks = Args.hasArg(OPT_fasm_blocks) || Opts.MicrosoftExt;
1252  Opts.MSCVersion = getLastArgIntValue(Args, OPT_fmsc_version, 0, Diags);
1253  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
1254  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
1255  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
1256                                   Opts.ConstStrings);
1257  if (Args.hasArg(OPT_fno_lax_vector_conversions))
1258    Opts.LaxVectorConversions = 0;
1259  if (Args.hasArg(OPT_fno_threadsafe_statics))
1260    Opts.ThreadsafeStatics = 0;
1261  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
1262  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
1263  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
1264  Opts.SjLjExceptions = Args.hasArg(OPT_fsjlj_exceptions);
1265  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
1266
1267  Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
1268  Opts.Blocks = Args.hasArg(OPT_fblocks);
1269  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
1270  Opts.Modules = Args.hasArg(OPT_fmodules);
1271  Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
1272  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
1273  Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
1274  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
1275  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
1276  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
1277  Opts.NoMathBuiltin = Args.hasArg(OPT_fno_math_builtin);
1278  Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
1279  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
1280  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
1281  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
1282  Opts.MathErrno = Args.hasArg(OPT_fmath_errno);
1283  Opts.InstantiationDepth =
1284      getLastArgIntValue(Args, OPT_ftemplate_depth, 256, Diags);
1285  Opts.ConstexprCallDepth =
1286      getLastArgIntValue(Args, OPT_fconstexpr_depth, 512, Diags);
1287  Opts.ConstexprStepLimit =
1288      getLastArgIntValue(Args, OPT_fconstexpr_steps, 1048576, Diags);
1289  Opts.BracketDepth = getLastArgIntValue(Args, OPT_fbracket_depth, 256, Diags);
1290  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
1291  Opts.NumLargeByValueCopy =
1292      getLastArgIntValue(Args, OPT_Wlarge_by_value_copy_EQ, 0, Diags);
1293  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
1294  Opts.ObjCConstantStringClass =
1295    Args.getLastArgValue(OPT_fconstant_string_class);
1296  Opts.ObjCDefaultSynthProperties =
1297    Args.hasArg(OPT_fobjc_default_synthesize_properties);
1298  Opts.EncodeExtendedBlockSig =
1299    Args.hasArg(OPT_fencode_extended_block_signature);
1300  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
1301  Opts.PackStruct = getLastArgIntValue(Args, OPT_fpack_struct_EQ, 0, Diags);
1302  Opts.PICLevel = getLastArgIntValue(Args, OPT_pic_level, 0, Diags);
1303  Opts.PIELevel = getLastArgIntValue(Args, OPT_pie_level, 0, Diags);
1304  Opts.Static = Args.hasArg(OPT_static_define);
1305  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
1306  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
1307                        || Args.hasArg(OPT_fdump_record_layouts);
1308  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
1309  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
1310  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
1311  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
1312  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
1313  Opts.MRTD = Args.hasArg(OPT_mrtd);
1314  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
1315  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
1316  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
1317  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
1318  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
1319  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
1320  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
1321  Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name);
1322
1323  // Check if -fopenmp is specified.
1324  Opts.OpenMP = Args.hasArg(OPT_fopenmp);
1325
1326  // Record whether the __DEPRECATED define was requested.
1327  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
1328                                 OPT_fno_deprecated_macro,
1329                                 Opts.Deprecated);
1330
1331  // FIXME: Eliminate this dependency.
1332  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
1333       OptSize = getOptimizationLevelSize(Args);
1334  Opts.Optimize = Opt != 0;
1335  Opts.OptimizeSize = OptSize != 0;
1336
1337  // This is the __NO_INLINE__ define, which just depends on things like the
1338  // optimization level and -fno-inline, not actually whether the backend has
1339  // inlining enabled.
1340  Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline);
1341
1342  Opts.FastMath = Args.hasArg(OPT_ffast_math);
1343  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only);
1344
1345  Opts.RetainCommentsFromSystemHeaders =
1346      Args.hasArg(OPT_fretain_comments_from_system_headers);
1347
1348  unsigned SSP = getLastArgIntValue(Args, OPT_stack_protector, 0, Diags);
1349  switch (SSP) {
1350  default:
1351    Diags.Report(diag::err_drv_invalid_value)
1352      << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
1353    break;
1354  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
1355  case 1: Opts.setStackProtector(LangOptions::SSPOn);  break;
1356  case 2: Opts.setStackProtector(LangOptions::SSPReq); break;
1357  }
1358
1359  // Parse -fsanitize= arguments.
1360  std::vector<std::string> Sanitizers = Args.getAllArgValues(OPT_fsanitize_EQ);
1361  for (unsigned I = 0, N = Sanitizers.size(); I != N; ++I) {
1362    // Since the Opts.Sanitize* values are bitfields, it's a little tricky to
1363    // efficiently map string values to them. Perform the mapping indirectly:
1364    // convert strings to enumerated values, then switch over the enum to set
1365    // the right bitfield value.
1366    enum Sanitizer {
1367#define SANITIZER(NAME, ID) \
1368      ID,
1369#include "clang/Basic/Sanitizers.def"
1370      Unknown
1371    };
1372    switch (llvm::StringSwitch<unsigned>(Sanitizers[I])
1373#define SANITIZER(NAME, ID) \
1374              .Case(NAME, ID)
1375#include "clang/Basic/Sanitizers.def"
1376              .Default(Unknown)) {
1377#define SANITIZER(NAME, ID) \
1378    case ID: \
1379      Opts.Sanitize.ID = true; \
1380      break;
1381#include "clang/Basic/Sanitizers.def"
1382
1383    case Unknown:
1384      Diags.Report(diag::err_drv_invalid_value)
1385        << "-fsanitize=" << Sanitizers[I];
1386      break;
1387    }
1388  }
1389}
1390
1391static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
1392                                  FileManager &FileMgr,
1393                                  DiagnosticsEngine &Diags) {
1394  using namespace options;
1395  Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
1396  Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
1397  if (const Arg *A = Args.getLastArg(OPT_token_cache))
1398      Opts.TokenCache = A->getValue();
1399  else
1400    Opts.TokenCache = Opts.ImplicitPTHInclude;
1401  Opts.UsePredefines = !Args.hasArg(OPT_undef);
1402  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
1403  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
1404
1405  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
1406  for (arg_iterator it = Args.filtered_begin(OPT_error_on_deserialized_pch_decl),
1407         ie = Args.filtered_end(); it != ie; ++it) {
1408    const Arg *A = *it;
1409    Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue());
1410  }
1411
1412  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
1413    StringRef Value(A->getValue());
1414    size_t Comma = Value.find(',');
1415    unsigned Bytes = 0;
1416    unsigned EndOfLine = 0;
1417
1418    if (Comma == StringRef::npos ||
1419        Value.substr(0, Comma).getAsInteger(10, Bytes) ||
1420        Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
1421      Diags.Report(diag::err_drv_preamble_format);
1422    else {
1423      Opts.PrecompiledPreambleBytes.first = Bytes;
1424      Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
1425    }
1426  }
1427
1428  // Add macros from the command line.
1429  for (arg_iterator it = Args.filtered_begin(OPT_D, OPT_U),
1430         ie = Args.filtered_end(); it != ie; ++it) {
1431    if ((*it)->getOption().matches(OPT_D))
1432      Opts.addMacroDef((*it)->getValue());
1433    else
1434      Opts.addMacroUndef((*it)->getValue());
1435  }
1436
1437  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
1438
1439  // Add the ordered list of -includes.
1440  for (arg_iterator it = Args.filtered_begin(OPT_include),
1441         ie = Args.filtered_end(); it != ie; ++it) {
1442    const Arg *A = *it;
1443    Opts.Includes.push_back(A->getValue());
1444  }
1445
1446  for (arg_iterator it = Args.filtered_begin(OPT_chain_include),
1447         ie = Args.filtered_end(); it != ie; ++it) {
1448    const Arg *A = *it;
1449    Opts.ChainedIncludes.push_back(A->getValue());
1450  }
1451
1452  // Include 'altivec.h' if -faltivec option present
1453  if (Args.hasArg(OPT_faltivec))
1454    Opts.Includes.push_back("altivec.h");
1455
1456  for (arg_iterator it = Args.filtered_begin(OPT_remap_file),
1457         ie = Args.filtered_end(); it != ie; ++it) {
1458    const Arg *A = *it;
1459    std::pair<StringRef,StringRef> Split =
1460      StringRef(A->getValue()).split(';');
1461
1462    if (Split.second.empty()) {
1463      Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
1464      continue;
1465    }
1466
1467    Opts.addRemappedFile(Split.first, Split.second);
1468  }
1469
1470  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
1471    StringRef Name = A->getValue();
1472    unsigned Library = llvm::StringSwitch<unsigned>(Name)
1473      .Case("libc++", ARCXX_libcxx)
1474      .Case("libstdc++", ARCXX_libstdcxx)
1475      .Case("none", ARCXX_nolib)
1476      .Default(~0U);
1477    if (Library == ~0U)
1478      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1479    else
1480      Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
1481  }
1482}
1483
1484static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
1485                                        ArgList &Args,
1486                                        frontend::ActionKind Action) {
1487  using namespace options;
1488
1489  switch (Action) {
1490  case frontend::ASTDeclList:
1491  case frontend::ASTDump:
1492  case frontend::ASTDumpXML:
1493  case frontend::ASTPrint:
1494  case frontend::ASTView:
1495  case frontend::EmitAssembly:
1496  case frontend::EmitBC:
1497  case frontend::EmitHTML:
1498  case frontend::EmitLLVM:
1499  case frontend::EmitLLVMOnly:
1500  case frontend::EmitCodeGenOnly:
1501  case frontend::EmitObj:
1502  case frontend::FixIt:
1503  case frontend::GenerateModule:
1504  case frontend::GeneratePCH:
1505  case frontend::GeneratePTH:
1506  case frontend::ParseSyntaxOnly:
1507  case frontend::ModuleFileInfo:
1508  case frontend::PluginAction:
1509  case frontend::PrintDeclContext:
1510  case frontend::RewriteObjC:
1511  case frontend::RewriteTest:
1512  case frontend::RunAnalysis:
1513  case frontend::MigrateSource:
1514    Opts.ShowCPP = 0;
1515    break;
1516
1517  case frontend::DumpRawTokens:
1518  case frontend::DumpTokens:
1519  case frontend::InitOnly:
1520  case frontend::PrintPreamble:
1521  case frontend::PrintPreprocessedInput:
1522  case frontend::RewriteMacros:
1523  case frontend::RunPreprocessorOnly:
1524    Opts.ShowCPP = !Args.hasArg(OPT_dM);
1525    break;
1526  }
1527
1528  Opts.ShowComments = Args.hasArg(OPT_C);
1529  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
1530  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
1531  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
1532  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
1533}
1534
1535static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) {
1536  using namespace options;
1537  Opts.ABI = Args.getLastArgValue(OPT_target_abi);
1538  Opts.CXXABI = Args.getLastArgValue(OPT_cxx_abi);
1539  Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
1540  Opts.FeaturesAsWritten = Args.getAllArgValues(OPT_target_feature);
1541  Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
1542  Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
1543
1544  // Use the default target triple if unspecified.
1545  if (Opts.Triple.empty())
1546    Opts.Triple = llvm::sys::getDefaultTargetTriple();
1547}
1548
1549//
1550
1551bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
1552                                        const char *const *ArgBegin,
1553                                        const char *const *ArgEnd,
1554                                        DiagnosticsEngine &Diags) {
1555  bool Success = true;
1556
1557  // Parse the arguments.
1558  OwningPtr<OptTable> Opts(createDriverOptTable());
1559  const unsigned IncludedFlagsBitmask = options::CC1Option;
1560  unsigned MissingArgIndex, MissingArgCount;
1561  OwningPtr<InputArgList> Args(
1562    Opts->ParseArgs(ArgBegin, ArgEnd, MissingArgIndex, MissingArgCount,
1563                    IncludedFlagsBitmask));
1564
1565  // Check for missing argument error.
1566  if (MissingArgCount) {
1567    Diags.Report(diag::err_drv_missing_argument)
1568      << Args->getArgString(MissingArgIndex) << MissingArgCount;
1569    Success = false;
1570  }
1571
1572  // Issue errors on unknown arguments.
1573  for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
1574         ie = Args->filtered_end(); it != ie; ++it) {
1575    Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Args);
1576    Success = false;
1577  }
1578
1579  Success = ParseAnalyzerArgs(*Res.getAnalyzerOpts(), *Args, Diags) && Success;
1580  Success = ParseMigratorArgs(Res.getMigratorOpts(), *Args) && Success;
1581  ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), *Args);
1582  Success = ParseDiagnosticArgs(Res.getDiagnosticOpts(), *Args, &Diags)
1583            && Success;
1584  ParseCommentArgs(Res.getLangOpts()->CommentOpts, *Args);
1585  ParseFileSystemArgs(Res.getFileSystemOpts(), *Args);
1586  // FIXME: We shouldn't have to pass the DashX option around here
1587  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), *Args, Diags);
1588  Success = ParseCodeGenArgs(Res.getCodeGenOpts(), *Args, DashX, Diags)
1589            && Success;
1590  ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), *Args);
1591  if (DashX != IK_AST && DashX != IK_LLVM_IR) {
1592    ParseLangArgs(*Res.getLangOpts(), *Args, DashX, Diags);
1593    if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
1594      Res.getLangOpts()->ObjCExceptions = 1;
1595  }
1596  // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of
1597  // PCH file and find the original header name. Remove the need to do that in
1598  // ParsePreprocessorArgs and remove the FileManager
1599  // parameters from the function and the "FileManager.h" #include.
1600  FileManager FileMgr(Res.getFileSystemOpts());
1601  ParsePreprocessorArgs(Res.getPreprocessorOpts(), *Args, FileMgr, Diags);
1602  ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), *Args,
1603                              Res.getFrontendOpts().ProgramAction);
1604  ParseTargetArgs(Res.getTargetOpts(), *Args);
1605
1606  return Success;
1607}
1608
1609namespace {
1610
1611  class ModuleSignature {
1612    SmallVector<uint64_t, 16> Data;
1613    unsigned CurBit;
1614    uint64_t CurValue;
1615
1616  public:
1617    ModuleSignature() : CurBit(0), CurValue(0) { }
1618
1619    void add(uint64_t Value, unsigned Bits);
1620    void add(StringRef Value);
1621    void flush();
1622
1623    llvm::APInt getAsInteger() const;
1624  };
1625}
1626
1627void ModuleSignature::add(uint64_t Value, unsigned int NumBits) {
1628  CurValue |= Value << CurBit;
1629  if (CurBit + NumBits < 64) {
1630    CurBit += NumBits;
1631    return;
1632  }
1633
1634  // Add the current word.
1635  Data.push_back(CurValue);
1636
1637  if (CurBit)
1638    CurValue = Value >> (64-CurBit);
1639  else
1640    CurValue = 0;
1641  CurBit = (CurBit+NumBits) & 63;
1642}
1643
1644void ModuleSignature::flush() {
1645  if (CurBit == 0)
1646    return;
1647
1648  Data.push_back(CurValue);
1649  CurBit = 0;
1650  CurValue = 0;
1651}
1652
1653void ModuleSignature::add(StringRef Value) {
1654  for (StringRef::iterator I = Value.begin(), IEnd = Value.end(); I != IEnd;++I)
1655    add(*I, 8);
1656}
1657
1658llvm::APInt ModuleSignature::getAsInteger() const {
1659  return llvm::APInt(Data.size() * 64, Data);
1660}
1661
1662std::string CompilerInvocation::getModuleHash() const {
1663  // Note: For QoI reasons, the things we use as a hash here should all be
1664  // dumped via the -module-info flag.
1665  using llvm::hash_code;
1666  using llvm::hash_value;
1667  using llvm::hash_combine;
1668
1669  // Start the signature with the compiler version.
1670  // FIXME: We'd rather use something more cryptographically sound than
1671  // CityHash, but this will do for now.
1672  hash_code code = hash_value(getClangFullRepositoryVersion());
1673
1674  // Extend the signature with the language options
1675#define LANGOPT(Name, Bits, Default, Description) \
1676   code = hash_combine(code, LangOpts->Name);
1677#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
1678  code = hash_combine(code, static_cast<unsigned>(LangOpts->get##Name()));
1679#define BENIGN_LANGOPT(Name, Bits, Default, Description)
1680#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
1681#include "clang/Basic/LangOptions.def"
1682
1683  // Extend the signature with the target options.
1684  code = hash_combine(code, TargetOpts->Triple, TargetOpts->CPU,
1685                      TargetOpts->ABI, TargetOpts->CXXABI,
1686                      TargetOpts->LinkerVersion);
1687  for (unsigned i = 0, n = TargetOpts->FeaturesAsWritten.size(); i != n; ++i)
1688    code = hash_combine(code, TargetOpts->FeaturesAsWritten[i]);
1689
1690  // Extend the signature with preprocessor options.
1691  const PreprocessorOptions &ppOpts = getPreprocessorOpts();
1692  const HeaderSearchOptions &hsOpts = getHeaderSearchOpts();
1693  code = hash_combine(code, ppOpts.UsePredefines, ppOpts.DetailedRecord);
1694
1695  std::vector<StringRef> MacroDefs;
1696  for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
1697            I = getPreprocessorOpts().Macros.begin(),
1698         IEnd = getPreprocessorOpts().Macros.end();
1699       I != IEnd; ++I) {
1700    // If we're supposed to ignore this macro for the purposes of modules,
1701    // don't put it into the hash.
1702    if (!hsOpts.ModulesIgnoreMacros.empty()) {
1703      // Check whether we're ignoring this macro.
1704      StringRef MacroDef = I->first;
1705      if (hsOpts.ModulesIgnoreMacros.count(MacroDef.split('=').first))
1706        continue;
1707    }
1708
1709    code = hash_combine(code, I->first, I->second);
1710  }
1711
1712  // Extend the signature with the sysroot.
1713  code = hash_combine(code, hsOpts.Sysroot, hsOpts.UseBuiltinIncludes,
1714                      hsOpts.UseStandardSystemIncludes,
1715                      hsOpts.UseStandardCXXIncludes,
1716                      hsOpts.UseLibcxx);
1717
1718  // Darwin-specific hack: if we have a sysroot, use the contents and
1719  // modification time of
1720  //   $sysroot/System/Library/CoreServices/SystemVersion.plist
1721  // as part of the module hash.
1722  if (!hsOpts.Sysroot.empty()) {
1723    llvm::OwningPtr<llvm::MemoryBuffer> buffer;
1724    SmallString<128> systemVersionFile;
1725    systemVersionFile += hsOpts.Sysroot;
1726    llvm::sys::path::append(systemVersionFile, "System");
1727    llvm::sys::path::append(systemVersionFile, "Library");
1728    llvm::sys::path::append(systemVersionFile, "CoreServices");
1729    llvm::sys::path::append(systemVersionFile, "SystemVersion.plist");
1730    if (!llvm::MemoryBuffer::getFile(systemVersionFile, buffer)) {
1731      code = hash_combine(code, buffer.get()->getBuffer());
1732
1733      struct stat statBuf;
1734      if (stat(systemVersionFile.c_str(), &statBuf) == 0)
1735        code = hash_combine(code, statBuf.st_mtime);
1736    }
1737  }
1738
1739  return llvm::APInt(64, code).toString(36, /*Signed=*/false);
1740}
1741
1742namespace clang {
1743
1744// Declared in clang/Frontend/Utils.h.
1745int getLastArgIntValue(const ArgList &Args, OptSpecifier Id, int Default,
1746                       DiagnosticsEngine *Diags) {
1747  int Res = Default;
1748  if (Arg *A = Args.getLastArg(Id)) {
1749    if (StringRef(A->getValue()).getAsInteger(10, Res)) {
1750      if (Diags)
1751        Diags->Report(diag::err_drv_invalid_int_value) << A->getAsString(Args)
1752                                                       << A->getValue();
1753    }
1754  }
1755  return Res;
1756}
1757}
1758