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/Version.h"
13#include "clang/Basic/FileManager.h"
14#include "clang/Driver/Arg.h"
15#include "clang/Driver/ArgList.h"
16#include "clang/Driver/Options.h"
17#include "clang/Driver/DriverDiagnostic.h"
18#include "clang/Driver/OptTable.h"
19#include "clang/Driver/Option.h"
20#include "clang/Frontend/CompilerInvocation.h"
21#include "clang/Frontend/LangStandard.h"
22#include "clang/Serialization/ASTReader.h"
23#include "llvm/ADT/OwningPtr.h"
24#include "llvm/ADT/SmallVector.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/StringSwitch.h"
27#include "llvm/ADT/Triple.h"
28#include "llvm/Support/ErrorHandling.h"
29#include "llvm/Support/Host.h"
30#include "llvm/Support/Path.h"
31using namespace clang;
32
33//===----------------------------------------------------------------------===//
34// Initialization.
35//===----------------------------------------------------------------------===//
36
37CompilerInvocationBase::CompilerInvocationBase()
38  : LangOpts(new LangOptions()) {}
39
40CompilerInvocationBase::CompilerInvocationBase(const CompilerInvocationBase &X)
41  : RefCountedBase<CompilerInvocation>(),
42    LangOpts(new LangOptions(*X.getLangOpts())) {}
43
44//===----------------------------------------------------------------------===//
45// Utility functions.
46//===----------------------------------------------------------------------===//
47
48static const char *getAnalysisStoreName(AnalysisStores Kind) {
49  switch (Kind) {
50  default:
51    llvm_unreachable("Unknown analysis store!");
52#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
53  case NAME##Model: return CMDFLAG;
54#include "clang/StaticAnalyzer/Core/Analyses.def"
55  }
56}
57
58static const char *getAnalysisConstraintName(AnalysisConstraints Kind) {
59  switch (Kind) {
60  default:
61    llvm_unreachable("Unknown analysis constraints!");
62#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
63  case NAME##Model: return CMDFLAG;
64#include "clang/StaticAnalyzer/Core/Analyses.def"
65  }
66}
67
68static const char *getAnalysisDiagClientName(AnalysisDiagClients Kind) {
69  switch (Kind) {
70  default:
71    llvm_unreachable("Unknown analysis client!");
72#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREATE) \
73  case PD_##NAME: return CMDFLAG;
74#include "clang/StaticAnalyzer/Core/Analyses.def"
75  }
76}
77
78static const char *getAnalysisPurgeModeName(AnalysisPurgeMode Kind) {
79  switch (Kind) {
80  default:
81    llvm_unreachable("Unknown analysis purge mode!");
82#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
83  case NAME: return CMDFLAG;
84#include "clang/StaticAnalyzer/Core/Analyses.def"
85  }
86}
87
88static const char *getAnalysisIPAModeName(AnalysisIPAMode Kind) {
89  switch (Kind) {
90  default:
91    llvm_unreachable("Unknown analysis ipa mode!");
92#define ANALYSIS_IPA(NAME, CMDFLAG, DESC) \
93  case NAME: return CMDFLAG;
94#include "clang/StaticAnalyzer/Core/Analyses.def"
95  }
96}
97
98static const char *
99  getAnalysisInliningModeName(AnalysisInliningMode Kind) {
100  switch (Kind) {
101  default:
102    llvm_unreachable("Unknown analysis inlining mode!");
103#define ANALYSIS_INLINE_SELECTION(NAME, CMDFLAG, DESC) \
104  case NAME: return CMDFLAG;
105#include "clang/StaticAnalyzer/Core/Analyses.def"
106  }
107}
108
109//===----------------------------------------------------------------------===//
110// Serialization (to args)
111//===----------------------------------------------------------------------===//
112
113namespace {
114  /// ToArgsList - Helper class to create a list of std::strings.
115  class ToArgsList {
116    std::vector<std::string> &Res;
117  public:
118    explicit ToArgsList(std::vector<std::string> &Res) : Res(Res) {}
119
120    void push_back(StringRef Str) {
121      // Avoid creating a temporary string.
122      Res.push_back(std::string());
123      Res.back().assign(Str.data(), Str.size());
124    }
125
126    void push_back(StringRef Str1, StringRef Str2) {
127      push_back(Str1);
128      push_back(Str2);
129    }
130  };
131}
132
133static void AnalyzerOptsToArgs(const AnalyzerOptions &Opts, ToArgsList &Res) {
134  if (Opts.ShowCheckerHelp)
135    Res.push_back("-analyzer-checker-help");
136  if (Opts.AnalysisStoreOpt != RegionStoreModel)
137    Res.push_back("-analyzer-store",
138                  getAnalysisStoreName(Opts.AnalysisStoreOpt));
139  if (Opts.AnalysisConstraintsOpt != RangeConstraintsModel)
140    Res.push_back("-analyzer-constraints",
141                  getAnalysisConstraintName(Opts.AnalysisConstraintsOpt));
142  if (Opts.AnalysisDiagOpt != PD_HTML)
143    Res.push_back("-analyzer-output",
144                  getAnalysisDiagClientName(Opts.AnalysisDiagOpt));
145  if (Opts.AnalysisPurgeOpt != PurgeStmt)
146    Res.push_back("-analyzer-purge",
147                  getAnalysisPurgeModeName(Opts.AnalysisPurgeOpt));
148  if (!Opts.AnalyzeSpecificFunction.empty())
149    Res.push_back("-analyze-function", Opts.AnalyzeSpecificFunction);
150  if (Opts.IPAMode != DynamicDispatchBifurcate)
151    Res.push_back("-analyzer-ipa", getAnalysisIPAModeName(Opts.IPAMode));
152  if (Opts.InliningMode != NoRedundancy)
153    Res.push_back("-analyzer-inlining-mode",
154                  getAnalysisInliningModeName(Opts.InliningMode));
155
156  if (Opts.AnalyzeAll)
157    Res.push_back("-analyzer-opt-analyze-headers");
158  if (Opts.AnalyzerDisplayProgress)
159    Res.push_back("-analyzer-display-progress");
160  if (Opts.AnalyzeNestedBlocks)
161    Res.push_back("-analyzer-opt-analyze-nested-blocks");
162  if (Opts.eagerlyAssumeBinOpBifurcation)
163    Res.push_back("-analyzer-eagerly-assume");
164  if (Opts.TrimGraph)
165    Res.push_back("-trim-egraph");
166  if (Opts.visualizeExplodedGraphWithGraphViz)
167    Res.push_back("-analyzer-viz-egraph-graphviz");
168  if (Opts.visualizeExplodedGraphWithUbiGraph)
169    Res.push_back("-analyzer-viz-egraph-ubigraph");
170  if (Opts.NoRetryExhausted)
171    Res.push_back("-analyzer-disable-retry-exhausted");
172
173  for (unsigned i = 0, e = Opts.CheckersControlList.size(); i != e; ++i) {
174    const std::pair<std::string, bool> &opt = Opts.CheckersControlList[i];
175    if (opt.second)
176      Res.push_back("-analyzer-disable-checker");
177    else
178      Res.push_back("-analyzer-checker");
179    Res.push_back(opt.first);
180  }
181}
182
183static void CodeGenOptsToArgs(const CodeGenOptions &Opts, ToArgsList &Res) {
184  switch (Opts.DebugInfo) {
185    case CodeGenOptions::NoDebugInfo:
186      break;
187    case CodeGenOptions::DebugLineTablesOnly:
188      Res.push_back("-gline-tables-only");
189      break;
190    case CodeGenOptions::LimitedDebugInfo:
191      Res.push_back("-g");
192      Res.push_back("-flimit-debug-info");
193      break;
194    case CodeGenOptions::FullDebugInfo:
195      Res.push_back("-g");
196      Res.push_back("-fno-limit-debug-info");
197      break;
198  }
199  if (Opts.DisableLLVMOpts)
200    Res.push_back("-disable-llvm-optzns");
201  if (Opts.DisableRedZone)
202    Res.push_back("-disable-red-zone");
203  if (Opts.DisableTailCalls)
204    Res.push_back("-mdisable-tail-calls");
205  if (!Opts.DebugCompilationDir.empty())
206    Res.push_back("-fdebug-compilation-dir", Opts.DebugCompilationDir);
207  if (!Opts.DwarfDebugFlags.empty())
208    Res.push_back("-dwarf-debug-flags", Opts.DwarfDebugFlags);
209  if (Opts.EmitGcovArcs)
210    Res.push_back("-femit-coverage-data");
211  if (Opts.EmitGcovNotes)
212    Res.push_back("-femit-coverage-notes");
213  if (Opts.EmitOpenCLArgMetadata)
214    Res.push_back("-cl-kernel-arg-info");
215  if (!Opts.MergeAllConstants)
216    Res.push_back("-fno-merge-all-constants");
217  if (Opts.NoCommon)
218    Res.push_back("-fno-common");
219  if (Opts.ForbidGuardVariables)
220    Res.push_back("-fforbid-guard-variables");
221  if (Opts.UseRegisterSizedBitfieldAccess)
222    Res.push_back("-fuse-register-sized-bitfield-access");
223  if (Opts.NoImplicitFloat)
224    Res.push_back("-no-implicit-float");
225  if (Opts.OmitLeafFramePointer)
226    Res.push_back("-momit-leaf-frame-pointer");
227  if (Opts.OptimizeSize) {
228    assert(Opts.OptimizationLevel == 2 && "Invalid options!");
229    Opts.OptimizeSize == 1 ? Res.push_back("-Os") : Res.push_back("-Oz");
230  } else if (Opts.OptimizationLevel != 0)
231    Res.push_back("-O" + llvm::utostr(Opts.OptimizationLevel));
232  if (!Opts.MainFileName.empty())
233    Res.push_back("-main-file-name", Opts.MainFileName);
234  if (Opts.NoInfsFPMath)
235    Res.push_back("-menable-no-infinities");
236  if (Opts.NoNaNsFPMath)
237    Res.push_back("-menable-no-nans");
238  // SimplifyLibCalls is only derived.
239  // TimePasses is only derived.
240  // UnitAtATime is unused.
241  // Inlining is only derived.
242
243  // UnrollLoops is derived, but also accepts an option, no
244  // harm in pushing it back here.
245  if (Opts.UnrollLoops)
246    Res.push_back("-funroll-loops");
247  if (Opts.DataSections)
248    Res.push_back("-fdata-sections");
249  if (Opts.FunctionSections)
250    Res.push_back("-ffunction-sections");
251  if (Opts.AsmVerbose)
252    Res.push_back("-masm-verbose");
253  if (!Opts.CodeModel.empty())
254    Res.push_back("-mcode-model", Opts.CodeModel);
255  if (Opts.CUDAIsDevice)
256    Res.push_back("-fcuda-is-device");
257  if (!Opts.CXAAtExit)
258    Res.push_back("-fno-use-cxa-atexit");
259  if (Opts.CXXCtorDtorAliases)
260    Res.push_back("-mconstructor-aliases");
261  if (Opts.ObjCAutoRefCountExceptions)
262    Res.push_back("-fobjc-arc-eh");
263  if (!Opts.DebugPass.empty()) {
264    Res.push_back("-mdebug-pass", Opts.DebugPass);
265  }
266  if (Opts.DisableFPElim)
267    Res.push_back("-mdisable-fp-elim");
268  if (!Opts.FloatABI.empty())
269    Res.push_back("-mfloat-abi", Opts.FloatABI);
270  if (!Opts.LimitFloatPrecision.empty())
271    Res.push_back("-mlimit-float-precision", Opts.LimitFloatPrecision);
272  if (Opts.NoZeroInitializedInBSS)
273    Res.push_back("-mno-zero-initialized-bss");
274  switch (Opts.getObjCDispatchMethod()) {
275  case CodeGenOptions::Legacy:
276    break;
277  case CodeGenOptions::Mixed:
278    Res.push_back("-fobjc-dispatch-method=mixed");
279    break;
280  case CodeGenOptions::NonLegacy:
281    Res.push_back("-fobjc-dispatch-method=non-legacy");
282    break;
283  }
284  if (Opts.BoundsChecking > 0)
285    Res.push_back("-fbounds-checking=" + llvm::utostr(Opts.BoundsChecking));
286  if (Opts.NumRegisterParameters)
287    Res.push_back("-mregparm", llvm::utostr(Opts.NumRegisterParameters));
288  if (Opts.NoGlobalMerge)
289    Res.push_back("-mno-global-merge");
290  if (Opts.NoExecStack)
291    Res.push_back("-mnoexecstack");
292  if (Opts.RelaxAll)
293    Res.push_back("-mrelax-all");
294  if (Opts.SaveTempLabels)
295    Res.push_back("-msave-temp-labels");
296  if (Opts.NoDwarf2CFIAsm)
297    Res.push_back("-fno-dwarf2-cfi-asm");
298  if (Opts.NoDwarfDirectoryAsm)
299    Res.push_back("-fno-dwarf-directory-asm");
300  if (Opts.SoftFloat)
301    Res.push_back("-msoft-float");
302  if (Opts.StrictEnums)
303    Res.push_back("-fstrict-enums");
304  if (Opts.UnwindTables)
305    Res.push_back("-munwind-tables");
306  if (Opts.RelocationModel != "pic")
307    Res.push_back("-mrelocation-model", Opts.RelocationModel);
308  if (!Opts.VerifyModule)
309    Res.push_back("-disable-llvm-verifier");
310  for (unsigned i = 0, e = Opts.BackendOptions.size(); i != e; ++i)
311    Res.push_back("-backend-option", Opts.BackendOptions[i]);
312
313  switch (Opts.DefaultTLSModel) {
314  case CodeGenOptions::GeneralDynamicTLSModel:
315    break;
316  case CodeGenOptions::LocalDynamicTLSModel:
317    Res.push_back("-ftls-model=local-dynamic");
318    break;
319  case CodeGenOptions::InitialExecTLSModel:
320    Res.push_back("-ftls-model=initial-exec");
321    break;
322  case CodeGenOptions::LocalExecTLSModel:
323    Res.push_back("-ftls-model=local-exec");
324    break;
325  }
326}
327
328static void DependencyOutputOptsToArgs(const DependencyOutputOptions &Opts,
329                                       ToArgsList &Res) {
330  if (Opts.IncludeSystemHeaders)
331    Res.push_back("-sys-header-deps");
332  if (Opts.ShowHeaderIncludes)
333    Res.push_back("-H");
334  if (!Opts.HeaderIncludeOutputFile.empty())
335    Res.push_back("-header-include-file", Opts.HeaderIncludeOutputFile);
336  if (Opts.UsePhonyTargets)
337    Res.push_back("-MP");
338  if (!Opts.OutputFile.empty())
339    Res.push_back("-dependency-file", Opts.OutputFile);
340  for (unsigned i = 0, e = Opts.Targets.size(); i != e; ++i)
341    Res.push_back("-MT", Opts.Targets[i]);
342}
343
344static void DiagnosticOptsToArgs(const DiagnosticOptions &Opts,
345                                 ToArgsList &Res) {
346  if (Opts.IgnoreWarnings)
347    Res.push_back("-w");
348  if (Opts.NoRewriteMacros)
349    Res.push_back("-Wno-rewrite-macros");
350  if (Opts.Pedantic)
351    Res.push_back("-pedantic");
352  if (Opts.PedanticErrors)
353    Res.push_back("-pedantic-errors");
354  if (!Opts.ShowColumn)
355    Res.push_back("-fno-show-column");
356  if (!Opts.ShowLocation)
357    Res.push_back("-fno-show-source-location");
358  if (!Opts.ShowCarets)
359    Res.push_back("-fno-caret-diagnostics");
360  if (!Opts.ShowFixits)
361    Res.push_back("-fno-diagnostics-fixit-info");
362  if (Opts.ShowSourceRanges)
363    Res.push_back("-fdiagnostics-print-source-range-info");
364  if (Opts.ShowParseableFixits)
365    Res.push_back("-fdiagnostics-parseable-fixits");
366  if (Opts.ShowColors)
367    Res.push_back("-fcolor-diagnostics");
368  if (Opts.VerifyDiagnostics)
369    Res.push_back("-verify");
370  if (Opts.ShowOptionNames)
371    Res.push_back("-fdiagnostics-show-option");
372  if (Opts.ShowCategories == 1)
373    Res.push_back("-fdiagnostics-show-category=id");
374  else if (Opts.ShowCategories == 2)
375    Res.push_back("-fdiagnostics-show-category=name");
376  switch (Opts.Format) {
377  case DiagnosticOptions::Clang:
378    Res.push_back("-fdiagnostics-format=clang"); break;
379  case DiagnosticOptions::Msvc:
380    Res.push_back("-fdiagnostics-format=msvc");  break;
381  case DiagnosticOptions::Vi:
382    Res.push_back("-fdiagnostics-format=vi");    break;
383  }
384  if (Opts.ErrorLimit)
385    Res.push_back("-ferror-limit", llvm::utostr(Opts.ErrorLimit));
386  if (!Opts.DiagnosticLogFile.empty())
387    Res.push_back("-diagnostic-log-file", Opts.DiagnosticLogFile);
388  if (Opts.MacroBacktraceLimit
389                        != DiagnosticOptions::DefaultMacroBacktraceLimit)
390    Res.push_back("-fmacro-backtrace-limit",
391                  llvm::utostr(Opts.MacroBacktraceLimit));
392  if (Opts.TemplateBacktraceLimit
393                        != DiagnosticOptions::DefaultTemplateBacktraceLimit)
394    Res.push_back("-ftemplate-backtrace-limit",
395                  llvm::utostr(Opts.TemplateBacktraceLimit));
396  if (Opts.ConstexprBacktraceLimit
397                        != DiagnosticOptions::DefaultConstexprBacktraceLimit)
398    Res.push_back("-fconstexpr-backtrace-limit",
399                  llvm::utostr(Opts.ConstexprBacktraceLimit));
400
401  if (Opts.TabStop != DiagnosticOptions::DefaultTabStop)
402    Res.push_back("-ftabstop", llvm::utostr(Opts.TabStop));
403  if (Opts.MessageLength)
404    Res.push_back("-fmessage-length", llvm::utostr(Opts.MessageLength));
405  if (!Opts.DumpBuildInformation.empty())
406    Res.push_back("-dump-build-information", Opts.DumpBuildInformation);
407  for (unsigned i = 0, e = Opts.Warnings.size(); i != e; ++i)
408    Res.push_back("-W" + Opts.Warnings[i]);
409}
410
411static const char *getInputKindName(InputKind Kind) {
412  switch (Kind) {
413  case IK_None:              break;
414  case IK_AST:               return "ast";
415  case IK_Asm:               return "assembler-with-cpp";
416  case IK_C:                 return "c";
417  case IK_CXX:               return "c++";
418  case IK_LLVM_IR:           return "ir";
419  case IK_ObjC:              return "objective-c";
420  case IK_ObjCXX:            return "objective-c++";
421  case IK_OpenCL:            return "cl";
422  case IK_CUDA:              return "cuda";
423  case IK_PreprocessedC:     return "cpp-output";
424  case IK_PreprocessedCXX:   return "c++-cpp-output";
425  case IK_PreprocessedObjC:  return "objective-c-cpp-output";
426  case IK_PreprocessedObjCXX:return "objective-c++-cpp-output";
427  }
428
429  llvm_unreachable("Unexpected language kind!");
430}
431
432static const char *getActionName(frontend::ActionKind Kind) {
433  switch (Kind) {
434  case frontend::PluginAction:
435    llvm_unreachable("Invalid kind!");
436
437  case frontend::ASTDeclList:            return "-ast-list";
438  case frontend::ASTDump:                return "-ast-dump";
439  case frontend::ASTDumpXML:             return "-ast-dump-xml";
440  case frontend::ASTPrint:               return "-ast-print";
441  case frontend::ASTView:                return "-ast-view";
442  case frontend::DumpRawTokens:          return "-dump-raw-tokens";
443  case frontend::DumpTokens:             return "-dump-tokens";
444  case frontend::EmitAssembly:           return "-S";
445  case frontend::EmitBC:                 return "-emit-llvm-bc";
446  case frontend::EmitHTML:               return "-emit-html";
447  case frontend::EmitLLVM:               return "-emit-llvm";
448  case frontend::EmitLLVMOnly:           return "-emit-llvm-only";
449  case frontend::EmitCodeGenOnly:        return "-emit-codegen-only";
450  case frontend::EmitObj:                return "-emit-obj";
451  case frontend::FixIt:                  return "-fixit";
452  case frontend::GenerateModule:         return "-emit-module";
453  case frontend::GeneratePCH:            return "-emit-pch";
454  case frontend::GeneratePTH:            return "-emit-pth";
455  case frontend::InitOnly:               return "-init-only";
456  case frontend::ParseSyntaxOnly:        return "-fsyntax-only";
457  case frontend::PrintDeclContext:       return "-print-decl-contexts";
458  case frontend::PrintPreamble:          return "-print-preamble";
459  case frontend::PrintPreprocessedInput: return "-E";
460  case frontend::RewriteMacros:          return "-rewrite-macros";
461  case frontend::RewriteObjC:            return "-rewrite-objc";
462  case frontend::RewriteTest:            return "-rewrite-test";
463  case frontend::RunAnalysis:            return "-analyze";
464  case frontend::MigrateSource:          return "-migrate";
465  case frontend::RunPreprocessorOnly:    return "-Eonly";
466  }
467
468  llvm_unreachable("Unexpected language kind!");
469}
470
471static void FileSystemOptsToArgs(const FileSystemOptions &Opts, ToArgsList &Res){
472  if (!Opts.WorkingDir.empty())
473    Res.push_back("-working-directory", Opts.WorkingDir);
474}
475
476static void CodeCompleteOptionsToArgs(const CodeCompleteOptions &Opts,
477                                      ToArgsList &Res) {
478  if (Opts.IncludeMacros)
479    Res.push_back("-code-completion-macros");
480  if (Opts.IncludeCodePatterns)
481    Res.push_back("-code-completion-patterns");
482  if (!Opts.IncludeGlobals)
483    Res.push_back("-no-code-completion-globals");
484  if (Opts.IncludeBriefComments)
485    Res.push_back("-code-completion-brief-comments");
486}
487
488static void FrontendOptsToArgs(const FrontendOptions &Opts, ToArgsList &Res) {
489  if (Opts.DisableFree)
490    Res.push_back("-disable-free");
491  if (Opts.RelocatablePCH)
492    Res.push_back("-relocatable-pch");
493  if (Opts.ShowHelp)
494    Res.push_back("-help");
495  if (Opts.ShowStats)
496    Res.push_back("-print-stats");
497  if (Opts.ShowTimers)
498    Res.push_back("-ftime-report");
499  if (Opts.ShowVersion)
500    Res.push_back("-version");
501  if (Opts.FixWhatYouCan)
502    Res.push_back("-fix-what-you-can");
503  if (Opts.FixOnlyWarnings)
504    Res.push_back("-fix-only-warnings");
505  if (Opts.FixAndRecompile)
506    Res.push_back("-fixit-recompile");
507  if (Opts.FixToTemporaries)
508    Res.push_back("-fixit-to-temporary");
509  switch (Opts.ARCMTAction) {
510  case FrontendOptions::ARCMT_None:
511    break;
512  case FrontendOptions::ARCMT_Check:
513    Res.push_back("-arcmt-check");
514    break;
515  case FrontendOptions::ARCMT_Modify:
516    Res.push_back("-arcmt-modify");
517    break;
518  case FrontendOptions::ARCMT_Migrate:
519    Res.push_back("-arcmt-migrate");
520    break;
521  }
522  CodeCompleteOptionsToArgs(Opts.CodeCompleteOpts, Res);
523  if (!Opts.MTMigrateDir.empty())
524    Res.push_back("-mt-migrate-directory", Opts.MTMigrateDir);
525  if (!Opts.ARCMTMigrateReportOut.empty())
526    Res.push_back("-arcmt-migrate-report-output", Opts.ARCMTMigrateReportOut);
527  if (Opts.ARCMTMigrateEmitARCErrors)
528    Res.push_back("-arcmt-migrate-emit-errors");
529
530  if (Opts.ObjCMTAction & ~FrontendOptions::ObjCMT_Literals)
531    Res.push_back("-objcmt-migrate-literals");
532  if (Opts.ObjCMTAction & ~FrontendOptions::ObjCMT_Subscripting)
533    Res.push_back("-objcmt-migrate-subscripting");
534
535  bool NeedLang = false;
536  for (unsigned i = 0, e = Opts.Inputs.size(); i != e; ++i)
537    if (FrontendOptions::getInputKindForExtension(Opts.Inputs[i].File) !=
538        Opts.Inputs[i].Kind)
539      NeedLang = true;
540  if (NeedLang)
541    Res.push_back("-x", getInputKindName(Opts.Inputs[0].Kind));
542  for (unsigned i = 0, e = Opts.Inputs.size(); i != e; ++i) {
543    assert((!NeedLang || Opts.Inputs[i].Kind == Opts.Inputs[0].Kind) &&
544           "Unable to represent this input vector!");
545    Res.push_back(Opts.Inputs[i].File);
546  }
547
548  if (!Opts.OutputFile.empty())
549    Res.push_back("-o", Opts.OutputFile);
550  if (!Opts.CodeCompletionAt.FileName.empty())
551    Res.push_back("-code-completion-at",
552                  Opts.CodeCompletionAt.FileName + ":" +
553                  llvm::utostr(Opts.CodeCompletionAt.Line) + ":" +
554                  llvm::utostr(Opts.CodeCompletionAt.Column));
555  if (Opts.ProgramAction != frontend::PluginAction)
556    Res.push_back(getActionName(Opts.ProgramAction));
557  if (!Opts.ActionName.empty()) {
558    Res.push_back("-plugin", Opts.ActionName);
559    for(unsigned i = 0, e = Opts.PluginArgs.size(); i != e; ++i)
560      Res.push_back("-plugin-arg-" + Opts.ActionName, Opts.PluginArgs[i]);
561  }
562  if (!Opts.ASTDumpFilter.empty())
563    Res.push_back("-ast-dump-filter", Opts.ASTDumpFilter);
564  for (unsigned i = 0, e = Opts.Plugins.size(); i != e; ++i)
565    Res.push_back("-load", Opts.Plugins[i]);
566  for (unsigned i = 0, e = Opts.AddPluginActions.size(); i != e; ++i) {
567    Res.push_back("-add-plugin", Opts.AddPluginActions[i]);
568    for(unsigned ai = 0, ae = Opts.AddPluginArgs.size(); ai != ae; ++ai)
569      Res.push_back("-plugin-arg-" + Opts.AddPluginActions[i],
570                    Opts.AddPluginArgs[i][ai]);
571  }
572  for (unsigned i = 0, e = Opts.ASTMergeFiles.size(); i != e; ++i)
573    Res.push_back("-ast-merge", Opts.ASTMergeFiles[i]);
574  for (unsigned i = 0, e = Opts.LLVMArgs.size(); i != e; ++i)
575    Res.push_back("-mllvm", Opts.LLVMArgs[i]);
576  if (!Opts.OverrideRecordLayoutsFile.empty())
577    Res.push_back("-foverride-record-layout=" + Opts.OverrideRecordLayoutsFile);
578}
579
580static void HeaderSearchOptsToArgs(const HeaderSearchOptions &Opts,
581                                   ToArgsList &Res) {
582  if (Opts.Sysroot != "/") {
583    Res.push_back("-isysroot");
584    Res.push_back(Opts.Sysroot);
585  }
586
587  /// User specified include entries.
588  for (unsigned i = 0, e = Opts.UserEntries.size(); i != e; ++i) {
589    const HeaderSearchOptions::Entry &E = Opts.UserEntries[i];
590    if (E.IsFramework && (E.Group != frontend::Angled || !E.IsUserSupplied))
591      llvm::report_fatal_error("Invalid option set!");
592    if (E.IsUserSupplied) {
593      switch (E.Group) {
594      case frontend::After:
595        Res.push_back("-idirafter");
596        break;
597
598      case frontend::Quoted:
599        Res.push_back("-iquote");
600        break;
601
602      case frontend::System:
603        Res.push_back("-isystem");
604        break;
605
606      case frontend::IndexHeaderMap:
607        Res.push_back("-index-header-map");
608        Res.push_back(E.IsFramework? "-F" : "-I");
609        break;
610
611      case frontend::CSystem:
612        Res.push_back("-c-isystem");
613        break;
614
615      case frontend::CXXSystem:
616        Res.push_back("-cxx-isystem");
617        break;
618
619      case frontend::ObjCSystem:
620        Res.push_back("-objc-isystem");
621        break;
622
623      case frontend::ObjCXXSystem:
624        Res.push_back("-objcxx-isystem");
625        break;
626
627      case frontend::Angled:
628        Res.push_back(E.IsFramework ? "-F" : "-I");
629        break;
630      }
631    } else {
632      if (E.IsInternal) {
633        assert(E.Group == frontend::System && "Unexpected header search group");
634        if (E.ImplicitExternC)
635          Res.push_back("-internal-externc-isystem");
636        else
637          Res.push_back("-internal-isystem");
638      } else {
639        if (E.Group != frontend::Angled && E.Group != frontend::System)
640          llvm::report_fatal_error("Invalid option set!");
641        Res.push_back(E.Group == frontend::Angled ? "-iwithprefixbefore" :
642                      "-iwithprefix");
643      }
644    }
645    Res.push_back(E.Path);
646  }
647
648  /// User-specified system header prefixes.
649  for (unsigned i = 0, e = Opts.SystemHeaderPrefixes.size(); i != e; ++i) {
650    if (Opts.SystemHeaderPrefixes[i].IsSystemHeader)
651      Res.push_back("-isystem-prefix");
652    else
653      Res.push_back("-ino-system-prefix");
654
655    Res.push_back(Opts.SystemHeaderPrefixes[i].Prefix);
656  }
657
658  if (!Opts.ResourceDir.empty())
659    Res.push_back("-resource-dir", Opts.ResourceDir);
660  if (!Opts.ModuleCachePath.empty())
661    Res.push_back("-fmodule-cache-path", Opts.ModuleCachePath);
662  if (!Opts.UseStandardSystemIncludes)
663    Res.push_back("-nostdsysteminc");
664  if (!Opts.UseStandardCXXIncludes)
665    Res.push_back("-nostdinc++");
666  if (Opts.UseLibcxx)
667    Res.push_back("-stdlib=libc++");
668  if (Opts.Verbose)
669    Res.push_back("-v");
670}
671
672static void LangOptsToArgs(const LangOptions &Opts, ToArgsList &Res) {
673  LangOptions DefaultLangOpts;
674
675  // FIXME: Need to set -std to get all the implicit options.
676
677  // FIXME: We want to only pass options relative to the defaults, which
678  // requires constructing a target. :(
679  //
680  // It would be better to push the all target specific choices into the driver,
681  // so that everything below that was more uniform.
682
683  if (Opts.Trigraphs)
684    Res.push_back("-trigraphs");
685  // Implicit based on the input kind:
686  //   AsmPreprocessor, CPlusPlus, ObjC1, ObjC2, OpenCL
687  // Implicit based on the input language standard:
688  //   BCPLComment, C99, CPlusPlus0x, Digraphs, GNUInline, ImplicitInt, GNUMode
689  if (Opts.DollarIdents)
690    Res.push_back("-fdollars-in-identifiers");
691  if (Opts.GNUMode && !Opts.GNUKeywords)
692    Res.push_back("-fno-gnu-keywords");
693  if (!Opts.GNUMode && Opts.GNUKeywords)
694    Res.push_back("-fgnu-keywords");
695  if (Opts.MicrosoftExt)
696    Res.push_back("-fms-extensions");
697  if (Opts.MicrosoftMode)
698    Res.push_back("-fms-compatibility");
699  if (Opts.MSCVersion != 0)
700    Res.push_back("-fmsc-version=" + llvm::utostr(Opts.MSCVersion));
701  if (Opts.Borland)
702    Res.push_back("-fborland-extensions");
703  if (Opts.ObjCDefaultSynthProperties)
704    Res.push_back("-fobjc-default-synthesize-properties");
705  // NoInline is implicit.
706  if (!Opts.CXXOperatorNames)
707    Res.push_back("-fno-operator-names");
708  if (Opts.PascalStrings)
709    Res.push_back("-fpascal-strings");
710  if (Opts.CatchUndefined)
711    Res.push_back("-fcatch-undefined-behavior");
712  if (Opts.AddressSanitizer)
713    Res.push_back("-faddress-sanitizer");
714  if (Opts.ThreadSanitizer)
715    Res.push_back("-fthread-sanitizer");
716  if (Opts.WritableStrings)
717    Res.push_back("-fwritable-strings");
718  if (Opts.ConstStrings)
719    Res.push_back("-fconst-strings");
720  if (!Opts.LaxVectorConversions)
721    Res.push_back("-fno-lax-vector-conversions");
722  if (Opts.AltiVec)
723    Res.push_back("-faltivec");
724  if (Opts.Exceptions)
725    Res.push_back("-fexceptions");
726  if (Opts.ObjCExceptions)
727    Res.push_back("-fobjc-exceptions");
728  if (Opts.CXXExceptions)
729    Res.push_back("-fcxx-exceptions");
730  if (Opts.SjLjExceptions)
731    Res.push_back("-fsjlj-exceptions");
732  if (Opts.TraditionalCPP)
733    Res.push_back("-traditional-cpp");
734  if (!Opts.RTTI)
735    Res.push_back("-fno-rtti");
736  if (Opts.MSBitfields)
737    Res.push_back("-mms-bitfields");
738  if (Opts.Freestanding)
739    Res.push_back("-ffreestanding");
740  if (Opts.NoBuiltin)
741    Res.push_back("-fno-builtin");
742  if (!Opts.AssumeSaneOperatorNew)
743    Res.push_back("-fno-assume-sane-operator-new");
744  if (!Opts.ThreadsafeStatics)
745    Res.push_back("-fno-threadsafe-statics");
746  if (Opts.POSIXThreads)
747    Res.push_back("-pthread");
748  if (Opts.Blocks)
749    Res.push_back("-fblocks");
750  if (Opts.BlocksRuntimeOptional)
751    Res.push_back("-fblocks-runtime-optional");
752  if (Opts.Modules)
753    Res.push_back("-fmodules");
754  if (Opts.EmitAllDecls)
755    Res.push_back("-femit-all-decls");
756  if (Opts.MathErrno)
757    Res.push_back("-fmath-errno");
758  switch (Opts.getSignedOverflowBehavior()) {
759  case LangOptions::SOB_Undefined: break;
760  case LangOptions::SOB_Defined:   Res.push_back("-fwrapv"); break;
761  case LangOptions::SOB_Trapping:
762    Res.push_back("-ftrapv");
763    if (!Opts.OverflowHandler.empty())
764      Res.push_back("-ftrapv-handler", Opts.OverflowHandler);
765    break;
766  }
767  switch (Opts.getFPContractMode()) {
768  case LangOptions::FPC_Off:  Res.push_back("-ffp-contract=off"); break;
769  case LangOptions::FPC_On:   Res.push_back("-ffp-contract=on"); break;
770  case LangOptions::FPC_Fast: Res.push_back("-ffp-contract=fast"); break;
771  }
772  if (Opts.HeinousExtensions)
773    Res.push_back("-fheinous-gnu-extensions");
774  // Optimize is implicit.
775  // OptimizeSize is implicit.
776  if (Opts.FastMath)
777    Res.push_back("-ffast-math");
778  if (Opts.Static)
779    Res.push_back("-static-define");
780  if (Opts.DumpRecordLayoutsSimple)
781    Res.push_back("-fdump-record-layouts-simple");
782  else if (Opts.DumpRecordLayouts)
783    Res.push_back("-fdump-record-layouts");
784  if (Opts.DumpVTableLayouts)
785    Res.push_back("-fdump-vtable-layouts");
786  if (Opts.NoBitFieldTypeAlign)
787    Res.push_back("-fno-bitfield-type-alignment");
788  if (Opts.PICLevel)
789    Res.push_back("-pic-level", llvm::utostr(Opts.PICLevel));
790  if (Opts.PIELevel)
791    Res.push_back("-pie-level", llvm::utostr(Opts.PIELevel));
792  if (Opts.ObjCGCBitmapPrint)
793    Res.push_back("-print-ivar-layout");
794  if (Opts.NoConstantCFStrings)
795    Res.push_back("-fno-constant-cfstrings");
796  if (!Opts.AccessControl)
797    Res.push_back("-fno-access-control");
798  if (!Opts.CharIsSigned)
799    Res.push_back("-fno-signed-char");
800  if (Opts.CPlusPlus && !Opts.WChar)
801    Res.push_back("-fno-wchar");
802  if (Opts.ShortWChar)
803    Res.push_back("-fshort-wchar");
804  if (!Opts.ElideConstructors)
805    Res.push_back("-fno-elide-constructors");
806  if (Opts.getGC() != LangOptions::NonGC) {
807    if (Opts.getGC() == LangOptions::HybridGC) {
808      Res.push_back("-fobjc-gc");
809    } else {
810      assert(Opts.getGC() == LangOptions::GCOnly && "Invalid GC mode!");
811      Res.push_back("-fobjc-gc-only");
812    }
813  }
814  Res.push_back("-fobjc-runtime=" + Opts.ObjCRuntime.getAsString());
815  if (Opts.ObjCAutoRefCount)
816    Res.push_back("-fobjc-arc");
817  if (Opts.ObjCARCWeak)
818    Res.push_back("-fobjc-runtime-has-weak");
819  if (!Opts.ObjCInferRelatedResultType)
820    Res.push_back("-fno-objc-infer-related-result-type");
821
822  if (Opts.AppleKext)
823    Res.push_back("-fapple-kext");
824
825  if (Opts.getVisibilityMode() != DefaultVisibility) {
826    Res.push_back("-fvisibility");
827    if (Opts.getVisibilityMode() == HiddenVisibility) {
828      Res.push_back("hidden");
829    } else {
830      assert(Opts.getVisibilityMode() == ProtectedVisibility &&
831             "Invalid visibility!");
832      Res.push_back("protected");
833    }
834  }
835  if (Opts.InlineVisibilityHidden)
836    Res.push_back("-fvisibility-inlines-hidden");
837
838  if (Opts.getStackProtector() != 0)
839    Res.push_back("-stack-protector", llvm::utostr(Opts.getStackProtector()));
840  if (Opts.InstantiationDepth != DefaultLangOpts.InstantiationDepth)
841    Res.push_back("-ftemplate-depth", llvm::utostr(Opts.InstantiationDepth));
842  if (Opts.ConstexprCallDepth != DefaultLangOpts.ConstexprCallDepth)
843    Res.push_back("-fconstexpr-depth", llvm::utostr(Opts.ConstexprCallDepth));
844  if (!Opts.ObjCConstantStringClass.empty())
845    Res.push_back("-fconstant-string-class", Opts.ObjCConstantStringClass);
846  if (Opts.FakeAddressSpaceMap)
847    Res.push_back("-ffake-address-space-map");
848  if (Opts.ParseUnknownAnytype)
849    Res.push_back("-funknown-anytype");
850  if (Opts.DebuggerSupport)
851    Res.push_back("-fdebugger-support");
852  if (Opts.DebuggerCastResultToId)
853    Res.push_back("-fdebugger-cast-result-to-id");
854  if (Opts.DebuggerObjCLiteral)
855    Res.push_back("-fdebugger-objc-literal");
856  if (Opts.DelayedTemplateParsing)
857    Res.push_back("-fdelayed-template-parsing");
858  if (Opts.Deprecated)
859    Res.push_back("-fdeprecated-macro");
860  if (Opts.ApplePragmaPack)
861    Res.push_back("-fapple-pragma-pack");
862  if (!Opts.CurrentModule.empty())
863    Res.push_back("-fmodule-name=" + Opts.CurrentModule);
864}
865
866static void PreprocessorOptsToArgs(const PreprocessorOptions &Opts,
867                                   ToArgsList &Res) {
868  for (unsigned i = 0, e = Opts.Macros.size(); i != e; ++i)
869    Res.push_back(std::string(Opts.Macros[i].second ? "-U" : "-D") +
870                  Opts.Macros[i].first);
871  for (unsigned i = 0, e = Opts.Includes.size(); i != e; ++i) {
872    // FIXME: We need to avoid reincluding the implicit PCH and PTH includes.
873    Res.push_back("-include", Opts.Includes[i]);
874  }
875  for (unsigned i = 0, e = Opts.MacroIncludes.size(); i != e; ++i)
876    Res.push_back("-imacros", Opts.MacroIncludes[i]);
877  if (!Opts.UsePredefines)
878    Res.push_back("-undef");
879  if (Opts.DetailedRecord)
880    Res.push_back("-detailed-preprocessing-record");
881  if (!Opts.ImplicitPCHInclude.empty())
882    Res.push_back("-include-pch", Opts.ImplicitPCHInclude);
883  if (!Opts.ImplicitPTHInclude.empty())
884    Res.push_back("-include-pth", Opts.ImplicitPTHInclude);
885  if (!Opts.TokenCache.empty()) {
886    if (Opts.ImplicitPTHInclude.empty())
887      Res.push_back("-token-cache", Opts.TokenCache);
888    else
889      assert(Opts.ImplicitPTHInclude == Opts.TokenCache &&
890             "Unsupported option combination!");
891  }
892  for (unsigned i = 0, e = Opts.ChainedIncludes.size(); i != e; ++i)
893    Res.push_back("-chain-include", Opts.ChainedIncludes[i]);
894  for (unsigned i = 0, e = Opts.RemappedFiles.size(); i != e; ++i) {
895    Res.push_back("-remap-file", Opts.RemappedFiles[i].first + ";" +
896                                 Opts.RemappedFiles[i].second);
897  }
898}
899
900static void PreprocessorOutputOptsToArgs(const PreprocessorOutputOptions &Opts,
901                                         ToArgsList &Res) {
902  if (!Opts.ShowCPP && !Opts.ShowMacros)
903    llvm::report_fatal_error("Invalid option combination!");
904
905  if (Opts.ShowCPP && Opts.ShowMacros)
906    Res.push_back("-dD");
907  else if (!Opts.ShowCPP && Opts.ShowMacros)
908    Res.push_back("-dM");
909
910  if (!Opts.ShowLineMarkers)
911    Res.push_back("-P");
912  if (Opts.ShowComments)
913    Res.push_back("-C");
914  if (Opts.ShowMacroComments)
915    Res.push_back("-CC");
916}
917
918static void TargetOptsToArgs(const TargetOptions &Opts,
919                             ToArgsList &Res) {
920  Res.push_back("-triple");
921  Res.push_back(Opts.Triple);
922  if (!Opts.CPU.empty())
923    Res.push_back("-target-cpu", Opts.CPU);
924  if (!Opts.ABI.empty())
925    Res.push_back("-target-abi", Opts.ABI);
926  if (!Opts.LinkerVersion.empty())
927    Res.push_back("-target-linker-version", Opts.LinkerVersion);
928  if (!Opts.CXXABI.empty())
929    Res.push_back("-cxx-abi", Opts.CXXABI);
930  for (unsigned i = 0, e = Opts.Features.size(); i != e; ++i)
931    Res.push_back("-target-feature", Opts.Features[i]);
932}
933
934void CompilerInvocation::toArgs(std::vector<std::string> &Res) const {
935  ToArgsList List(Res);
936  AnalyzerOptsToArgs(*getAnalyzerOpts(), List);
937  CodeGenOptsToArgs(getCodeGenOpts(), List);
938  DependencyOutputOptsToArgs(getDependencyOutputOpts(), List);
939  DiagnosticOptsToArgs(getDiagnosticOpts(), List);
940  FileSystemOptsToArgs(getFileSystemOpts(), List);
941  FrontendOptsToArgs(getFrontendOpts(), List);
942  HeaderSearchOptsToArgs(getHeaderSearchOpts(), List);
943  LangOptsToArgs(*getLangOpts(), List);
944  PreprocessorOptsToArgs(getPreprocessorOpts(), List);
945  PreprocessorOutputOptsToArgs(getPreprocessorOutputOpts(), List);
946  TargetOptsToArgs(getTargetOpts(), List);
947}
948
949//===----------------------------------------------------------------------===//
950// Deserialization (to args)
951//===----------------------------------------------------------------------===//
952
953using namespace clang::driver;
954using namespace clang::driver::options;
955
956//
957
958static unsigned getOptimizationLevel(ArgList &Args, InputKind IK,
959                                     DiagnosticsEngine &Diags) {
960  unsigned DefaultOpt = 0;
961  if (IK == IK_OpenCL && !Args.hasArg(OPT_cl_opt_disable))
962    DefaultOpt = 2;
963
964  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
965    if (A->getOption().matches(options::OPT_O0))
966      return 0;
967
968    assert (A->getOption().matches(options::OPT_O));
969
970    llvm::StringRef S(A->getValue(Args));
971    if (S == "s" || S == "z" || S.empty())
972      return 2;
973
974    return Args.getLastArgIntValue(OPT_O, DefaultOpt, Diags);
975  }
976
977  return DefaultOpt;
978}
979
980static unsigned getOptimizationLevelSize(ArgList &Args, InputKind IK,
981                                         DiagnosticsEngine &Diags) {
982  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
983    if (A->getOption().matches(options::OPT_O)) {
984      switch (A->getValue(Args)[0]) {
985      default:
986        return 0;
987      case 's':
988        return 1;
989      case 'z':
990        return 2;
991      }
992    }
993  }
994  return 0;
995}
996
997static void addWarningArgs(ArgList &Args, std::vector<std::string> &Warnings) {
998  for (arg_iterator I = Args.filtered_begin(OPT_W_Group),
999         E = Args.filtered_end(); I != E; ++I) {
1000    Arg *A = *I;
1001    // If the argument is a pure flag, add its name (minus the "-W" at the beginning)
1002    // to the warning list. Else, add its value (for the OPT_W case).
1003    if (A->getOption().getKind() == Option::FlagClass) {
1004      Warnings.push_back(A->getOption().getName().substr(2));
1005    } else {
1006      for (unsigned Idx = 0, End = A->getNumValues();
1007           Idx < End; ++Idx) {
1008        StringRef V = A->getValue(Args, Idx);
1009        // "-Wl," and such are not warning options.
1010        // FIXME: Should be handled by putting these in separate flags.
1011        if (V.startswith("l,") || V.startswith("a,") || V.startswith("p,"))
1012          continue;
1013
1014        Warnings.push_back(V);
1015      }
1016    }
1017  }
1018}
1019
1020static bool ParseAnalyzerArgs(AnalyzerOptions &Opts, ArgList &Args,
1021                              DiagnosticsEngine &Diags) {
1022  using namespace options;
1023  bool Success = true;
1024  if (Arg *A = Args.getLastArg(OPT_analyzer_store)) {
1025    StringRef Name = A->getValue(Args);
1026    AnalysisStores Value = llvm::StringSwitch<AnalysisStores>(Name)
1027#define ANALYSIS_STORE(NAME, CMDFLAG, DESC, CREATFN) \
1028      .Case(CMDFLAG, NAME##Model)
1029#include "clang/StaticAnalyzer/Core/Analyses.def"
1030      .Default(NumStores);
1031    if (Value == NumStores) {
1032      Diags.Report(diag::err_drv_invalid_value)
1033        << A->getAsString(Args) << Name;
1034      Success = false;
1035    } else {
1036      Opts.AnalysisStoreOpt = Value;
1037    }
1038  }
1039
1040  if (Arg *A = Args.getLastArg(OPT_analyzer_constraints)) {
1041    StringRef Name = A->getValue(Args);
1042    AnalysisConstraints Value = llvm::StringSwitch<AnalysisConstraints>(Name)
1043#define ANALYSIS_CONSTRAINTS(NAME, CMDFLAG, DESC, CREATFN) \
1044      .Case(CMDFLAG, NAME##Model)
1045#include "clang/StaticAnalyzer/Core/Analyses.def"
1046      .Default(NumConstraints);
1047    if (Value == NumConstraints) {
1048      Diags.Report(diag::err_drv_invalid_value)
1049        << A->getAsString(Args) << Name;
1050      Success = false;
1051    } else {
1052      Opts.AnalysisConstraintsOpt = Value;
1053    }
1054  }
1055
1056  if (Arg *A = Args.getLastArg(OPT_analyzer_output)) {
1057    StringRef Name = A->getValue(Args);
1058    AnalysisDiagClients Value = llvm::StringSwitch<AnalysisDiagClients>(Name)
1059#define ANALYSIS_DIAGNOSTICS(NAME, CMDFLAG, DESC, CREATFN, AUTOCREAT) \
1060      .Case(CMDFLAG, PD_##NAME)
1061#include "clang/StaticAnalyzer/Core/Analyses.def"
1062      .Default(NUM_ANALYSIS_DIAG_CLIENTS);
1063    if (Value == NUM_ANALYSIS_DIAG_CLIENTS) {
1064      Diags.Report(diag::err_drv_invalid_value)
1065        << A->getAsString(Args) << Name;
1066      Success = false;
1067    } else {
1068      Opts.AnalysisDiagOpt = Value;
1069    }
1070  }
1071
1072  if (Arg *A = Args.getLastArg(OPT_analyzer_purge)) {
1073    StringRef Name = A->getValue(Args);
1074    AnalysisPurgeMode Value = llvm::StringSwitch<AnalysisPurgeMode>(Name)
1075#define ANALYSIS_PURGE(NAME, CMDFLAG, DESC) \
1076      .Case(CMDFLAG, NAME)
1077#include "clang/StaticAnalyzer/Core/Analyses.def"
1078      .Default(NumPurgeModes);
1079    if (Value == NumPurgeModes) {
1080      Diags.Report(diag::err_drv_invalid_value)
1081        << A->getAsString(Args) << Name;
1082      Success = false;
1083    } else {
1084      Opts.AnalysisPurgeOpt = Value;
1085    }
1086  }
1087
1088  if (Arg *A = Args.getLastArg(OPT_analyzer_ipa)) {
1089    StringRef Name = A->getValue(Args);
1090    AnalysisIPAMode Value = llvm::StringSwitch<AnalysisIPAMode>(Name)
1091#define ANALYSIS_IPA(NAME, CMDFLAG, DESC) \
1092      .Case(CMDFLAG, NAME)
1093#include "clang/StaticAnalyzer/Core/Analyses.def"
1094      .Default(NumIPAModes);
1095    if (Value == NumIPAModes) {
1096      Diags.Report(diag::err_drv_invalid_value)
1097        << A->getAsString(Args) << Name;
1098      Success = false;
1099    } else {
1100      Opts.IPAMode = Value;
1101    }
1102  }
1103
1104  if (Arg *A = Args.getLastArg(OPT_analyzer_inlining_mode)) {
1105    StringRef Name = A->getValue(Args);
1106    AnalysisInliningMode Value = llvm::StringSwitch<AnalysisInliningMode>(Name)
1107#define ANALYSIS_INLINING_MODE(NAME, CMDFLAG, DESC) \
1108      .Case(CMDFLAG, NAME)
1109#include "clang/StaticAnalyzer/Core/Analyses.def"
1110      .Default(NumInliningModes);
1111    if (Value == NumInliningModes) {
1112      Diags.Report(diag::err_drv_invalid_value)
1113        << A->getAsString(Args) << Name;
1114      Success = false;
1115    } else {
1116      Opts.InliningMode = Value;
1117    }
1118  }
1119
1120  Opts.ShowCheckerHelp = Args.hasArg(OPT_analyzer_checker_help);
1121  Opts.visualizeExplodedGraphWithGraphViz =
1122    Args.hasArg(OPT_analyzer_viz_egraph_graphviz);
1123  Opts.visualizeExplodedGraphWithUbiGraph =
1124    Args.hasArg(OPT_analyzer_viz_egraph_ubigraph);
1125  Opts.NoRetryExhausted = Args.hasArg(OPT_analyzer_disable_retry_exhausted);
1126  Opts.AnalyzeAll = Args.hasArg(OPT_analyzer_opt_analyze_headers);
1127  Opts.AnalyzerDisplayProgress = Args.hasArg(OPT_analyzer_display_progress);
1128  Opts.AnalyzeNestedBlocks =
1129    Args.hasArg(OPT_analyzer_opt_analyze_nested_blocks);
1130  Opts.eagerlyAssumeBinOpBifurcation = Args.hasArg(OPT_analyzer_eagerly_assume);
1131  Opts.AnalyzeSpecificFunction = Args.getLastArgValue(OPT_analyze_function);
1132  Opts.UnoptimizedCFG = Args.hasArg(OPT_analysis_UnoptimizedCFG);
1133  Opts.TrimGraph = Args.hasArg(OPT_trim_egraph);
1134  Opts.MaxNodes = Args.getLastArgIntValue(OPT_analyzer_max_nodes, 150000,Diags);
1135  Opts.maxBlockVisitOnPath = Args.getLastArgIntValue(OPT_analyzer_max_loop, 4, Diags);
1136  Opts.eagerlyTrimExplodedGraph = !Args.hasArg(OPT_analyzer_no_eagerly_trim_egraph);
1137  Opts.PrintStats = Args.hasArg(OPT_analyzer_stats);
1138  Opts.InlineMaxStackDepth =
1139    Args.getLastArgIntValue(OPT_analyzer_inline_max_stack_depth,
1140                            Opts.InlineMaxStackDepth, Diags);
1141  Opts.InlineMaxFunctionSize =
1142    Args.getLastArgIntValue(OPT_analyzer_inline_max_function_size,
1143                            Opts.InlineMaxFunctionSize, Diags);
1144
1145  Opts.CheckersControlList.clear();
1146  for (arg_iterator it = Args.filtered_begin(OPT_analyzer_checker,
1147                                             OPT_analyzer_disable_checker),
1148         ie = Args.filtered_end(); it != ie; ++it) {
1149    const Arg *A = *it;
1150    A->claim();
1151    bool enable = (A->getOption().getID() == OPT_analyzer_checker);
1152    // We can have a list of comma separated checker names, e.g:
1153    // '-analyzer-checker=cocoa,unix'
1154    StringRef checkerList = A->getValue(Args);
1155    SmallVector<StringRef, 4> checkers;
1156    checkerList.split(checkers, ",");
1157    for (unsigned i = 0, e = checkers.size(); i != e; ++i)
1158      Opts.CheckersControlList.push_back(std::make_pair(checkers[i], enable));
1159  }
1160
1161  // Go through the analyzer configuration options.
1162  for (arg_iterator it = Args.filtered_begin(OPT_analyzer_config),
1163       ie = Args.filtered_end(); it != ie; ++it) {
1164    const Arg *A = *it;
1165    A->claim();
1166    // We can have a list of comma separated config names, e.g:
1167    // '-analyzer-config key1=val1,key2=val2'
1168    StringRef configList = A->getValue(Args);
1169    SmallVector<StringRef, 4> configVals;
1170    configList.split(configVals, ",");
1171    for (unsigned i = 0, e = configVals.size(); i != e; ++i) {
1172      StringRef key, val;
1173      llvm::tie(key, val) = configVals[i].split("=");
1174      if (val.empty()) {
1175        Diags.Report(SourceLocation(),
1176                     diag::err_analyzer_config_no_value) << configVals[i];
1177        Success = false;
1178        break;
1179      }
1180      if (val.find('=') != StringRef::npos) {
1181        Diags.Report(SourceLocation(),
1182                     diag::err_analyzer_config_multiple_values)
1183          << configVals[i];
1184        Success = false;
1185        break;
1186      }
1187      Opts.Config[key] = val;
1188    }
1189  }
1190
1191  return Success;
1192}
1193
1194static bool ParseMigratorArgs(MigratorOptions &Opts, ArgList &Args) {
1195  Opts.NoNSAllocReallocError = Args.hasArg(OPT_migrator_no_nsalloc_error);
1196  Opts.NoFinalizeRemoval = Args.hasArg(OPT_migrator_no_finalize_removal);
1197  return true;
1198}
1199
1200static bool ParseCodeGenArgs(CodeGenOptions &Opts, ArgList &Args, InputKind IK,
1201                             DiagnosticsEngine &Diags) {
1202  using namespace options;
1203  bool Success = true;
1204
1205  unsigned OptLevel = getOptimizationLevel(Args, IK, Diags);
1206  if (OptLevel > 3) {
1207    Diags.Report(diag::err_drv_invalid_value)
1208      << Args.getLastArg(OPT_O)->getAsString(Args) << OptLevel;
1209    OptLevel = 3;
1210    Success = false;
1211  }
1212  Opts.OptimizationLevel = OptLevel;
1213
1214  // We must always run at least the always inlining pass.
1215  Opts.Inlining = (Opts.OptimizationLevel > 1) ? CodeGenOptions::NormalInlining
1216    : CodeGenOptions::OnlyAlwaysInlining;
1217  // -fno-inline-functions overrides OptimizationLevel > 1.
1218  Opts.NoInline = Args.hasArg(OPT_fno_inline);
1219  Opts.Inlining = Args.hasArg(OPT_fno_inline_functions) ?
1220    CodeGenOptions::OnlyAlwaysInlining : Opts.Inlining;
1221
1222  if (Args.hasArg(OPT_gline_tables_only)) {
1223    Opts.DebugInfo = CodeGenOptions::DebugLineTablesOnly;
1224  } else if (Args.hasArg(OPT_g_Flag)) {
1225    if (Args.hasFlag(OPT_flimit_debug_info, OPT_fno_limit_debug_info, true))
1226      Opts.DebugInfo = CodeGenOptions::LimitedDebugInfo;
1227    else
1228      Opts.DebugInfo = CodeGenOptions::FullDebugInfo;
1229  }
1230
1231  Opts.DisableLLVMOpts = Args.hasArg(OPT_disable_llvm_optzns);
1232  Opts.DisableRedZone = Args.hasArg(OPT_disable_red_zone);
1233  Opts.ForbidGuardVariables = Args.hasArg(OPT_fforbid_guard_variables);
1234  Opts.UseRegisterSizedBitfieldAccess = Args.hasArg(
1235    OPT_fuse_register_sized_bitfield_access);
1236  Opts.RelaxedAliasing = Args.hasArg(OPT_relaxed_aliasing);
1237  Opts.DwarfDebugFlags = Args.getLastArgValue(OPT_dwarf_debug_flags);
1238  Opts.MergeAllConstants = !Args.hasArg(OPT_fno_merge_all_constants);
1239  Opts.NoCommon = Args.hasArg(OPT_fno_common);
1240  Opts.NoImplicitFloat = Args.hasArg(OPT_no_implicit_float);
1241  Opts.OptimizeSize = getOptimizationLevelSize(Args, IK, Diags);
1242  Opts.SimplifyLibCalls = !(Args.hasArg(OPT_fno_builtin) ||
1243                            Args.hasArg(OPT_ffreestanding));
1244  Opts.UnrollLoops = Args.hasArg(OPT_funroll_loops) ||
1245                     (Opts.OptimizationLevel > 1 && !Opts.OptimizeSize);
1246
1247  Opts.AsmVerbose = Args.hasArg(OPT_masm_verbose);
1248  Opts.ObjCAutoRefCountExceptions = Args.hasArg(OPT_fobjc_arc_exceptions);
1249  Opts.CUDAIsDevice = Args.hasArg(OPT_fcuda_is_device);
1250  Opts.CXAAtExit = !Args.hasArg(OPT_fno_use_cxa_atexit);
1251  Opts.CXXCtorDtorAliases = Args.hasArg(OPT_mconstructor_aliases);
1252  Opts.CodeModel = Args.getLastArgValue(OPT_mcode_model);
1253  Opts.DebugPass = Args.getLastArgValue(OPT_mdebug_pass);
1254  Opts.DisableFPElim = Args.hasArg(OPT_mdisable_fp_elim);
1255  Opts.DisableTailCalls = Args.hasArg(OPT_mdisable_tail_calls);
1256  Opts.FloatABI = Args.getLastArgValue(OPT_mfloat_abi);
1257  Opts.HiddenWeakVTables = Args.hasArg(OPT_fhidden_weak_vtables);
1258  Opts.LessPreciseFPMAD = Args.hasArg(OPT_cl_mad_enable);
1259  Opts.LimitFloatPrecision = Args.getLastArgValue(OPT_mlimit_float_precision);
1260  Opts.NoInfsFPMath = (Args.hasArg(OPT_menable_no_infinities) ||
1261                       Args.hasArg(OPT_cl_finite_math_only)||
1262                       Args.hasArg(OPT_cl_fast_relaxed_math));
1263  Opts.NoNaNsFPMath = (Args.hasArg(OPT_menable_no_nans) ||
1264                       Args.hasArg(OPT_cl_finite_math_only)||
1265                       Args.hasArg(OPT_cl_fast_relaxed_math));
1266  Opts.NoZeroInitializedInBSS = Args.hasArg(OPT_mno_zero_initialized_in_bss);
1267  Opts.BackendOptions = Args.getAllArgValues(OPT_backend_option);
1268  Opts.NumRegisterParameters = Args.getLastArgIntValue(OPT_mregparm, 0, Diags);
1269  Opts.NoGlobalMerge = Args.hasArg(OPT_mno_global_merge);
1270  Opts.NoExecStack = Args.hasArg(OPT_mno_exec_stack);
1271  Opts.RelaxAll = Args.hasArg(OPT_mrelax_all);
1272  Opts.OmitLeafFramePointer = Args.hasArg(OPT_momit_leaf_frame_pointer);
1273  Opts.SaveTempLabels = Args.hasArg(OPT_msave_temp_labels);
1274  Opts.NoDwarf2CFIAsm = Args.hasArg(OPT_fno_dwarf2_cfi_asm);
1275  Opts.NoDwarfDirectoryAsm = Args.hasArg(OPT_fno_dwarf_directory_asm);
1276  Opts.SoftFloat = Args.hasArg(OPT_msoft_float);
1277  Opts.StrictEnums = Args.hasArg(OPT_fstrict_enums);
1278  Opts.UnsafeFPMath = Args.hasArg(OPT_menable_unsafe_fp_math) ||
1279                      Args.hasArg(OPT_cl_unsafe_math_optimizations) ||
1280                      Args.hasArg(OPT_cl_fast_relaxed_math);
1281  Opts.UnwindTables = Args.hasArg(OPT_munwind_tables);
1282  Opts.RelocationModel = Args.getLastArgValue(OPT_mrelocation_model, "pic");
1283  Opts.TrapFuncName = Args.getLastArgValue(OPT_ftrap_function_EQ);
1284  Opts.BoundsChecking = Args.getLastArgIntValue(OPT_fbounds_checking_EQ, 0,
1285                                                Diags);
1286  Opts.UseInitArray = Args.hasArg(OPT_fuse_init_array);
1287
1288  Opts.FunctionSections = Args.hasArg(OPT_ffunction_sections);
1289  Opts.DataSections = Args.hasArg(OPT_fdata_sections);
1290
1291  Opts.MainFileName = Args.getLastArgValue(OPT_main_file_name);
1292  Opts.VerifyModule = !Args.hasArg(OPT_disable_llvm_verifier);
1293
1294  Opts.InstrumentFunctions = Args.hasArg(OPT_finstrument_functions);
1295  Opts.InstrumentForProfiling = Args.hasArg(OPT_pg);
1296  Opts.EmitGcovArcs = Args.hasArg(OPT_femit_coverage_data);
1297  Opts.EmitGcovNotes = Args.hasArg(OPT_femit_coverage_notes);
1298  Opts.EmitOpenCLArgMetadata = Args.hasArg(OPT_cl_kernel_arg_info);
1299  Opts.CoverageFile = Args.getLastArgValue(OPT_coverage_file);
1300  Opts.DebugCompilationDir = Args.getLastArgValue(OPT_fdebug_compilation_dir);
1301  Opts.LinkBitcodeFile = Args.getLastArgValue(OPT_mlink_bitcode_file);
1302  Opts.SSPBufferSize =
1303    Args.getLastArgIntValue(OPT_stack_protector_buffer_size, 8, Diags);
1304  Opts.StackRealignment = Args.hasArg(OPT_mstackrealign);
1305  if (Arg *A = Args.getLastArg(OPT_mstack_alignment)) {
1306    StringRef Val = A->getValue(Args);
1307    Val.getAsInteger(10, Opts.StackAlignment);
1308  }
1309
1310  if (Arg *A = Args.getLastArg(OPT_fobjc_dispatch_method_EQ)) {
1311    StringRef Name = A->getValue(Args);
1312    unsigned Method = llvm::StringSwitch<unsigned>(Name)
1313      .Case("legacy", CodeGenOptions::Legacy)
1314      .Case("non-legacy", CodeGenOptions::NonLegacy)
1315      .Case("mixed", CodeGenOptions::Mixed)
1316      .Default(~0U);
1317    if (Method == ~0U) {
1318      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1319      Success = false;
1320    } else {
1321      Opts.ObjCDispatchMethod = Method;
1322    }
1323  }
1324
1325  if (Arg *A = Args.getLastArg(OPT_ftlsmodel_EQ)) {
1326    StringRef Name = A->getValue(Args);
1327    unsigned Model = llvm::StringSwitch<unsigned>(Name)
1328        .Case("global-dynamic", CodeGenOptions::GeneralDynamicTLSModel)
1329        .Case("local-dynamic", CodeGenOptions::LocalDynamicTLSModel)
1330        .Case("initial-exec", CodeGenOptions::InitialExecTLSModel)
1331        .Case("local-exec", CodeGenOptions::LocalExecTLSModel)
1332        .Default(~0U);
1333    if (Model == ~0U) {
1334      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
1335      Success = false;
1336    } else {
1337      Opts.DefaultTLSModel = static_cast<CodeGenOptions::TLSModel>(Model);
1338    }
1339  }
1340
1341  return Success;
1342}
1343
1344static void ParseDependencyOutputArgs(DependencyOutputOptions &Opts,
1345                                      ArgList &Args) {
1346  using namespace options;
1347  Opts.OutputFile = Args.getLastArgValue(OPT_dependency_file);
1348  Opts.Targets = Args.getAllArgValues(OPT_MT);
1349  Opts.IncludeSystemHeaders = Args.hasArg(OPT_sys_header_deps);
1350  Opts.UsePhonyTargets = Args.hasArg(OPT_MP);
1351  Opts.ShowHeaderIncludes = Args.hasArg(OPT_H);
1352  Opts.HeaderIncludeOutputFile = Args.getLastArgValue(OPT_header_include_file);
1353  Opts.AddMissingHeaderDeps = Args.hasArg(OPT_MG);
1354  Opts.DOTOutputFile = Args.getLastArgValue(OPT_dependency_dot);
1355}
1356
1357bool clang::ParseDiagnosticArgs(DiagnosticOptions &Opts, ArgList &Args,
1358                                DiagnosticsEngine *Diags) {
1359  using namespace options;
1360  bool Success = true;
1361
1362  Opts.DiagnosticLogFile = Args.getLastArgValue(OPT_diagnostic_log_file);
1363  Opts.DiagnosticSerializationFile =
1364    Args.getLastArgValue(OPT_diagnostic_serialized_file);
1365  Opts.IgnoreWarnings = Args.hasArg(OPT_w);
1366  Opts.NoRewriteMacros = Args.hasArg(OPT_Wno_rewrite_macros);
1367  Opts.Pedantic = Args.hasArg(OPT_pedantic);
1368  Opts.PedanticErrors = Args.hasArg(OPT_pedantic_errors);
1369  Opts.ShowCarets = !Args.hasArg(OPT_fno_caret_diagnostics);
1370  Opts.ShowColors = Args.hasArg(OPT_fcolor_diagnostics);
1371  Opts.ShowColumn = Args.hasFlag(OPT_fshow_column,
1372                                 OPT_fno_show_column,
1373                                 /*Default=*/true);
1374  Opts.ShowFixits = !Args.hasArg(OPT_fno_diagnostics_fixit_info);
1375  Opts.ShowLocation = !Args.hasArg(OPT_fno_show_source_location);
1376  Opts.ShowOptionNames = Args.hasArg(OPT_fdiagnostics_show_option);
1377
1378  // Default behavior is to not to show note include stacks.
1379  Opts.ShowNoteIncludeStack = false;
1380  if (Arg *A = Args.getLastArg(OPT_fdiagnostics_show_note_include_stack,
1381                               OPT_fno_diagnostics_show_note_include_stack))
1382    if (A->getOption().matches(OPT_fdiagnostics_show_note_include_stack))
1383      Opts.ShowNoteIncludeStack = true;
1384
1385  StringRef ShowOverloads =
1386    Args.getLastArgValue(OPT_fshow_overloads_EQ, "all");
1387  if (ShowOverloads == "best")
1388    Opts.ShowOverloads = DiagnosticsEngine::Ovl_Best;
1389  else if (ShowOverloads == "all")
1390    Opts.ShowOverloads = DiagnosticsEngine::Ovl_All;
1391  else {
1392    Success = false;
1393    if (Diags)
1394      Diags->Report(diag::err_drv_invalid_value)
1395      << Args.getLastArg(OPT_fshow_overloads_EQ)->getAsString(Args)
1396      << ShowOverloads;
1397  }
1398
1399  StringRef ShowCategory =
1400    Args.getLastArgValue(OPT_fdiagnostics_show_category, "none");
1401  if (ShowCategory == "none")
1402    Opts.ShowCategories = 0;
1403  else if (ShowCategory == "id")
1404    Opts.ShowCategories = 1;
1405  else if (ShowCategory == "name")
1406    Opts.ShowCategories = 2;
1407  else {
1408    Success = false;
1409    if (Diags)
1410      Diags->Report(diag::err_drv_invalid_value)
1411      << Args.getLastArg(OPT_fdiagnostics_show_category)->getAsString(Args)
1412      << ShowCategory;
1413  }
1414
1415  StringRef Format =
1416    Args.getLastArgValue(OPT_fdiagnostics_format, "clang");
1417  if (Format == "clang")
1418    Opts.Format = DiagnosticOptions::Clang;
1419  else if (Format == "msvc")
1420    Opts.Format = DiagnosticOptions::Msvc;
1421  else if (Format == "vi")
1422    Opts.Format = DiagnosticOptions::Vi;
1423  else {
1424    Success = false;
1425    if (Diags)
1426      Diags->Report(diag::err_drv_invalid_value)
1427      << Args.getLastArg(OPT_fdiagnostics_format)->getAsString(Args)
1428      << Format;
1429  }
1430
1431  Opts.ShowSourceRanges = Args.hasArg(OPT_fdiagnostics_print_source_range_info);
1432  Opts.ShowParseableFixits = Args.hasArg(OPT_fdiagnostics_parseable_fixits);
1433  Opts.VerifyDiagnostics = Args.hasArg(OPT_verify);
1434  Opts.ElideType = !Args.hasArg(OPT_fno_elide_type);
1435  Opts.ShowTemplateTree = Args.hasArg(OPT_fdiagnostics_show_template_tree);
1436  Opts.ErrorLimit = Args.getLastArgIntValue(OPT_ferror_limit, 0, Diags);
1437  Opts.MacroBacktraceLimit
1438    = Args.getLastArgIntValue(OPT_fmacro_backtrace_limit,
1439                         DiagnosticOptions::DefaultMacroBacktraceLimit, Diags);
1440  Opts.TemplateBacktraceLimit
1441    = Args.getLastArgIntValue(OPT_ftemplate_backtrace_limit,
1442                         DiagnosticOptions::DefaultTemplateBacktraceLimit,
1443                         Diags);
1444  Opts.ConstexprBacktraceLimit
1445    = Args.getLastArgIntValue(OPT_fconstexpr_backtrace_limit,
1446                         DiagnosticOptions::DefaultConstexprBacktraceLimit,
1447                         Diags);
1448  Opts.TabStop = Args.getLastArgIntValue(OPT_ftabstop,
1449                                    DiagnosticOptions::DefaultTabStop, Diags);
1450  if (Opts.TabStop == 0 || Opts.TabStop > DiagnosticOptions::MaxTabStop) {
1451    Opts.TabStop = DiagnosticOptions::DefaultTabStop;
1452    if (Diags)
1453      Diags->Report(diag::warn_ignoring_ftabstop_value)
1454      << Opts.TabStop << DiagnosticOptions::DefaultTabStop;
1455  }
1456  Opts.MessageLength = Args.getLastArgIntValue(OPT_fmessage_length, 0, Diags);
1457  Opts.DumpBuildInformation = Args.getLastArgValue(OPT_dump_build_information);
1458  addWarningArgs(Args, Opts.Warnings);
1459
1460  return Success;
1461}
1462
1463static void ParseFileSystemArgs(FileSystemOptions &Opts, ArgList &Args) {
1464  Opts.WorkingDir = Args.getLastArgValue(OPT_working_directory);
1465}
1466
1467static InputKind ParseFrontendArgs(FrontendOptions &Opts, ArgList &Args,
1468                                   DiagnosticsEngine &Diags) {
1469  using namespace options;
1470  Opts.ProgramAction = frontend::ParseSyntaxOnly;
1471  if (const Arg *A = Args.getLastArg(OPT_Action_Group)) {
1472    switch (A->getOption().getID()) {
1473    default:
1474      llvm_unreachable("Invalid option in group!");
1475    case OPT_ast_list:
1476      Opts.ProgramAction = frontend::ASTDeclList; break;
1477    case OPT_ast_dump:
1478      Opts.ProgramAction = frontend::ASTDump; break;
1479    case OPT_ast_dump_xml:
1480      Opts.ProgramAction = frontend::ASTDumpXML; break;
1481    case OPT_ast_print:
1482      Opts.ProgramAction = frontend::ASTPrint; break;
1483    case OPT_ast_view:
1484      Opts.ProgramAction = frontend::ASTView; break;
1485    case OPT_dump_raw_tokens:
1486      Opts.ProgramAction = frontend::DumpRawTokens; break;
1487    case OPT_dump_tokens:
1488      Opts.ProgramAction = frontend::DumpTokens; break;
1489    case OPT_S:
1490      Opts.ProgramAction = frontend::EmitAssembly; break;
1491    case OPT_emit_llvm_bc:
1492      Opts.ProgramAction = frontend::EmitBC; break;
1493    case OPT_emit_html:
1494      Opts.ProgramAction = frontend::EmitHTML; break;
1495    case OPT_emit_llvm:
1496      Opts.ProgramAction = frontend::EmitLLVM; break;
1497    case OPT_emit_llvm_only:
1498      Opts.ProgramAction = frontend::EmitLLVMOnly; break;
1499    case OPT_emit_codegen_only:
1500      Opts.ProgramAction = frontend::EmitCodeGenOnly; break;
1501    case OPT_emit_obj:
1502      Opts.ProgramAction = frontend::EmitObj; break;
1503    case OPT_fixit_EQ:
1504      Opts.FixItSuffix = A->getValue(Args);
1505      // fall-through!
1506    case OPT_fixit:
1507      Opts.ProgramAction = frontend::FixIt; break;
1508    case OPT_emit_module:
1509      Opts.ProgramAction = frontend::GenerateModule; break;
1510    case OPT_emit_pch:
1511      Opts.ProgramAction = frontend::GeneratePCH; break;
1512    case OPT_emit_pth:
1513      Opts.ProgramAction = frontend::GeneratePTH; break;
1514    case OPT_init_only:
1515      Opts.ProgramAction = frontend::InitOnly; break;
1516    case OPT_fsyntax_only:
1517      Opts.ProgramAction = frontend::ParseSyntaxOnly; break;
1518    case OPT_print_decl_contexts:
1519      Opts.ProgramAction = frontend::PrintDeclContext; break;
1520    case OPT_print_preamble:
1521      Opts.ProgramAction = frontend::PrintPreamble; break;
1522    case OPT_E:
1523      Opts.ProgramAction = frontend::PrintPreprocessedInput; break;
1524    case OPT_rewrite_macros:
1525      Opts.ProgramAction = frontend::RewriteMacros; break;
1526    case OPT_rewrite_objc:
1527      Opts.ProgramAction = frontend::RewriteObjC; break;
1528    case OPT_rewrite_test:
1529      Opts.ProgramAction = frontend::RewriteTest; break;
1530    case OPT_analyze:
1531      Opts.ProgramAction = frontend::RunAnalysis; break;
1532    case OPT_migrate:
1533      Opts.ProgramAction = frontend::MigrateSource; break;
1534    case OPT_Eonly:
1535      Opts.ProgramAction = frontend::RunPreprocessorOnly; break;
1536    }
1537  }
1538
1539  if (const Arg* A = Args.getLastArg(OPT_plugin)) {
1540    Opts.Plugins.push_back(A->getValue(Args,0));
1541    Opts.ProgramAction = frontend::PluginAction;
1542    Opts.ActionName = A->getValue(Args);
1543
1544    for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
1545           end = Args.filtered_end(); it != end; ++it) {
1546      if ((*it)->getValue(Args, 0) == Opts.ActionName)
1547        Opts.PluginArgs.push_back((*it)->getValue(Args, 1));
1548    }
1549  }
1550
1551  Opts.AddPluginActions = Args.getAllArgValues(OPT_add_plugin);
1552  Opts.AddPluginArgs.resize(Opts.AddPluginActions.size());
1553  for (int i = 0, e = Opts.AddPluginActions.size(); i != e; ++i) {
1554    for (arg_iterator it = Args.filtered_begin(OPT_plugin_arg),
1555           end = Args.filtered_end(); it != end; ++it) {
1556      if ((*it)->getValue(Args, 0) == Opts.AddPluginActions[i])
1557        Opts.AddPluginArgs[i].push_back((*it)->getValue(Args, 1));
1558    }
1559  }
1560
1561  if (const Arg *A = Args.getLastArg(OPT_code_completion_at)) {
1562    Opts.CodeCompletionAt =
1563      ParsedSourceLocation::FromString(A->getValue(Args));
1564    if (Opts.CodeCompletionAt.FileName.empty())
1565      Diags.Report(diag::err_drv_invalid_value)
1566        << A->getAsString(Args) << A->getValue(Args);
1567  }
1568  Opts.DisableFree = Args.hasArg(OPT_disable_free);
1569
1570  Opts.OutputFile = Args.getLastArgValue(OPT_o);
1571  Opts.Plugins = Args.getAllArgValues(OPT_load);
1572  Opts.RelocatablePCH = Args.hasArg(OPT_relocatable_pch);
1573  Opts.ShowHelp = Args.hasArg(OPT_help);
1574  Opts.ShowStats = Args.hasArg(OPT_print_stats);
1575  Opts.ShowTimers = Args.hasArg(OPT_ftime_report);
1576  Opts.ShowVersion = Args.hasArg(OPT_version);
1577  Opts.ASTMergeFiles = Args.getAllArgValues(OPT_ast_merge);
1578  Opts.LLVMArgs = Args.getAllArgValues(OPT_mllvm);
1579  Opts.FixWhatYouCan = Args.hasArg(OPT_fix_what_you_can);
1580  Opts.FixOnlyWarnings = Args.hasArg(OPT_fix_only_warnings);
1581  Opts.FixAndRecompile = Args.hasArg(OPT_fixit_recompile);
1582  Opts.FixToTemporaries = Args.hasArg(OPT_fixit_to_temp);
1583  Opts.ASTDumpFilter = Args.getLastArgValue(OPT_ast_dump_filter);
1584
1585  Opts.CodeCompleteOpts.IncludeMacros
1586    = Args.hasArg(OPT_code_completion_macros);
1587  Opts.CodeCompleteOpts.IncludeCodePatterns
1588    = Args.hasArg(OPT_code_completion_patterns);
1589  Opts.CodeCompleteOpts.IncludeGlobals
1590    = !Args.hasArg(OPT_no_code_completion_globals);
1591  Opts.CodeCompleteOpts.IncludeBriefComments
1592    = Args.hasArg(OPT_code_completion_brief_comments);
1593
1594  Opts.OverrideRecordLayoutsFile
1595    = Args.getLastArgValue(OPT_foverride_record_layout_EQ);
1596  if (const Arg *A = Args.getLastArg(OPT_arcmt_check,
1597                                     OPT_arcmt_modify,
1598                                     OPT_arcmt_migrate)) {
1599    switch (A->getOption().getID()) {
1600    default:
1601      llvm_unreachable("missed a case");
1602    case OPT_arcmt_check:
1603      Opts.ARCMTAction = FrontendOptions::ARCMT_Check;
1604      break;
1605    case OPT_arcmt_modify:
1606      Opts.ARCMTAction = FrontendOptions::ARCMT_Modify;
1607      break;
1608    case OPT_arcmt_migrate:
1609      Opts.ARCMTAction = FrontendOptions::ARCMT_Migrate;
1610      break;
1611    }
1612  }
1613  Opts.MTMigrateDir = Args.getLastArgValue(OPT_mt_migrate_directory);
1614  Opts.ARCMTMigrateReportOut
1615    = Args.getLastArgValue(OPT_arcmt_migrate_report_output);
1616  Opts.ARCMTMigrateEmitARCErrors
1617    = Args.hasArg(OPT_arcmt_migrate_emit_arc_errors);
1618
1619  if (Args.hasArg(OPT_objcmt_migrate_literals))
1620    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Literals;
1621  if (Args.hasArg(OPT_objcmt_migrate_subscripting))
1622    Opts.ObjCMTAction |= FrontendOptions::ObjCMT_Subscripting;
1623
1624  if (Opts.ARCMTAction != FrontendOptions::ARCMT_None &&
1625      Opts.ObjCMTAction != FrontendOptions::ObjCMT_None) {
1626    Diags.Report(diag::err_drv_argument_not_allowed_with)
1627      << "ARC migration" << "ObjC migration";
1628  }
1629
1630  InputKind DashX = IK_None;
1631  if (const Arg *A = Args.getLastArg(OPT_x)) {
1632    DashX = llvm::StringSwitch<InputKind>(A->getValue(Args))
1633      .Case("c", IK_C)
1634      .Case("cl", IK_OpenCL)
1635      .Case("cuda", IK_CUDA)
1636      .Case("c++", IK_CXX)
1637      .Case("objective-c", IK_ObjC)
1638      .Case("objective-c++", IK_ObjCXX)
1639      .Case("cpp-output", IK_PreprocessedC)
1640      .Case("assembler-with-cpp", IK_Asm)
1641      .Case("c++-cpp-output", IK_PreprocessedCXX)
1642      .Case("objective-c-cpp-output", IK_PreprocessedObjC)
1643      .Case("objc-cpp-output", IK_PreprocessedObjC)
1644      .Case("objective-c++-cpp-output", IK_PreprocessedObjCXX)
1645      .Case("objc++-cpp-output", IK_PreprocessedObjCXX)
1646      .Case("c-header", IK_C)
1647      .Case("cl-header", IK_OpenCL)
1648      .Case("objective-c-header", IK_ObjC)
1649      .Case("c++-header", IK_CXX)
1650      .Case("objective-c++-header", IK_ObjCXX)
1651      .Case("ast", IK_AST)
1652      .Case("ir", IK_LLVM_IR)
1653      .Default(IK_None);
1654    if (DashX == IK_None)
1655      Diags.Report(diag::err_drv_invalid_value)
1656        << A->getAsString(Args) << A->getValue(Args);
1657  }
1658
1659  // '-' is the default input if none is given.
1660  std::vector<std::string> Inputs = Args.getAllArgValues(OPT_INPUT);
1661  Opts.Inputs.clear();
1662  if (Inputs.empty())
1663    Inputs.push_back("-");
1664  for (unsigned i = 0, e = Inputs.size(); i != e; ++i) {
1665    InputKind IK = DashX;
1666    if (IK == IK_None) {
1667      IK = FrontendOptions::getInputKindForExtension(
1668        StringRef(Inputs[i]).rsplit('.').second);
1669      // FIXME: Remove this hack.
1670      if (i == 0)
1671        DashX = IK;
1672    }
1673    Opts.Inputs.push_back(FrontendInputFile(Inputs[i], IK));
1674  }
1675
1676  return DashX;
1677}
1678
1679std::string CompilerInvocation::GetResourcesPath(const char *Argv0,
1680                                                 void *MainAddr) {
1681  llvm::sys::Path P = llvm::sys::Path::GetMainExecutable(Argv0, MainAddr);
1682
1683  if (!P.isEmpty()) {
1684    P.eraseComponent();  // Remove /clang from foo/bin/clang
1685    P.eraseComponent();  // Remove /bin   from foo/bin
1686
1687    // Get foo/lib/clang/<version>/include
1688    P.appendComponent("lib");
1689    P.appendComponent("clang");
1690    P.appendComponent(CLANG_VERSION_STRING);
1691  }
1692
1693  return P.str();
1694}
1695
1696static void ParseHeaderSearchArgs(HeaderSearchOptions &Opts, ArgList &Args) {
1697  using namespace options;
1698  Opts.Sysroot = Args.getLastArgValue(OPT_isysroot, "/");
1699  Opts.Verbose = Args.hasArg(OPT_v);
1700  Opts.UseBuiltinIncludes = !Args.hasArg(OPT_nobuiltininc);
1701  Opts.UseStandardSystemIncludes = !Args.hasArg(OPT_nostdsysteminc);
1702  Opts.UseStandardCXXIncludes = !Args.hasArg(OPT_nostdincxx);
1703  if (const Arg *A = Args.getLastArg(OPT_stdlib_EQ))
1704    Opts.UseLibcxx = (strcmp(A->getValue(Args), "libc++") == 0);
1705  Opts.ResourceDir = Args.getLastArgValue(OPT_resource_dir);
1706  Opts.ModuleCachePath = Args.getLastArgValue(OPT_fmodule_cache_path);
1707  Opts.DisableModuleHash = Args.hasArg(OPT_fdisable_module_hash);
1708
1709  // Add -I..., -F..., and -index-header-map options in order.
1710  bool IsIndexHeaderMap = false;
1711  for (arg_iterator it = Args.filtered_begin(OPT_I, OPT_F,
1712                                             OPT_index_header_map),
1713       ie = Args.filtered_end(); it != ie; ++it) {
1714    if ((*it)->getOption().matches(OPT_index_header_map)) {
1715      // -index-header-map applies to the next -I or -F.
1716      IsIndexHeaderMap = true;
1717      continue;
1718    }
1719
1720    frontend::IncludeDirGroup Group
1721      = IsIndexHeaderMap? frontend::IndexHeaderMap : frontend::Angled;
1722
1723    Opts.AddPath((*it)->getValue(Args), Group, true,
1724                 /*IsFramework=*/ (*it)->getOption().matches(OPT_F), false);
1725    IsIndexHeaderMap = false;
1726  }
1727
1728  // Add -iprefix/-iwith-prefix/-iwithprefixbefore options.
1729  StringRef Prefix = ""; // FIXME: This isn't the correct default prefix.
1730  for (arg_iterator it = Args.filtered_begin(OPT_iprefix, OPT_iwithprefix,
1731                                             OPT_iwithprefixbefore),
1732         ie = Args.filtered_end(); it != ie; ++it) {
1733    const Arg *A = *it;
1734    if (A->getOption().matches(OPT_iprefix))
1735      Prefix = A->getValue(Args);
1736    else if (A->getOption().matches(OPT_iwithprefix))
1737      Opts.AddPath(Prefix.str() + A->getValue(Args),
1738                   frontend::System, false, false, false);
1739    else
1740      Opts.AddPath(Prefix.str() + A->getValue(Args),
1741                   frontend::Angled, false, false, false);
1742  }
1743
1744  for (arg_iterator it = Args.filtered_begin(OPT_idirafter),
1745         ie = Args.filtered_end(); it != ie; ++it)
1746    Opts.AddPath((*it)->getValue(Args), frontend::After, true, false, false);
1747  for (arg_iterator it = Args.filtered_begin(OPT_iquote),
1748         ie = Args.filtered_end(); it != ie; ++it)
1749    Opts.AddPath((*it)->getValue(Args), frontend::Quoted, true, false, false);
1750  for (arg_iterator it = Args.filtered_begin(OPT_isystem,
1751         OPT_iwithsysroot), ie = Args.filtered_end(); it != ie; ++it)
1752    Opts.AddPath((*it)->getValue(Args), frontend::System, true, false,
1753                 !(*it)->getOption().matches(OPT_iwithsysroot));
1754  for (arg_iterator it = Args.filtered_begin(OPT_iframework),
1755         ie = Args.filtered_end(); it != ie; ++it)
1756    Opts.AddPath((*it)->getValue(Args), frontend::System, true, true,
1757                 true);
1758
1759  // Add the paths for the various language specific isystem flags.
1760  for (arg_iterator it = Args.filtered_begin(OPT_c_isystem),
1761       ie = Args.filtered_end(); it != ie; ++it)
1762    Opts.AddPath((*it)->getValue(Args), frontend::CSystem, true, false, true);
1763  for (arg_iterator it = Args.filtered_begin(OPT_cxx_isystem),
1764       ie = Args.filtered_end(); it != ie; ++it)
1765    Opts.AddPath((*it)->getValue(Args), frontend::CXXSystem, true, false, true);
1766  for (arg_iterator it = Args.filtered_begin(OPT_objc_isystem),
1767       ie = Args.filtered_end(); it != ie; ++it)
1768    Opts.AddPath((*it)->getValue(Args), frontend::ObjCSystem, true, false,true);
1769  for (arg_iterator it = Args.filtered_begin(OPT_objcxx_isystem),
1770       ie = Args.filtered_end(); it != ie; ++it)
1771    Opts.AddPath((*it)->getValue(Args), frontend::ObjCXXSystem, true, false,
1772                 true);
1773
1774  // Add the internal paths from a driver that detects standard include paths.
1775  for (arg_iterator I = Args.filtered_begin(OPT_internal_isystem,
1776                                            OPT_internal_externc_isystem),
1777                    E = Args.filtered_end();
1778       I != E; ++I)
1779    Opts.AddPath((*I)->getValue(Args), frontend::System,
1780                 false, false, /*IgnoreSysRoot=*/true, /*IsInternal=*/true,
1781                 (*I)->getOption().matches(OPT_internal_externc_isystem));
1782
1783  // Add the path prefixes which are implicitly treated as being system headers.
1784  for (arg_iterator I = Args.filtered_begin(OPT_isystem_prefix,
1785                                            OPT_ino_system_prefix),
1786                    E = Args.filtered_end();
1787       I != E; ++I)
1788    Opts.AddSystemHeaderPrefix((*I)->getValue(Args),
1789                               (*I)->getOption().matches(OPT_isystem_prefix));
1790}
1791
1792void CompilerInvocation::setLangDefaults(LangOptions &Opts, InputKind IK,
1793                                         LangStandard::Kind LangStd) {
1794  // Set some properties which depend solely on the input kind; it would be nice
1795  // to move these to the language standard, and have the driver resolve the
1796  // input kind + language standard.
1797  if (IK == IK_Asm) {
1798    Opts.AsmPreprocessor = 1;
1799  } else if (IK == IK_ObjC ||
1800             IK == IK_ObjCXX ||
1801             IK == IK_PreprocessedObjC ||
1802             IK == IK_PreprocessedObjCXX) {
1803    Opts.ObjC1 = Opts.ObjC2 = 1;
1804  }
1805
1806  if (LangStd == LangStandard::lang_unspecified) {
1807    // Based on the base language, pick one.
1808    switch (IK) {
1809    case IK_None:
1810    case IK_AST:
1811    case IK_LLVM_IR:
1812      llvm_unreachable("Invalid input kind!");
1813    case IK_OpenCL:
1814      LangStd = LangStandard::lang_opencl;
1815      break;
1816    case IK_CUDA:
1817      LangStd = LangStandard::lang_cuda;
1818      break;
1819    case IK_Asm:
1820    case IK_C:
1821    case IK_PreprocessedC:
1822    case IK_ObjC:
1823    case IK_PreprocessedObjC:
1824      LangStd = LangStandard::lang_gnu99;
1825      break;
1826    case IK_CXX:
1827    case IK_PreprocessedCXX:
1828    case IK_ObjCXX:
1829    case IK_PreprocessedObjCXX:
1830      LangStd = LangStandard::lang_gnucxx98;
1831      break;
1832    }
1833  }
1834
1835  const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1836  Opts.BCPLComment = Std.hasBCPLComments();
1837  Opts.C99 = Std.isC99();
1838  Opts.C11 = Std.isC11();
1839  Opts.CPlusPlus = Std.isCPlusPlus();
1840  Opts.CPlusPlus0x = Std.isCPlusPlus0x();
1841  Opts.Digraphs = Std.hasDigraphs();
1842  Opts.GNUMode = Std.isGNUMode();
1843  Opts.GNUInline = !Std.isC99();
1844  Opts.HexFloats = Std.hasHexFloats();
1845  Opts.ImplicitInt = Std.hasImplicitInt();
1846
1847  // Set OpenCL Version.
1848  if (LangStd == LangStandard::lang_opencl) {
1849    Opts.OpenCL = 1;
1850    Opts.OpenCLVersion = 100;
1851  }
1852  else if (LangStd == LangStandard::lang_opencl11) {
1853      Opts.OpenCL = 1;
1854      Opts.OpenCLVersion = 110;
1855  }
1856  else if (LangStd == LangStandard::lang_opencl12) {
1857    Opts.OpenCL = 1;
1858    Opts.OpenCLVersion = 120;
1859  }
1860
1861  // OpenCL has some additional defaults.
1862  if (Opts.OpenCL) {
1863    Opts.AltiVec = 0;
1864    Opts.CXXOperatorNames = 1;
1865    Opts.LaxVectorConversions = 0;
1866    Opts.DefaultFPContract = 1;
1867  }
1868
1869  if (LangStd == LangStandard::lang_cuda)
1870    Opts.CUDA = 1;
1871
1872  // OpenCL and C++ both have bool, true, false keywords.
1873  Opts.Bool = Opts.OpenCL || Opts.CPlusPlus;
1874
1875  // C++ has wchar_t keyword.
1876  Opts.WChar = Opts.CPlusPlus;
1877
1878  Opts.GNUKeywords = Opts.GNUMode;
1879  Opts.CXXOperatorNames = Opts.CPlusPlus;
1880
1881  // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs
1882  // is specified, or -std is set to a conforming mode.
1883  Opts.Trigraphs = !Opts.GNUMode;
1884
1885  Opts.DollarIdents = !Opts.AsmPreprocessor;
1886}
1887
1888static void ParseLangArgs(LangOptions &Opts, ArgList &Args, InputKind IK,
1889                          DiagnosticsEngine &Diags) {
1890  // FIXME: Cleanup per-file based stuff.
1891  LangStandard::Kind LangStd = LangStandard::lang_unspecified;
1892  if (const Arg *A = Args.getLastArg(OPT_std_EQ)) {
1893    LangStd = llvm::StringSwitch<LangStandard::Kind>(A->getValue(Args))
1894#define LANGSTANDARD(id, name, desc, features) \
1895      .Case(name, LangStandard::lang_##id)
1896#include "clang/Frontend/LangStandards.def"
1897      .Default(LangStandard::lang_unspecified);
1898    if (LangStd == LangStandard::lang_unspecified)
1899      Diags.Report(diag::err_drv_invalid_value)
1900        << A->getAsString(Args) << A->getValue(Args);
1901    else {
1902      // Valid standard, check to make sure language and standard are compatable.
1903      const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd);
1904      switch (IK) {
1905      case IK_C:
1906      case IK_ObjC:
1907      case IK_PreprocessedC:
1908      case IK_PreprocessedObjC:
1909        if (!(Std.isC89() || Std.isC99()))
1910          Diags.Report(diag::err_drv_argument_not_allowed_with)
1911            << A->getAsString(Args) << "C/ObjC";
1912        break;
1913      case IK_CXX:
1914      case IK_ObjCXX:
1915      case IK_PreprocessedCXX:
1916      case IK_PreprocessedObjCXX:
1917        if (!Std.isCPlusPlus())
1918          Diags.Report(diag::err_drv_argument_not_allowed_with)
1919            << A->getAsString(Args) << "C++/ObjC++";
1920        break;
1921      case IK_OpenCL:
1922        if (!Std.isC99())
1923          Diags.Report(diag::err_drv_argument_not_allowed_with)
1924            << A->getAsString(Args) << "OpenCL";
1925        break;
1926      case IK_CUDA:
1927        if (!Std.isCPlusPlus())
1928          Diags.Report(diag::err_drv_argument_not_allowed_with)
1929            << A->getAsString(Args) << "CUDA";
1930        break;
1931      default:
1932        break;
1933      }
1934    }
1935  }
1936
1937  // -cl-std only applies for OpenCL language standards.
1938  // Override the -std option in this case.
1939  if (const Arg *A = Args.getLastArg(OPT_cl_std_EQ)) {
1940    LangStandard::Kind OpenCLLangStd
1941    = llvm::StringSwitch<LangStandard::Kind>(A->getValue(Args))
1942    .Case("CL", LangStandard::lang_opencl)
1943    .Case("CL1.1", LangStandard::lang_opencl11)
1944    .Case("CL1.2", LangStandard::lang_opencl12)
1945    .Default(LangStandard::lang_unspecified);
1946
1947    if (OpenCLLangStd == LangStandard::lang_unspecified) {
1948      Diags.Report(diag::err_drv_invalid_value)
1949      << A->getAsString(Args) << A->getValue(Args);
1950    }
1951    else
1952      LangStd = OpenCLLangStd;
1953  }
1954
1955  CompilerInvocation::setLangDefaults(Opts, IK, LangStd);
1956
1957  // We abuse '-f[no-]gnu-keywords' to force overriding all GNU-extension
1958  // keywords. This behavior is provided by GCC's poorly named '-fasm' flag,
1959  // while a subset (the non-C++ GNU keywords) is provided by GCC's
1960  // '-fgnu-keywords'. Clang conflates the two for simplicity under the single
1961  // name, as it doesn't seem a useful distinction.
1962  Opts.GNUKeywords = Args.hasFlag(OPT_fgnu_keywords, OPT_fno_gnu_keywords,
1963                                  Opts.GNUKeywords);
1964
1965  if (Args.hasArg(OPT_fno_operator_names))
1966    Opts.CXXOperatorNames = 0;
1967
1968  if (Opts.ObjC1) {
1969    if (Arg *arg = Args.getLastArg(OPT_fobjc_runtime_EQ)) {
1970      StringRef value = arg->getValue(Args);
1971      if (Opts.ObjCRuntime.tryParse(value))
1972        Diags.Report(diag::err_drv_unknown_objc_runtime) << value;
1973    }
1974
1975    if (Args.hasArg(OPT_fobjc_gc_only))
1976      Opts.setGC(LangOptions::GCOnly);
1977    else if (Args.hasArg(OPT_fobjc_gc))
1978      Opts.setGC(LangOptions::HybridGC);
1979    else if (Args.hasArg(OPT_fobjc_arc)) {
1980      Opts.ObjCAutoRefCount = 1;
1981      if (!Opts.ObjCRuntime.allowsARC())
1982        Diags.Report(diag::err_arc_unsupported_on_runtime);
1983
1984      // Only set ObjCARCWeak if ARC is enabled.
1985      if (Args.hasArg(OPT_fobjc_runtime_has_weak))
1986        Opts.ObjCARCWeak = 1;
1987      else
1988        Opts.ObjCARCWeak = Opts.ObjCRuntime.allowsWeak();
1989    }
1990
1991    if (Args.hasArg(OPT_fno_objc_infer_related_result_type))
1992      Opts.ObjCInferRelatedResultType = 0;
1993  }
1994
1995  if (Args.hasArg(OPT_fgnu89_inline))
1996    Opts.GNUInline = 1;
1997
1998  if (Args.hasArg(OPT_fapple_kext)) {
1999    if (!Opts.CPlusPlus)
2000      Diags.Report(diag::warn_c_kext);
2001    else
2002      Opts.AppleKext = 1;
2003  }
2004
2005  if (Args.hasArg(OPT_print_ivar_layout))
2006    Opts.ObjCGCBitmapPrint = 1;
2007  if (Args.hasArg(OPT_fno_constant_cfstrings))
2008    Opts.NoConstantCFStrings = 1;
2009
2010  if (Args.hasArg(OPT_faltivec))
2011    Opts.AltiVec = 1;
2012
2013  if (Args.hasArg(OPT_pthread))
2014    Opts.POSIXThreads = 1;
2015
2016  if (Args.hasArg(OPT_fdelayed_template_parsing))
2017    Opts.DelayedTemplateParsing = 1;
2018
2019  StringRef Vis = Args.getLastArgValue(OPT_fvisibility, "default");
2020  if (Vis == "default")
2021    Opts.setVisibilityMode(DefaultVisibility);
2022  else if (Vis == "hidden")
2023    Opts.setVisibilityMode(HiddenVisibility);
2024  else if (Vis == "protected")
2025    // FIXME: diagnose if target does not support protected visibility
2026    Opts.setVisibilityMode(ProtectedVisibility);
2027  else
2028    Diags.Report(diag::err_drv_invalid_value)
2029      << Args.getLastArg(OPT_fvisibility)->getAsString(Args) << Vis;
2030
2031  if (Arg *A = Args.getLastArg(OPT_ffp_contract)) {
2032    StringRef Val = A->getValue(Args);
2033    if (Val == "fast")
2034      Opts.setFPContractMode(LangOptions::FPC_Fast);
2035    else if (Val == "on")
2036      Opts.setFPContractMode(LangOptions::FPC_On);
2037    else if (Val == "off")
2038      Opts.setFPContractMode(LangOptions::FPC_Off);
2039    else
2040      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Val;
2041  }
2042
2043  if (Args.hasArg(OPT_fvisibility_inlines_hidden))
2044    Opts.InlineVisibilityHidden = 1;
2045
2046  if (Args.hasArg(OPT_ftrapv)) {
2047    Opts.setSignedOverflowBehavior(LangOptions::SOB_Trapping);
2048    // Set the handler, if one is specified.
2049    Opts.OverflowHandler =
2050        Args.getLastArgValue(OPT_ftrapv_handler);
2051  }
2052  else if (Args.hasArg(OPT_fwrapv))
2053    Opts.setSignedOverflowBehavior(LangOptions::SOB_Defined);
2054
2055  if (Args.hasArg(OPT_trigraphs))
2056    Opts.Trigraphs = 1;
2057
2058  Opts.DollarIdents = Args.hasFlag(OPT_fdollars_in_identifiers,
2059                                   OPT_fno_dollars_in_identifiers,
2060                                   Opts.DollarIdents);
2061  Opts.PascalStrings = Args.hasArg(OPT_fpascal_strings);
2062  Opts.MicrosoftExt
2063    = Args.hasArg(OPT_fms_extensions) || Args.hasArg(OPT_fms_compatibility);
2064  Opts.MicrosoftMode = Args.hasArg(OPT_fms_compatibility);
2065  Opts.MSCVersion = Args.getLastArgIntValue(OPT_fmsc_version, 0, Diags);
2066  Opts.Borland = Args.hasArg(OPT_fborland_extensions);
2067  Opts.WritableStrings = Args.hasArg(OPT_fwritable_strings);
2068  Opts.ConstStrings = Args.hasFlag(OPT_fconst_strings, OPT_fno_const_strings,
2069                                   Opts.ConstStrings);
2070  if (Args.hasArg(OPT_fno_lax_vector_conversions))
2071    Opts.LaxVectorConversions = 0;
2072  if (Args.hasArg(OPT_fno_threadsafe_statics))
2073    Opts.ThreadsafeStatics = 0;
2074  Opts.Exceptions = Args.hasArg(OPT_fexceptions);
2075  Opts.ObjCExceptions = Args.hasArg(OPT_fobjc_exceptions);
2076  Opts.CXXExceptions = Args.hasArg(OPT_fcxx_exceptions);
2077  Opts.SjLjExceptions = Args.hasArg(OPT_fsjlj_exceptions);
2078  Opts.TraditionalCPP = Args.hasArg(OPT_traditional_cpp);
2079
2080  Opts.RTTI = !Args.hasArg(OPT_fno_rtti);
2081  Opts.Blocks = Args.hasArg(OPT_fblocks);
2082  Opts.BlocksRuntimeOptional = Args.hasArg(OPT_fblocks_runtime_optional);
2083  Opts.Modules = Args.hasArg(OPT_fmodules);
2084  Opts.CharIsSigned = !Args.hasArg(OPT_fno_signed_char);
2085  Opts.WChar = Opts.CPlusPlus && !Args.hasArg(OPT_fno_wchar);
2086  Opts.ShortWChar = Args.hasArg(OPT_fshort_wchar);
2087  Opts.ShortEnums = Args.hasArg(OPT_fshort_enums);
2088  Opts.Freestanding = Args.hasArg(OPT_ffreestanding);
2089  Opts.NoBuiltin = Args.hasArg(OPT_fno_builtin) || Opts.Freestanding;
2090  Opts.AssumeSaneOperatorNew = !Args.hasArg(OPT_fno_assume_sane_operator_new);
2091  Opts.HeinousExtensions = Args.hasArg(OPT_fheinous_gnu_extensions);
2092  Opts.AccessControl = !Args.hasArg(OPT_fno_access_control);
2093  Opts.ElideConstructors = !Args.hasArg(OPT_fno_elide_constructors);
2094  Opts.MathErrno = Args.hasArg(OPT_fmath_errno);
2095  Opts.InstantiationDepth = Args.getLastArgIntValue(OPT_ftemplate_depth, 512,
2096                                                    Diags);
2097  Opts.ConstexprCallDepth = Args.getLastArgIntValue(OPT_fconstexpr_depth, 512,
2098                                                    Diags);
2099  Opts.DelayedTemplateParsing = Args.hasArg(OPT_fdelayed_template_parsing);
2100  Opts.NumLargeByValueCopy = Args.getLastArgIntValue(OPT_Wlarge_by_value_copy_EQ,
2101                                                    0, Diags);
2102  Opts.MSBitfields = Args.hasArg(OPT_mms_bitfields);
2103  Opts.ObjCConstantStringClass =
2104    Args.getLastArgValue(OPT_fconstant_string_class);
2105  Opts.ObjCDefaultSynthProperties =
2106    Args.hasArg(OPT_fobjc_default_synthesize_properties);
2107  Opts.CatchUndefined = Args.hasArg(OPT_fcatch_undefined_behavior);
2108  Opts.EmitAllDecls = Args.hasArg(OPT_femit_all_decls);
2109  Opts.PackStruct = Args.getLastArgIntValue(OPT_fpack_struct_EQ, 0, Diags);
2110  Opts.PICLevel = Args.getLastArgIntValue(OPT_pic_level, 0, Diags);
2111  Opts.PIELevel = Args.getLastArgIntValue(OPT_pie_level, 0, Diags);
2112  Opts.Static = Args.hasArg(OPT_static_define);
2113  Opts.DumpRecordLayoutsSimple = Args.hasArg(OPT_fdump_record_layouts_simple);
2114  Opts.DumpRecordLayouts = Opts.DumpRecordLayoutsSimple
2115                        || Args.hasArg(OPT_fdump_record_layouts);
2116  Opts.DumpVTableLayouts = Args.hasArg(OPT_fdump_vtable_layouts);
2117  Opts.SpellChecking = !Args.hasArg(OPT_fno_spell_checking);
2118  Opts.NoBitFieldTypeAlign = Args.hasArg(OPT_fno_bitfield_type_align);
2119  Opts.SinglePrecisionConstants = Args.hasArg(OPT_cl_single_precision_constant);
2120  Opts.FastRelaxedMath = Args.hasArg(OPT_cl_fast_relaxed_math);
2121  Opts.MRTD = Args.hasArg(OPT_mrtd);
2122  Opts.HexagonQdsp6Compat = Args.hasArg(OPT_mqdsp6_compat);
2123  Opts.FakeAddressSpaceMap = Args.hasArg(OPT_ffake_address_space_map);
2124  Opts.ParseUnknownAnytype = Args.hasArg(OPT_funknown_anytype);
2125  Opts.DebuggerSupport = Args.hasArg(OPT_fdebugger_support);
2126  Opts.DebuggerCastResultToId = Args.hasArg(OPT_fdebugger_cast_result_to_id);
2127  Opts.DebuggerObjCLiteral = Args.hasArg(OPT_fdebugger_objc_literal);
2128  Opts.AddressSanitizer = Args.hasArg(OPT_faddress_sanitizer);
2129  Opts.ThreadSanitizer = Args.hasArg(OPT_fthread_sanitizer);
2130  Opts.ApplePragmaPack = Args.hasArg(OPT_fapple_pragma_pack);
2131  Opts.CurrentModule = Args.getLastArgValue(OPT_fmodule_name);
2132
2133  // Record whether the __DEPRECATED define was requested.
2134  Opts.Deprecated = Args.hasFlag(OPT_fdeprecated_macro,
2135                                 OPT_fno_deprecated_macro,
2136                                 Opts.Deprecated);
2137
2138  // FIXME: Eliminate this dependency.
2139  unsigned Opt = getOptimizationLevel(Args, IK, Diags),
2140       OptSize = getOptimizationLevelSize(Args, IK, Diags);
2141  Opts.Optimize = Opt != 0;
2142  Opts.OptimizeSize = OptSize != 0;
2143
2144  // This is the __NO_INLINE__ define, which just depends on things like the
2145  // optimization level and -fno-inline, not actually whether the backend has
2146  // inlining enabled.
2147  Opts.NoInlineDefine = !Opt || Args.hasArg(OPT_fno_inline);
2148
2149  Opts.FastMath = Args.hasArg(OPT_ffast_math);
2150  Opts.FiniteMathOnly = Args.hasArg(OPT_ffinite_math_only);
2151
2152  Opts.EmitMicrosoftInlineAsm = Args.hasArg(OPT_fenable_experimental_ms_inline_asm);
2153
2154  unsigned SSP = Args.getLastArgIntValue(OPT_stack_protector, 0, Diags);
2155  switch (SSP) {
2156  default:
2157    Diags.Report(diag::err_drv_invalid_value)
2158      << Args.getLastArg(OPT_stack_protector)->getAsString(Args) << SSP;
2159    break;
2160  case 0: Opts.setStackProtector(LangOptions::SSPOff); break;
2161  case 1: Opts.setStackProtector(LangOptions::SSPOn);  break;
2162  case 2: Opts.setStackProtector(LangOptions::SSPReq); break;
2163  }
2164}
2165
2166static void ParsePreprocessorArgs(PreprocessorOptions &Opts, ArgList &Args,
2167                                  FileManager &FileMgr,
2168                                  DiagnosticsEngine &Diags) {
2169  using namespace options;
2170  Opts.ImplicitPCHInclude = Args.getLastArgValue(OPT_include_pch);
2171  Opts.ImplicitPTHInclude = Args.getLastArgValue(OPT_include_pth);
2172  if (const Arg *A = Args.getLastArg(OPT_token_cache))
2173      Opts.TokenCache = A->getValue(Args);
2174  else
2175    Opts.TokenCache = Opts.ImplicitPTHInclude;
2176  Opts.UsePredefines = !Args.hasArg(OPT_undef);
2177  Opts.DetailedRecord = Args.hasArg(OPT_detailed_preprocessing_record);
2178  Opts.DisablePCHValidation = Args.hasArg(OPT_fno_validate_pch);
2179
2180  Opts.DumpDeserializedPCHDecls = Args.hasArg(OPT_dump_deserialized_pch_decls);
2181  for (arg_iterator it = Args.filtered_begin(OPT_error_on_deserialized_pch_decl),
2182         ie = Args.filtered_end(); it != ie; ++it) {
2183    const Arg *A = *it;
2184    Opts.DeserializedPCHDeclsToErrorOn.insert(A->getValue(Args));
2185  }
2186
2187  if (const Arg *A = Args.getLastArg(OPT_preamble_bytes_EQ)) {
2188    StringRef Value(A->getValue(Args));
2189    size_t Comma = Value.find(',');
2190    unsigned Bytes = 0;
2191    unsigned EndOfLine = 0;
2192
2193    if (Comma == StringRef::npos ||
2194        Value.substr(0, Comma).getAsInteger(10, Bytes) ||
2195        Value.substr(Comma + 1).getAsInteger(10, EndOfLine))
2196      Diags.Report(diag::err_drv_preamble_format);
2197    else {
2198      Opts.PrecompiledPreambleBytes.first = Bytes;
2199      Opts.PrecompiledPreambleBytes.second = (EndOfLine != 0);
2200    }
2201  }
2202
2203  // Add macros from the command line.
2204  for (arg_iterator it = Args.filtered_begin(OPT_D, OPT_U),
2205         ie = Args.filtered_end(); it != ie; ++it) {
2206    if ((*it)->getOption().matches(OPT_D))
2207      Opts.addMacroDef((*it)->getValue(Args));
2208    else
2209      Opts.addMacroUndef((*it)->getValue(Args));
2210  }
2211
2212  Opts.MacroIncludes = Args.getAllArgValues(OPT_imacros);
2213
2214  // Add the ordered list of -includes.
2215  for (arg_iterator it = Args.filtered_begin(OPT_include, OPT_include_pch,
2216                                             OPT_include_pth),
2217         ie = Args.filtered_end(); it != ie; ++it) {
2218    const Arg *A = *it;
2219    // PCH is handled specially, we need to extra the original include path.
2220    if (A->getOption().matches(OPT_include_pch)) {
2221      std::string OriginalFile =
2222        ASTReader::getOriginalSourceFile(A->getValue(Args), FileMgr, Diags);
2223      if (OriginalFile.empty())
2224        continue;
2225
2226      Opts.Includes.push_back(OriginalFile);
2227    } else
2228      Opts.Includes.push_back(A->getValue(Args));
2229  }
2230
2231  for (arg_iterator it = Args.filtered_begin(OPT_chain_include),
2232         ie = Args.filtered_end(); it != ie; ++it) {
2233    const Arg *A = *it;
2234    Opts.ChainedIncludes.push_back(A->getValue(Args));
2235  }
2236
2237  // Include 'altivec.h' if -faltivec option present
2238  if (Args.hasArg(OPT_faltivec))
2239    Opts.Includes.push_back("altivec.h");
2240
2241  for (arg_iterator it = Args.filtered_begin(OPT_remap_file),
2242         ie = Args.filtered_end(); it != ie; ++it) {
2243    const Arg *A = *it;
2244    std::pair<StringRef,StringRef> Split =
2245      StringRef(A->getValue(Args)).split(';');
2246
2247    if (Split.second.empty()) {
2248      Diags.Report(diag::err_drv_invalid_remap_file) << A->getAsString(Args);
2249      continue;
2250    }
2251
2252    Opts.addRemappedFile(Split.first, Split.second);
2253  }
2254
2255  if (Arg *A = Args.getLastArg(OPT_fobjc_arc_cxxlib_EQ)) {
2256    StringRef Name = A->getValue(Args);
2257    unsigned Library = llvm::StringSwitch<unsigned>(Name)
2258      .Case("libc++", ARCXX_libcxx)
2259      .Case("libstdc++", ARCXX_libstdcxx)
2260      .Case("none", ARCXX_nolib)
2261      .Default(~0U);
2262    if (Library == ~0U)
2263      Diags.Report(diag::err_drv_invalid_value) << A->getAsString(Args) << Name;
2264    else
2265      Opts.ObjCXXARCStandardLibrary = (ObjCXXARCStandardLibraryKind)Library;
2266  }
2267}
2268
2269static void ParsePreprocessorOutputArgs(PreprocessorOutputOptions &Opts,
2270                                        ArgList &Args) {
2271  using namespace options;
2272  Opts.ShowCPP = !Args.hasArg(OPT_dM);
2273  Opts.ShowComments = Args.hasArg(OPT_C);
2274  Opts.ShowLineMarkers = !Args.hasArg(OPT_P);
2275  Opts.ShowMacroComments = Args.hasArg(OPT_CC);
2276  Opts.ShowMacros = Args.hasArg(OPT_dM) || Args.hasArg(OPT_dD);
2277  Opts.RewriteIncludes = Args.hasArg(OPT_frewrite_includes);
2278}
2279
2280static void ParseTargetArgs(TargetOptions &Opts, ArgList &Args) {
2281  using namespace options;
2282  Opts.ABI = Args.getLastArgValue(OPT_target_abi);
2283  Opts.CXXABI = Args.getLastArgValue(OPT_cxx_abi);
2284  Opts.CPU = Args.getLastArgValue(OPT_target_cpu);
2285  Opts.Features = Args.getAllArgValues(OPT_target_feature);
2286  Opts.LinkerVersion = Args.getLastArgValue(OPT_target_linker_version);
2287  Opts.Triple = llvm::Triple::normalize(Args.getLastArgValue(OPT_triple));
2288
2289  // Use the default target triple if unspecified.
2290  if (Opts.Triple.empty())
2291    Opts.Triple = llvm::sys::getDefaultTargetTriple();
2292}
2293
2294//
2295
2296bool CompilerInvocation::CreateFromArgs(CompilerInvocation &Res,
2297                                        const char *const *ArgBegin,
2298                                        const char *const *ArgEnd,
2299                                        DiagnosticsEngine &Diags) {
2300  bool Success = true;
2301
2302  // Parse the arguments.
2303  OwningPtr<OptTable> Opts(createDriverOptTable());
2304  unsigned MissingArgIndex, MissingArgCount;
2305  OwningPtr<InputArgList> Args(
2306    Opts->ParseArgs(ArgBegin, ArgEnd,MissingArgIndex, MissingArgCount));
2307
2308  // Check for missing argument error.
2309  if (MissingArgCount) {
2310    Diags.Report(diag::err_drv_missing_argument)
2311      << Args->getArgString(MissingArgIndex) << MissingArgCount;
2312    Success = false;
2313  }
2314
2315  // Issue errors on unknown arguments.
2316  for (arg_iterator it = Args->filtered_begin(OPT_UNKNOWN),
2317         ie = Args->filtered_end(); it != ie; ++it) {
2318    Diags.Report(diag::err_drv_unknown_argument) << (*it)->getAsString(*Args);
2319    Success = false;
2320  }
2321
2322  // Issue errors on arguments that are not valid for CC1.
2323  for (ArgList::iterator I = Args->begin(), E = Args->end();
2324       I != E; ++I) {
2325    if (!(*I)->getOption().isCC1Option()) {
2326      Diags.Report(diag::err_drv_unknown_argument) << (*I)->getAsString(*Args);
2327      Success = false;
2328    }
2329  }
2330
2331  Success = ParseAnalyzerArgs(*Res.getAnalyzerOpts(), *Args, Diags) && Success;
2332  Success = ParseMigratorArgs(Res.getMigratorOpts(), *Args) && Success;
2333  ParseDependencyOutputArgs(Res.getDependencyOutputOpts(), *Args);
2334  Success = ParseDiagnosticArgs(Res.getDiagnosticOpts(), *Args, &Diags)
2335            && Success;
2336  ParseFileSystemArgs(Res.getFileSystemOpts(), *Args);
2337  // FIXME: We shouldn't have to pass the DashX option around here
2338  InputKind DashX = ParseFrontendArgs(Res.getFrontendOpts(), *Args, Diags);
2339  Success = ParseCodeGenArgs(Res.getCodeGenOpts(), *Args, DashX, Diags)
2340            && Success;
2341  ParseHeaderSearchArgs(Res.getHeaderSearchOpts(), *Args);
2342  if (DashX != IK_AST && DashX != IK_LLVM_IR) {
2343    ParseLangArgs(*Res.getLangOpts(), *Args, DashX, Diags);
2344    if (Res.getFrontendOpts().ProgramAction == frontend::RewriteObjC)
2345      Res.getLangOpts()->ObjCExceptions = 1;
2346  }
2347  // FIXME: ParsePreprocessorArgs uses the FileManager to read the contents of
2348  // PCH file and find the original header name. Remove the need to do that in
2349  // ParsePreprocessorArgs and remove the FileManager
2350  // parameters from the function and the "FileManager.h" #include.
2351  FileManager FileMgr(Res.getFileSystemOpts());
2352  ParsePreprocessorArgs(Res.getPreprocessorOpts(), *Args, FileMgr, Diags);
2353  ParsePreprocessorOutputArgs(Res.getPreprocessorOutputOpts(), *Args);
2354  ParseTargetArgs(Res.getTargetOpts(), *Args);
2355
2356  return Success;
2357}
2358
2359namespace {
2360
2361  class ModuleSignature {
2362    llvm::SmallVector<uint64_t, 16> Data;
2363    unsigned CurBit;
2364    uint64_t CurValue;
2365
2366  public:
2367    ModuleSignature() : CurBit(0), CurValue(0) { }
2368
2369    void add(uint64_t Value, unsigned Bits);
2370    void add(StringRef Value);
2371    void flush();
2372
2373    llvm::APInt getAsInteger() const;
2374  };
2375}
2376
2377void ModuleSignature::add(uint64_t Value, unsigned int NumBits) {
2378  CurValue |= Value << CurBit;
2379  if (CurBit + NumBits < 64) {
2380    CurBit += NumBits;
2381    return;
2382  }
2383
2384  // Add the current word.
2385  Data.push_back(CurValue);
2386
2387  if (CurBit)
2388    CurValue = Value >> (64-CurBit);
2389  else
2390    CurValue = 0;
2391  CurBit = (CurBit+NumBits) & 63;
2392}
2393
2394void ModuleSignature::flush() {
2395  if (CurBit == 0)
2396    return;
2397
2398  Data.push_back(CurValue);
2399  CurBit = 0;
2400  CurValue = 0;
2401}
2402
2403void ModuleSignature::add(StringRef Value) {
2404  for (StringRef::iterator I = Value.begin(), IEnd = Value.end(); I != IEnd;++I)
2405    add(*I, 8);
2406}
2407
2408llvm::APInt ModuleSignature::getAsInteger() const {
2409  return llvm::APInt(Data.size() * 64, Data);
2410}
2411
2412std::string CompilerInvocation::getModuleHash() const {
2413  ModuleSignature Signature;
2414
2415  // Start the signature with the compiler version.
2416  // FIXME: The full version string can be quite long.  Omit it from the
2417  // module hash for now to avoid failures where the path name becomes too
2418  // long.  An MD5 or similar checksum would work well here.
2419  // Signature.add(getClangFullRepositoryVersion());
2420
2421  // Extend the signature with the language options
2422#define LANGOPT(Name, Bits, Default, Description) \
2423  Signature.add(LangOpts->Name, Bits);
2424#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
2425  Signature.add(static_cast<unsigned>(LangOpts->get##Name()), Bits);
2426#define BENIGN_LANGOPT(Name, Bits, Default, Description)
2427#define BENIGN_ENUM_LANGOPT(Name, Type, Bits, Default, Description)
2428#include "clang/Basic/LangOptions.def"
2429
2430  // Extend the signature with the target triple
2431  llvm::Triple T(TargetOpts.Triple);
2432  Signature.add((unsigned)T.getArch(), 5);
2433  Signature.add((unsigned)T.getVendor(), 4);
2434  Signature.add((unsigned)T.getOS(), 5);
2435  Signature.add((unsigned)T.getEnvironment(), 4);
2436
2437  // Extend the signature with preprocessor options.
2438  Signature.add(getPreprocessorOpts().UsePredefines, 1);
2439  Signature.add(getPreprocessorOpts().DetailedRecord, 1);
2440
2441  // Hash the preprocessor defines.
2442  // FIXME: This is terrible. Use an MD5 sum of the preprocessor defines.
2443  std::vector<StringRef> MacroDefs;
2444  for (std::vector<std::pair<std::string, bool/*isUndef*/> >::const_iterator
2445            I = getPreprocessorOpts().Macros.begin(),
2446         IEnd = getPreprocessorOpts().Macros.end();
2447       I != IEnd; ++I) {
2448    if (!I->second)
2449      MacroDefs.push_back(I->first);
2450  }
2451  llvm::array_pod_sort(MacroDefs.begin(), MacroDefs.end());
2452
2453  unsigned PPHashResult = 0;
2454  for (unsigned I = 0, N = MacroDefs.size(); I != N; ++I)
2455    PPHashResult = llvm::HashString(MacroDefs[I], PPHashResult);
2456  Signature.add(PPHashResult, 32);
2457
2458  // We've generated the signature. Treat it as one large APInt that we'll
2459  // encode in base-36 and return.
2460  Signature.flush();
2461  return Signature.getAsInteger().toString(36, /*Signed=*/false);
2462}
2463