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