Clang Project

clang_source_code/lib/Driver/ToolChains/Clang.cpp
1//===-- Clang.cpp - Clang+LLVM ToolChain Implementations --------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "Clang.h"
10#include "Arch/AArch64.h"
11#include "Arch/ARM.h"
12#include "Arch/Mips.h"
13#include "Arch/PPC.h"
14#include "Arch/RISCV.h"
15#include "Arch/Sparc.h"
16#include "Arch/SystemZ.h"
17#include "Arch/X86.h"
18#include "AMDGPU.h"
19#include "CommonArgs.h"
20#include "Hexagon.h"
21#include "MSP430.h"
22#include "InputInfo.h"
23#include "PS4CPU.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/LangOptions.h"
26#include "clang/Basic/ObjCRuntime.h"
27#include "clang/Basic/Version.h"
28#include "clang/Driver/Distro.h"
29#include "clang/Driver/DriverDiagnostic.h"
30#include "clang/Driver/Options.h"
31#include "clang/Driver/SanitizerArgs.h"
32#include "clang/Driver/XRayArgs.h"
33#include "llvm/ADT/StringExtras.h"
34#include "llvm/Config/llvm-config.h"
35#include "llvm/Option/ArgList.h"
36#include "llvm/Support/CodeGen.h"
37#include "llvm/Support/Compression.h"
38#include "llvm/Support/FileSystem.h"
39#include "llvm/Support/Path.h"
40#include "llvm/Support/Process.h"
41#include "llvm/Support/TargetParser.h"
42#include "llvm/Support/YAMLParser.h"
43
44#ifdef LLVM_ON_UNIX
45#include <unistd.h> // For getuid().
46#endif
47
48using namespace clang::driver;
49using namespace clang::driver::tools;
50using namespace clang;
51using namespace llvm::opt;
52
53static void CheckPreprocessingOptions(const Driver &Dconst ArgList &Args) {
54  if (Arg *A =
55          Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
56    if (!Args.hasArg(options::OPT_E) && !Args.hasArg(options::OPT__SLASH_P) &&
57        !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
58      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
59          << A->getBaseArg().getAsString(Args)
60          << (D.IsCLMode() ? "/E, /P or /EP" : "-E");
61    }
62  }
63}
64
65static void CheckCodeGenerationOptions(const Driver &Dconst ArgList &Args) {
66  // In gcc, only ARM checks this, but it seems reasonable to check universally.
67  if (Args.hasArg(options::OPT_static))
68    if (const Arg *A =
69            Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
70      D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
71                                                      << "-static";
72}
73
74// Add backslashes to escape spaces and other backslashes.
75// This is used for the space-separated argument list specified with
76// the -dwarf-debug-flags option.
77static void EscapeSpacesAndBackslashes(const char *Arg,
78                                       SmallVectorImpl<char> &Res) {
79  for (; *Arg; ++Arg) {
80    switch (*Arg) {
81    default:
82      break;
83    case ' ':
84    case '\\':
85      Res.push_back('\\');
86      break;
87    }
88    Res.push_back(*Arg);
89  }
90}
91
92// Quote target names for inclusion in GNU Make dependency files.
93// Only the characters '$', '#', ' ', '\t' are quoted.
94static void QuoteTarget(StringRef TargetSmallVectorImpl<char> &Res) {
95  for (unsigned i = 0e = Target.size(); i != e; ++i) {
96    switch (Target[i]) {
97    case ' ':
98    case '\t':
99      // Escape the preceding backslashes
100      for (int j = i - 1; j >= 0 && Target[j] == '\\'; --j)
101        Res.push_back('\\');
102
103      // Escape the space/tab
104      Res.push_back('\\');
105      break;
106    case '$':
107      Res.push_back('$');
108      break;
109    case '#':
110      Res.push_back('\\');
111      break;
112    default:
113      break;
114    }
115
116    Res.push_back(Target[i]);
117  }
118}
119
120/// Apply \a Work on the current tool chain \a RegularToolChain and any other
121/// offloading tool chain that is associated with the current action \a JA.
122static void
123forAllAssociatedToolChains(Compilation &Cconst JobAction &JA,
124                           const ToolChain &RegularToolChain,
125                           llvm::function_ref<void(const ToolChain &)> Work) {
126  // Apply Work on the current/regular tool chain.
127  Work(RegularToolChain);
128
129  // Apply Work on all the offloading tool chains associated with the current
130  // action.
131  if (JA.isHostOffloading(Action::OFK_Cuda))
132    Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
133  else if (JA.isDeviceOffloading(Action::OFK_Cuda))
134    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
135  else if (JA.isHostOffloading(Action::OFK_HIP))
136    Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
137  else if (JA.isDeviceOffloading(Action::OFK_HIP))
138    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
139
140  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
141    auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
142    for (auto II = TCs.first, IE = TCs.second; II != IE; ++II)
143      Work(*II->second);
144  } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
145    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
146
147  //
148  // TODO: Add support for other offloading programming models here.
149  //
150}
151
152/// This is a helper function for validating the optional refinement step
153/// parameter in reciprocal argument strings. Return false if there is an error
154/// parsing the refinement step. Otherwise, return true and set the Position
155/// of the refinement step in the input string.
156static bool getRefinementStep(StringRef Inconst Driver &D,
157                              const Arg &A, size_t &Position) {
158  const char RefinementStepToken = ':';
159  Position = In.find(RefinementStepToken);
160  if (Position != StringRef::npos) {
161    StringRef Option = A.getOption().getName();
162    StringRef RefStep = In.substr(Position + 1);
163    // Allow exactly one numeric character for the additional refinement
164    // step parameter. This is reasonable for all currently-supported
165    // operations and architectures because we would expect that a larger value
166    // of refinement steps would cause the estimate "optimization" to
167    // under-perform the native operation. Also, if the estimate does not
168    // converge quickly, it probably will not ever converge, so further
169    // refinement steps will not produce a better answer.
170    if (RefStep.size() != 1) {
171      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
172      return false;
173    }
174    char RefStepChar = RefStep[0];
175    if (RefStepChar < '0' || RefStepChar > '9') {
176      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
177      return false;
178    }
179  }
180  return true;
181}
182
183/// The -mrecip flag requires processing of many optional parameters.
184static void ParseMRecip(const Driver &Dconst ArgList &Args,
185                        ArgStringList &OutStrings) {
186  StringRef DisabledPrefixIn = "!";
187  StringRef DisabledPrefixOut = "!";
188  StringRef EnabledPrefixOut = "";
189  StringRef Out = "-mrecip=";
190
191  Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
192  if (!A)
193    return;
194
195  unsigned NumOptions = A->getNumValues();
196  if (NumOptions == 0) {
197    // No option is the same as "all".
198    OutStrings.push_back(Args.MakeArgString(Out + "all"));
199    return;
200  }
201
202  // Pass through "all", "none", or "default" with an optional refinement step.
203  if (NumOptions == 1) {
204    StringRef Val = A->getValue(0);
205    size_t RefStepLoc;
206    if (!getRefinementStep(Val, D, *A, RefStepLoc))
207      return;
208    StringRef ValBase = Val.slice(0, RefStepLoc);
209    if (ValBase == "all" || ValBase == "none" || ValBase == "default") {
210      OutStrings.push_back(Args.MakeArgString(Out + Val));
211      return;
212    }
213  }
214
215  // Each reciprocal type may be enabled or disabled individually.
216  // Check each input value for validity, concatenate them all back together,
217  // and pass through.
218
219  llvm::StringMap<bool> OptionStrings;
220  OptionStrings.insert(std::make_pair("divd"false));
221  OptionStrings.insert(std::make_pair("divf"false));
222  OptionStrings.insert(std::make_pair("vec-divd"false));
223  OptionStrings.insert(std::make_pair("vec-divf"false));
224  OptionStrings.insert(std::make_pair("sqrtd"false));
225  OptionStrings.insert(std::make_pair("sqrtf"false));
226  OptionStrings.insert(std::make_pair("vec-sqrtd"false));
227  OptionStrings.insert(std::make_pair("vec-sqrtf"false));
228
229  for (unsigned i = 0i != NumOptions; ++i) {
230    StringRef Val = A->getValue(i);
231
232    bool IsDisabled = Val.startswith(DisabledPrefixIn);
233    // Ignore the disablement token for string matching.
234    if (IsDisabled)
235      Val = Val.substr(1);
236
237    size_t RefStep;
238    if (!getRefinementStep(Val, D, *A, RefStep))
239      return;
240
241    StringRef ValBase = Val.slice(0, RefStep);
242    llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
243    if (OptionIter == OptionStrings.end()) {
244      // Try again specifying float suffix.
245      OptionIter = OptionStrings.find(ValBase.str() + 'f');
246      if (OptionIter == OptionStrings.end()) {
247        // The input name did not match any known option string.
248        D.Diag(diag::err_drv_unknown_argument) << Val;
249        return;
250      }
251      // The option was specified without a float or double suffix.
252      // Make sure that the double entry was not already specified.
253      // The float entry will be checked below.
254      if (OptionStrings[ValBase.str() + 'd']) {
255        D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
256        return;
257      }
258    }
259
260    if (OptionIter->second == true) {
261      // Duplicate option specified.
262      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
263      return;
264    }
265
266    // Mark the matched option as found. Do not allow duplicate specifiers.
267    OptionIter->second = true;
268
269    // If the precision was not specified, also mark the double entry as found.
270    if (ValBase.back() != 'f' && ValBase.back() != 'd')
271      OptionStrings[ValBase.str() + 'd'] = true;
272
273    // Build the output string.
274    StringRef Prefix = IsDisabled ? DisabledPrefixOut : EnabledPrefixOut;
275    Out = Args.MakeArgString(Out + Prefix + Val);
276    if (i != NumOptions - 1)
277      Out = Args.MakeArgString(Out + ",");
278  }
279
280  OutStrings.push_back(Args.MakeArgString(Out));
281}
282
283/// The -mprefer-vector-width option accepts either a positive integer
284/// or the string "none".
285static void ParseMPreferVectorWidth(const Driver &Dconst ArgList &Args,
286                                    ArgStringList &CmdArgs) {
287  Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
288  if (!A)
289    return;
290
291  StringRef Value = A->getValue();
292  if (Value == "none") {
293    CmdArgs.push_back("-mprefer-vector-width=none");
294  } else {
295    unsigned Width;
296    if (Value.getAsInteger(10, Width)) {
297      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
298      return;
299    }
300    CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
301  }
302}
303
304static void getWebAssemblyTargetFeatures(const ArgList &Args,
305                                         std::vector<StringRef> &Features) {
306  handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
307}
308
309static void getTargetFeatures(const ToolChain &TCconst llvm::Triple &Triple,
310                              const ArgList &Args, ArgStringList &CmdArgs,
311                              bool ForAS) {
312  const Driver &D = TC.getDriver();
313  std::vector<StringRefFeatures;
314  switch (Triple.getArch()) {
315  default:
316    break;
317  case llvm::Triple::mips:
318  case llvm::Triple::mipsel:
319  case llvm::Triple::mips64:
320  case llvm::Triple::mips64el:
321    mips::getMIPSTargetFeatures(D, Triple, Args, Features);
322    break;
323
324  case llvm::Triple::arm:
325  case llvm::Triple::armeb:
326  case llvm::Triple::thumb:
327  case llvm::Triple::thumbeb:
328    arm::getARMTargetFeatures(TC, Triple, Args, CmdArgs, Features, ForAS);
329    break;
330
331  case llvm::Triple::ppc:
332  case llvm::Triple::ppc64:
333  case llvm::Triple::ppc64le:
334    ppc::getPPCTargetFeatures(D, Triple, Args, Features);
335    break;
336  case llvm::Triple::riscv32:
337  case llvm::Triple::riscv64:
338    riscv::getRISCVTargetFeatures(D, Args, Features);
339    break;
340  case llvm::Triple::systemz:
341    systemz::getSystemZTargetFeatures(Args, Features);
342    break;
343  case llvm::Triple::aarch64:
344  case llvm::Triple::aarch64_be:
345    aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
346    break;
347  case llvm::Triple::x86:
348  case llvm::Triple::x86_64:
349    x86::getX86TargetFeatures(D, Triple, Args, Features);
350    break;
351  case llvm::Triple::hexagon:
352    hexagon::getHexagonTargetFeatures(D, Args, Features);
353    break;
354  case llvm::Triple::wasm32:
355  case llvm::Triple::wasm64:
356    getWebAssemblyTargetFeatures(Args, Features);
357    break;
358  case llvm::Triple::sparc:
359  case llvm::Triple::sparcel:
360  case llvm::Triple::sparcv9:
361    sparc::getSparcTargetFeatures(D, Args, Features);
362    break;
363  case llvm::Triple::r600:
364  case llvm::Triple::amdgcn:
365    amdgpu::getAMDGPUTargetFeatures(D, Args, Features);
366    break;
367  case llvm::Triple::msp430:
368    msp430::getMSP430TargetFeatures(D, Args, Features);
369  }
370
371  // Find the last of each feature.
372  llvm::StringMap<unsigned> LastOpt;
373  for (unsigned I = 0N = Features.size(); I < N; ++I) {
374    StringRef Name = Features[I];
375    assert(Name[0] == '-' || Name[0] == '+');
376    LastOpt[Name.drop_front(1)] = I;
377  }
378
379  for (unsigned I = 0N = Features.size(); I < N; ++I) {
380    // If this feature was overridden, ignore it.
381    StringRef Name = Features[I];
382    llvm::StringMap<unsigned>::iterator LastI = LastOpt.find(Name.drop_front(1));
383    assert(LastI != LastOpt.end());
384    unsigned Last = LastI->second;
385    if (Last != I)
386      continue;
387
388    CmdArgs.push_back("-target-feature");
389    CmdArgs.push_back(Name.data());
390  }
391}
392
393static bool
394shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
395                                          const llvm::Triple &Triple) {
396  // We use the zero-cost exception tables for Objective-C if the non-fragile
397  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
398  // later.
399  if (runtime.isNonFragile())
400    return true;
401
402  if (!Triple.isMacOSX())
403    return false;
404
405  return (!Triple.isMacOSXVersionLT(105) &&
406          (Triple.getArch() == llvm::Triple::x86_64 ||
407           Triple.getArch() == llvm::Triple::arm));
408}
409
410/// Adds exception related arguments to the driver command arguments. There's a
411/// master flag, -fexceptions and also language specific flags to enable/disable
412/// C++ and Objective-C exceptions. This makes it possible to for example
413/// disable C++ exceptions but enable Objective-C exceptions.
414static void addExceptionArgs(const ArgList &Argstypes::ID InputType,
415                             const ToolChain &TCbool KernelOrKext,
416                             const ObjCRuntime &objcRuntime,
417                             ArgStringList &CmdArgs) {
418  const llvm::Triple &Triple = TC.getTriple();
419
420  if (KernelOrKext) {
421    // -mkernel and -fapple-kext imply no exceptions, so claim exception related
422    // arguments now to avoid warnings about unused arguments.
423    Args.ClaimAllArgs(options::OPT_fexceptions);
424    Args.ClaimAllArgs(options::OPT_fno_exceptions);
425    Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
426    Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
427    Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
428    Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
429    return;
430  }
431
432  // See if the user explicitly enabled exceptions.
433  bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
434                         false);
435
436  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
437  // is not necessarily sensible, but follows GCC.
438  if (types::isObjC(InputType) &&
439      Args.hasFlag(options::OPT_fobjc_exceptions,
440                   options::OPT_fno_objc_exceptions, true)) {
441    CmdArgs.push_back("-fobjc-exceptions");
442
443    EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntimeTriple);
444  }
445
446  if (types::isCXX(InputType)) {
447    // Disable C++ EH by default on XCore and PS4.
448    bool CXXExceptionsEnabled =
449        Triple.getArch() != llvm::Triple::xcore && !Triple.isPS4CPU();
450    Arg *ExceptionArg = Args.getLastArg(
451        options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
452        options::OPT_fexceptions, options::OPT_fno_exceptions);
453    if (ExceptionArg)
454      CXXExceptionsEnabled =
455          ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
456          ExceptionArg->getOption().matches(options::OPT_fexceptions);
457
458    if (CXXExceptionsEnabled) {
459      CmdArgs.push_back("-fcxx-exceptions");
460
461      EH = true;
462    }
463  }
464
465  if (EH)
466    CmdArgs.push_back("-fexceptions");
467}
468
469static bool ShouldDisableAutolink(const ArgList &Argsconst ToolChain &TC) {
470  bool Default = true;
471  if (TC.getTriple().isOSDarwin()) {
472    // The native darwin assembler doesn't support the linker_option directives,
473    // so we disable them if we think the .s file will be passed to it.
474    Default = TC.useIntegratedAs();
475  }
476  return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
477                       Default);
478}
479
480static bool ShouldDisableDwarfDirectory(const ArgList &Args,
481                                        const ToolChain &TC) {
482  bool UseDwarfDirectory =
483      Args.hasFlag(options::OPT_fdwarf_directory_asm,
484                   options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
485  return !UseDwarfDirectory;
486}
487
488// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
489// to the corresponding DebugInfoKind.
490static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
491   (0) . __assert_fail ("A.getOption().matches(options..OPT_gN_Group) && \"Not a -g option that specifies a debug-info level\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 492, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(A.getOption().matches(options::OPT_gN_Group) &&
492 (0) . __assert_fail ("A.getOption().matches(options..OPT_gN_Group) && \"Not a -g option that specifies a debug-info level\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 492, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">         "Not a -g option that specifies a debug-info level");
493  if (A.getOption().matches(options::OPT_g0) ||
494      A.getOption().matches(options::OPT_ggdb0))
495    return codegenoptions::NoDebugInfo;
496  if (A.getOption().matches(options::OPT_gline_tables_only) ||
497      A.getOption().matches(options::OPT_ggdb1))
498    return codegenoptions::DebugLineTablesOnly;
499  if (A.getOption().matches(options::OPT_gline_directives_only))
500    return codegenoptions::DebugDirectivesOnly;
501  return codegenoptions::LimitedDebugInfo;
502}
503
504static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
505  switch (Triple.getArch()){
506  default:
507    return false;
508  case llvm::Triple::arm:
509  case llvm::Triple::thumb:
510    // ARM Darwin targets require a frame pointer to be always present to aid
511    // offline debugging via backtraces.
512    return Triple.isOSDarwin();
513  }
514}
515
516static bool useFramePointerForTargetByDefault(const ArgList &Args,
517                                              const llvm::Triple &Triple) {
518  switch (Triple.getArch()) {
519  case llvm::Triple::xcore:
520  case llvm::Triple::wasm32:
521  case llvm::Triple::wasm64:
522  case llvm::Triple::msp430:
523    // XCore never wants frame pointers, regardless of OS.
524    // WebAssembly never wants frame pointers.
525    return false;
526  case llvm::Triple::riscv32:
527  case llvm::Triple::riscv64:
528    return !areOptimizationsEnabled(Args);
529  default:
530    break;
531  }
532
533  if (Triple.isOSNetBSD()) {
534    return !areOptimizationsEnabled(Args);
535  }
536
537  if (Triple.isOSLinux() || Triple.getOS() == llvm::Triple::CloudABI ||
538      Triple.isOSHurd()) {
539    switch (Triple.getArch()) {
540    // Don't use a frame pointer on linux if optimizing for certain targets.
541    case llvm::Triple::mips64:
542    case llvm::Triple::mips64el:
543    case llvm::Triple::mips:
544    case llvm::Triple::mipsel:
545    case llvm::Triple::ppc:
546    case llvm::Triple::ppc64:
547    case llvm::Triple::ppc64le:
548    case llvm::Triple::systemz:
549    case llvm::Triple::x86:
550    case llvm::Triple::x86_64:
551      return !areOptimizationsEnabled(Args);
552    default:
553      return true;
554    }
555  }
556
557  if (Triple.isOSWindows()) {
558    switch (Triple.getArch()) {
559    case llvm::Triple::x86:
560      return !areOptimizationsEnabled(Args);
561    case llvm::Triple::x86_64:
562      return Triple.isOSBinFormatMachO();
563    case llvm::Triple::arm:
564    case llvm::Triple::thumb:
565      // Windows on ARM builds with FPO disabled to aid fast stack walking
566      return true;
567    default:
568      // All other supported Windows ISAs use xdata unwind information, so frame
569      // pointers are not generally useful.
570      return false;
571    }
572  }
573
574  return true;
575}
576
577static bool shouldUseFramePointer(const ArgList &Args,
578                                  const llvm::Triple &Triple) {
579  if (Arg *A = Args.getLastArg(options::OPT_fno_omit_frame_pointer,
580                               options::OPT_fomit_frame_pointer))
581    return A->getOption().matches(options::OPT_fno_omit_frame_pointer) ||
582           mustUseNonLeafFramePointerForTarget(Triple);
583
584  if (Args.hasArg(options::OPT_pg))
585    return true;
586
587  return useFramePointerForTargetByDefault(ArgsTriple);
588}
589
590static bool shouldUseLeafFramePointer(const ArgList &Args,
591                                      const llvm::Triple &Triple) {
592  if (Arg *A = Args.getLastArg(options::OPT_mno_omit_leaf_frame_pointer,
593                               options::OPT_momit_leaf_frame_pointer))
594    return A->getOption().matches(options::OPT_mno_omit_leaf_frame_pointer);
595
596  if (Args.hasArg(options::OPT_pg))
597    return true;
598
599  if (Triple.isPS4CPU())
600    return false;
601
602  return useFramePointerForTargetByDefault(ArgsTriple);
603}
604
605/// Add a CC1 option to specify the debug compilation directory.
606static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
607  SmallString<128cwd;
608  if (!llvm::sys::fs::current_path(cwd)) {
609    CmdArgs.push_back("-fdebug-compilation-dir");
610    CmdArgs.push_back(Args.MakeArgString(cwd));
611  }
612}
613
614/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
615static void addDebugPrefixMapArg(const Driver &Dconst ArgList &Args, ArgStringList &CmdArgs) {
616  for (const Arg *A : Args.filtered(options::OPT_fdebug_prefix_map_EQ)) {
617    StringRef Map = A->getValue();
618    if (Map.find('=') == StringRef::npos)
619      D.Diag(diag::err_drv_invalid_argument_to_fdebug_prefix_map) << Map;
620    else
621      CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
622    A->claim();
623  }
624}
625
626/// Vectorize at all optimization levels greater than 1 except for -Oz.
627/// For -Oz the loop vectorizer is disable, while the slp vectorizer is enabled.
628static bool shouldEnableVectorizerAtOLevel(const ArgList &Argsbool isSlpVec) {
629  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
630    if (A->getOption().matches(options::OPT_O4) ||
631        A->getOption().matches(options::OPT_Ofast))
632      return true;
633
634    if (A->getOption().matches(options::OPT_O0))
635      return false;
636
637     (0) . __assert_fail ("A->getOption().matches(options..OPT_O) && \"Must have a -O flag\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 637, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
638
639    // Vectorize -Os.
640    StringRef S(A->getValue());
641    if (S == "s")
642      return true;
643
644    // Don't vectorize -Oz, unless it's the slp vectorizer.
645    if (S == "z")
646      return isSlpVec;
647
648    unsigned OptLevel = 0;
649    if (S.getAsInteger(10, OptLevel))
650      return false;
651
652    return OptLevel > 1;
653  }
654
655  return false;
656}
657
658/// Add -x lang to \p CmdArgs for \p Input.
659static void addDashXForInput(const ArgList &Argsconst InputInfo &Input,
660                             ArgStringList &CmdArgs) {
661  // When using -verify-pch, we don't want to provide the type
662  // 'precompiled-header' if it was inferred from the file extension
663  if (Args.hasArg(options::OPT_verify_pch) && Input.getType() == types::TY_PCH)
664    return;
665
666  CmdArgs.push_back("-x");
667  if (Args.hasArg(options::OPT_rewrite_objc))
668    CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
669  else {
670    // Map the driver type to the frontend type. This is mostly an identity
671    // mapping, except that the distinction between module interface units
672    // and other source files does not exist at the frontend layer.
673    const char *ClangType;
674    switch (Input.getType()) {
675    case types::TY_CXXModule:
676      ClangType = "c++";
677      break;
678    case types::TY_PP_CXXModule:
679      ClangType = "c++-cpp-output";
680      break;
681    default:
682      ClangType = types::getTypeName(Input.getType());
683      break;
684    }
685    CmdArgs.push_back(ClangType);
686  }
687}
688
689static void appendUserToPath(SmallVectorImpl<char> &Result) {
690#ifdef LLVM_ON_UNIX
691  const char *Username = getenv("LOGNAME");
692#else
693  const char *Username = getenv("USERNAME");
694#endif
695  if (Username) {
696    // Validate that LoginName can be used in a path, and get its length.
697    size_t Len = 0;
698    for (const char *P = Username; *P; ++P, ++Len) {
699      if (!clang::isAlphanumeric(*P) && *P != '_') {
700        Username = nullptr;
701        break;
702      }
703    }
704
705    if (Username && Len > 0) {
706      Result.append(Username, Username + Len);
707      return;
708    }
709  }
710
711// Fallback to user id.
712#ifdef LLVM_ON_UNIX
713  std::string UID = llvm::utostr(getuid());
714#else
715  // FIXME: Windows seems to have an 'SID' that might work.
716  std::string UID = "9999";
717#endif
718  Result.append(UID.begin(), UID.end());
719}
720
721static void addPGOAndCoverageFlags(Compilation &Cconst Driver &D,
722                                   const InputInfo &Outputconst ArgList &Args,
723                                   ArgStringList &CmdArgs) {
724
725  auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
726                                         options::OPT_fprofile_generate_EQ,
727                                         options::OPT_fno_profile_generate);
728  if (PGOGenerateArg &&
729      PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
730    PGOGenerateArg = nullptr;
731
732  auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
733                                           options::OPT_fcs_profile_generate_EQ,
734                                           options::OPT_fno_profile_generate);
735  if (CSPGOGenerateArg &&
736      CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
737    CSPGOGenerateArg = nullptr;
738
739  auto *ProfileGenerateArg = Args.getLastArg(
740      options::OPT_fprofile_instr_generate,
741      options::OPT_fprofile_instr_generate_EQ,
742      options::OPT_fno_profile_instr_generate);
743  if (ProfileGenerateArg &&
744      ProfileGenerateArg->getOption().matches(
745          options::OPT_fno_profile_instr_generate))
746    ProfileGenerateArg = nullptr;
747
748  if (PGOGenerateArg && ProfileGenerateArg)
749    D.Diag(diag::err_drv_argument_not_allowed_with)
750        << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
751
752  auto *ProfileUseArg = getLastProfileUseArg(Args);
753
754  if (PGOGenerateArg && ProfileUseArg)
755    D.Diag(diag::err_drv_argument_not_allowed_with)
756        << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
757
758  if (ProfileGenerateArg && ProfileUseArg)
759    D.Diag(diag::err_drv_argument_not_allowed_with)
760        << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
761
762  if (CSPGOGenerateArg && PGOGenerateArg)
763    D.Diag(diag::err_drv_argument_not_allowed_with)
764        << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
765
766  if (ProfileGenerateArg) {
767    if (ProfileGenerateArg->getOption().matches(
768            options::OPT_fprofile_instr_generate_EQ))
769      CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
770                                           ProfileGenerateArg->getValue()));
771    // The default is to use Clang Instrumentation.
772    CmdArgs.push_back("-fprofile-instrument=clang");
773  }
774
775  Arg *PGOGenArg = nullptr;
776  if (PGOGenerateArg) {
777    assert(!CSPGOGenerateArg);
778    PGOGenArg = PGOGenerateArg;
779    CmdArgs.push_back("-fprofile-instrument=llvm");
780  }
781  if (CSPGOGenerateArg) {
782    assert(!PGOGenerateArg);
783    PGOGenArg = CSPGOGenerateArg;
784    CmdArgs.push_back("-fprofile-instrument=csllvm");
785  }
786  if (PGOGenArg) {
787    if (PGOGenArg->getOption().matches(
788            PGOGenerateArg ? options::OPT_fprofile_generate_EQ
789                           : options::OPT_fcs_profile_generate_EQ)) {
790      SmallString<128Path(PGOGenArg->getValue());
791      llvm::sys::path::append(Path, "default_%m.profraw");
792      CmdArgs.push_back(
793          Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
794    }
795  }
796
797  if (ProfileUseArg) {
798    if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
799      CmdArgs.push_back(Args.MakeArgString(
800          Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
801    else if ((ProfileUseArg->getOption().matches(
802                  options::OPT_fprofile_use_EQ) ||
803              ProfileUseArg->getOption().matches(
804                  options::OPT_fprofile_instr_use))) {
805      SmallString<128Path(
806          ProfileUseArg->getNumValues() == 0 ? "" : ProfileUseArg->getValue());
807      if (Path.empty() || llvm::sys::fs::is_directory(Path))
808        llvm::sys::path::append(Path, "default.profdata");
809      CmdArgs.push_back(
810          Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
811    }
812  }
813
814  if (Args.hasArg(options::OPT_ftest_coverage) ||
815      Args.hasArg(options::OPT_coverage))
816    CmdArgs.push_back("-femit-coverage-notes");
817  if (Args.hasFlag(options::OPT_fprofile_arcs, options::OPT_fno_profile_arcs,
818                   false) ||
819      Args.hasArg(options::OPT_coverage))
820    CmdArgs.push_back("-femit-coverage-data");
821
822  if (Args.hasFlag(options::OPT_fcoverage_mapping,
823                   options::OPT_fno_coverage_mapping, false)) {
824    if (!ProfileGenerateArg)
825      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
826          << "-fcoverage-mapping"
827          << "-fprofile-instr-generate";
828
829    CmdArgs.push_back("-fcoverage-mapping");
830  }
831
832  if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
833    auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
834    if (!Args.hasArg(options::OPT_coverage))
835      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
836          << "-fprofile-exclude-files="
837          << "--coverage";
838
839    StringRef v = Arg->getValue();
840    CmdArgs.push_back(
841        Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
842  }
843
844  if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
845    auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
846    if (!Args.hasArg(options::OPT_coverage))
847      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
848          << "-fprofile-filter-files="
849          << "--coverage";
850
851    StringRef v = Arg->getValue();
852    CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
853  }
854
855  if (C.getArgs().hasArg(options::OPT_c) ||
856      C.getArgs().hasArg(options::OPT_S)) {
857    if (Output.isFilename()) {
858      CmdArgs.push_back("-coverage-notes-file");
859      SmallString<128OutputFilename;
860      if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
861        OutputFilename = FinalOutput->getValue();
862      else
863        OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
864      SmallString<128CoverageFilename = OutputFilename;
865      if (llvm::sys::path::is_relative(CoverageFilename)) {
866        SmallString<128Pwd;
867        if (!llvm::sys::fs::current_path(Pwd)) {
868          llvm::sys::path::append(Pwd, CoverageFilename);
869          CoverageFilename.swap(Pwd);
870        }
871      }
872      llvm::sys::path::replace_extension(CoverageFilename, "gcno");
873      CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
874
875      // Leave -fprofile-dir= an unused argument unless .gcda emission is
876      // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
877      // the flag used. There is no -fno-profile-dir, so the user has no
878      // targeted way to suppress the warning.
879      if (Args.hasArg(options::OPT_fprofile_arcs) ||
880          Args.hasArg(options::OPT_coverage)) {
881        CmdArgs.push_back("-coverage-data-file");
882        if (Arg *FProfileDir = Args.getLastArg(options::OPT_fprofile_dir)) {
883          CoverageFilename = FProfileDir->getValue();
884          llvm::sys::path::append(CoverageFilename, OutputFilename);
885        }
886        llvm::sys::path::replace_extension(CoverageFilename, "gcda");
887        CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
888      }
889    }
890  }
891}
892
893/// Check whether the given input tree contains any compilation actions.
894static bool ContainsCompileAction(const Action *A) {
895  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
896    return true;
897
898  for (const auto &AI : A->inputs())
899    if (ContainsCompileAction(AI))
900      return true;
901
902  return false;
903}
904
905/// Check if -relax-all should be passed to the internal assembler.
906/// This is done by default when compiling non-assembler source with -O0.
907static bool UseRelaxAll(Compilation &Cconst ArgList &Args) {
908  bool RelaxDefault = true;
909
910  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
911    RelaxDefault = A->getOption().matches(options::OPT_O0);
912
913  if (RelaxDefault) {
914    RelaxDefault = false;
915    for (const auto &Act : C.getActions()) {
916      if (ContainsCompileAction(Act)) {
917        RelaxDefault = true;
918        break;
919      }
920    }
921  }
922
923  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
924                      RelaxDefault);
925}
926
927// Extract the integer N from a string spelled "-dwarf-N", returning 0
928// on mismatch. The StringRef input (rather than an Arg) allows
929// for use by the "-Xassembler" option parser.
930static unsigned DwarfVersionNum(StringRef ArgValue) {
931  return llvm::StringSwitch<unsigned>(ArgValue)
932      .Case("-gdwarf-2"2)
933      .Case("-gdwarf-3"3)
934      .Case("-gdwarf-4"4)
935      .Case("-gdwarf-5"5)
936      .Default(0);
937}
938
939static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
940                                    codegenoptions::DebugInfoKind DebugInfoKind,
941                                    unsigned DwarfVersion,
942                                    llvm::DebuggerKind DebuggerTuning) {
943  switch (DebugInfoKind) {
944  case codegenoptions::DebugDirectivesOnly:
945    CmdArgs.push_back("-debug-info-kind=line-directives-only");
946    break;
947  case codegenoptions::DebugLineTablesOnly:
948    CmdArgs.push_back("-debug-info-kind=line-tables-only");
949    break;
950  case codegenoptions::LimitedDebugInfo:
951    CmdArgs.push_back("-debug-info-kind=limited");
952    break;
953  case codegenoptions::FullDebugInfo:
954    CmdArgs.push_back("-debug-info-kind=standalone");
955    break;
956  default:
957    break;
958  }
959  if (DwarfVersion > 0)
960    CmdArgs.push_back(
961        Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
962  switch (DebuggerTuning) {
963  case llvm::DebuggerKind::GDB:
964    CmdArgs.push_back("-debugger-tuning=gdb");
965    break;
966  case llvm::DebuggerKind::LLDB:
967    CmdArgs.push_back("-debugger-tuning=lldb");
968    break;
969  case llvm::DebuggerKind::SCE:
970    CmdArgs.push_back("-debugger-tuning=sce");
971    break;
972  default:
973    break;
974  }
975}
976
977static bool checkDebugInfoOption(const Arg *Aconst ArgList &Args,
978                                 const Driver &Dconst ToolChain &TC) {
979   (0) . __assert_fail ("A && \"Expected non-nullptr argument.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 979, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(A && "Expected non-nullptr argument.");
980  if (TC.supportsDebugInfoOption(A))
981    return true;
982  D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
983      << A->getAsString(Args) << TC.getTripleString();
984  return false;
985}
986
987static void RenderDebugInfoCompressionArgs(const ArgList &Args,
988                                           ArgStringList &CmdArgs,
989                                           const Driver &D,
990                                           const ToolChain &TC) {
991  const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
992  if (!A)
993    return;
994  if (checkDebugInfoOption(AArgsDTC)) {
995    if (A->getOption().getID() == options::OPT_gz) {
996      if (llvm::zlib::isAvailable())
997        CmdArgs.push_back("-compress-debug-sections");
998      else
999        D.Diag(diag::warn_debug_compression_unavailable);
1000      return;
1001    }
1002
1003    StringRef Value = A->getValue();
1004    if (Value == "none") {
1005      CmdArgs.push_back("-compress-debug-sections=none");
1006    } else if (Value == "zlib" || Value == "zlib-gnu") {
1007      if (llvm::zlib::isAvailable()) {
1008        CmdArgs.push_back(
1009            Args.MakeArgString("-compress-debug-sections=" + Twine(Value)));
1010      } else {
1011        D.Diag(diag::warn_debug_compression_unavailable);
1012      }
1013    } else {
1014      D.Diag(diag::err_drv_unsupported_option_argument)
1015          << A->getOption().getName() << Value;
1016    }
1017  }
1018}
1019
1020static const char *RelocationModelName(llvm::Reloc::Model Model) {
1021  switch (Model) {
1022  case llvm::Reloc::Static:
1023    return "static";
1024  case llvm::Reloc::PIC_:
1025    return "pic";
1026  case llvm::Reloc::DynamicNoPIC:
1027    return "dynamic-no-pic";
1028  case llvm::Reloc::ROPI:
1029    return "ropi";
1030  case llvm::Reloc::RWPI:
1031    return "rwpi";
1032  case llvm::Reloc::ROPI_RWPI:
1033    return "ropi-rwpi";
1034  }
1035  llvm_unreachable("Unknown Reloc::Model kind");
1036}
1037
1038void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1039                                    const Driver &D, const ArgList &Args,
1040                                    ArgStringList &CmdArgs,
1041                                    const InputInfo &Output,
1042                                    const InputInfoList &Inputs) const {
1043  Arg *A;
1044  const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1045
1046  CheckPreprocessingOptions(D, Args);
1047
1048  Args.AddLastArg(CmdArgs, options::OPT_C);
1049  Args.AddLastArg(CmdArgs, options::OPT_CC);
1050
1051  // Handle dependency file generation.
1052  if ((A = Args.getLastArg(options::OPT_M, options::OPT_MM)) ||
1053      (A = Args.getLastArg(options::OPT_MD)) ||
1054      (A = Args.getLastArg(options::OPT_MMD))) {
1055    // Determine the output location.
1056    const char *DepFile;
1057    if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1058      DepFile = MF->getValue();
1059      C.addFailureResultFile(DepFile, &JA);
1060    } else if (Output.getType() == types::TY_Dependencies) {
1061      DepFile = Output.getFilename();
1062    } else if (A->getOption().matches(options::OPT_M) ||
1063               A->getOption().matches(options::OPT_MM)) {
1064      DepFile = "-";
1065    } else {
1066      DepFile = getDependencyFileName(Args, Inputs);
1067      C.addFailureResultFile(DepFile, &JA);
1068    }
1069    CmdArgs.push_back("-dependency-file");
1070    CmdArgs.push_back(DepFile);
1071
1072    // Add a default target if one wasn't specified.
1073    if (!Args.hasArg(options::OPT_MT) && !Args.hasArg(options::OPT_MQ)) {
1074      const char *DepTarget;
1075
1076      // If user provided -o, that is the dependency target, except
1077      // when we are only generating a dependency file.
1078      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1079      if (OutputOpt && Output.getType() != types::TY_Dependencies) {
1080        DepTarget = OutputOpt->getValue();
1081      } else {
1082        // Otherwise derive from the base input.
1083        //
1084        // FIXME: This should use the computed output file location.
1085        SmallString<128> P(Inputs[0].getBaseInput());
1086        llvm::sys::path::replace_extension(P, "o");
1087        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1088      }
1089
1090      if (!A->getOption().matches(options::OPT_MD) && !A->getOption().matches(options::OPT_MMD)) {
1091        CmdArgs.push_back("-w");
1092      }
1093      CmdArgs.push_back("-MT");
1094      SmallString<128> Quoted;
1095      QuoteTarget(DepTarget, Quoted);
1096      CmdArgs.push_back(Args.MakeArgString(Quoted));
1097    }
1098
1099    if (A->getOption().matches(options::OPT_M) ||
1100        A->getOption().matches(options::OPT_MD))
1101      CmdArgs.push_back("-sys-header-deps");
1102    if ((isa<PrecompileJobAction>(JA) &&
1103         !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1104        Args.hasArg(options::OPT_fmodule_file_deps))
1105      CmdArgs.push_back("-module-file-deps");
1106  }
1107
1108  if (Args.hasArg(options::OPT_MG)) {
1109    if (!A || A->getOption().matches(options::OPT_MD) ||
1110        A->getOption().matches(options::OPT_MMD))
1111      D.Diag(diag::err_drv_mg_requires_m_or_mm);
1112    CmdArgs.push_back("-MG");
1113  }
1114
1115  Args.AddLastArg(CmdArgs, options::OPT_MP);
1116  Args.AddLastArg(CmdArgs, options::OPT_MV);
1117
1118  // Convert all -MQ <target> args to -MT <quoted target>
1119  for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1120    A->claim();
1121
1122    if (A->getOption().matches(options::OPT_MQ)) {
1123      CmdArgs.push_back("-MT");
1124      SmallString<128> Quoted;
1125      QuoteTarget(A->getValue(), Quoted);
1126      CmdArgs.push_back(Args.MakeArgString(Quoted));
1127
1128      // -MT flag - no change
1129    } else {
1130      A->render(Args, CmdArgs);
1131    }
1132  }
1133
1134  // Add offload include arguments specific for CUDA.  This must happen before
1135  // we -I or -include anything else, because we must pick up the CUDA headers
1136  // from the particular CUDA installation, rather than from e.g.
1137  // /usr/local/include.
1138  if (JA.isOffloading(Action::OFK_Cuda))
1139    getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1140
1141  // Add -i* options, and automatically translate to
1142  // -include-pch/-include-pth for transparent PCH support. It's
1143  // wonky, but we include looking for .gch so we can support seamless
1144  // replacement into a build system already set up to be generating
1145  // .gch files.
1146
1147  if (getToolChain().getDriver().IsCLMode()) {
1148    const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1149    const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1150    if (YcArg && JA.getKind() >= Action::PrecompileJobClass &&
1151        JA.getKind() <= Action::AssembleJobClass) {
1152      CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1153    }
1154    if (YcArg || YuArg) {
1155      StringRef ThroughHeader = YcArg ? YcArg->getValue() : YuArg->getValue();
1156      if (!isa<PrecompileJobAction>(JA)) {
1157        CmdArgs.push_back("-include-pch");
1158        CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1159            C, !ThroughHeader.empty()
1160                   ? ThroughHeader
1161                   : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1162      }
1163
1164      if (ThroughHeader.empty()) {
1165        CmdArgs.push_back(Args.MakeArgString(
1166            Twine("-pch-through-hdrstop-") + (YcArg ? "create" : "use")));
1167      } else {
1168        CmdArgs.push_back(
1169            Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1170      }
1171    }
1172  }
1173
1174  bool RenderedImplicitInclude = false;
1175  for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1176    if (A->getOption().matches(options::OPT_include)) {
1177      // Handling of gcc-style gch precompiled headers.
1178      bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1179      RenderedImplicitInclude = true;
1180
1181      bool FoundPCH = false;
1182      SmallString<128> P(A->getValue());
1183      // We want the files to have a name like foo.h.pch. Add a dummy extension
1184      // so that replace_extension does the right thing.
1185      P += ".dummy";
1186      llvm::sys::path::replace_extension(P, "pch");
1187      if (llvm::sys::fs::exists(P))
1188        FoundPCH = true;
1189
1190      if (!FoundPCH) {
1191        llvm::sys::path::replace_extension(P, "gch");
1192        if (llvm::sys::fs::exists(P)) {
1193          FoundPCH = true;
1194        }
1195      }
1196
1197      if (FoundPCH) {
1198        if (IsFirstImplicitInclude) {
1199          A->claim();
1200          CmdArgs.push_back("-include-pch");
1201          CmdArgs.push_back(Args.MakeArgString(P));
1202          continue;
1203        } else {
1204          // Ignore the PCH if not first on command line and emit warning.
1205          D.Diag(diag::warn_drv_pch_not_first_include) << P
1206                                                       << A->getAsString(Args);
1207        }
1208      }
1209    } else if (A->getOption().matches(options::OPT_isystem_after)) {
1210      // Handling of paths which must come late.  These entries are handled by
1211      // the toolchain itself after the resource dir is inserted in the right
1212      // search order.
1213      // Do not claim the argument so that the use of the argument does not
1214      // silently go unnoticed on toolchains which do not honour the option.
1215      continue;
1216    }
1217
1218    // Not translated, render as usual.
1219    A->claim();
1220    A->render(Args, CmdArgs);
1221  }
1222
1223  Args.AddAllArgs(CmdArgs,
1224                  {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1225                   options::OPT_F, options::OPT_index_header_map});
1226
1227  // Add -Wp, and -Xpreprocessor if using the preprocessor.
1228
1229  // FIXME: There is a very unfortunate problem here, some troubled
1230  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1231  // really support that we would have to parse and then translate
1232  // those options. :(
1233  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1234                       options::OPT_Xpreprocessor);
1235
1236  // -I- is a deprecated GCC feature, reject it.
1237  if (Arg *A = Args.getLastArg(options::OPT_I_))
1238    D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1239
1240  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1241  // -isysroot to the CC1 invocation.
1242  StringRef sysroot = C.getSysRoot();
1243  if (sysroot != "") {
1244    if (!Args.hasArg(options::OPT_isysroot)) {
1245      CmdArgs.push_back("-isysroot");
1246      CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1247    }
1248  }
1249
1250  // Parse additional include paths from environment variables.
1251  // FIXME: We should probably sink the logic for handling these from the
1252  // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1253  // CPATH - included following the user specified includes (but prior to
1254  // builtin and standard includes).
1255  addDirectoryList(Args, CmdArgs, "-I""CPATH");
1256  // C_INCLUDE_PATH - system includes enabled when compiling C.
1257  addDirectoryList(Args, CmdArgs, "-c-isystem""C_INCLUDE_PATH");
1258  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1259  addDirectoryList(Args, CmdArgs, "-cxx-isystem""CPLUS_INCLUDE_PATH");
1260  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1261  addDirectoryList(Args, CmdArgs, "-objc-isystem""OBJC_INCLUDE_PATH");
1262  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1263  addDirectoryList(Args, CmdArgs, "-objcxx-isystem""OBJCPLUS_INCLUDE_PATH");
1264
1265  // While adding the include arguments, we also attempt to retrieve the
1266  // arguments of related offloading toolchains or arguments that are specific
1267  // of an offloading programming model.
1268
1269  // Add C++ include arguments, if needed.
1270  if (types::isCXX(Inputs[0].getType()))
1271    forAllAssociatedToolChains(C, JA, getToolChain(),
1272                               [&Args, &CmdArgs](const ToolChain &TC) {
1273                                 TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1274                               });
1275
1276  // Add system include arguments for all targets but IAMCU.
1277  if (!IsIAMCU)
1278    forAllAssociatedToolChains(C, JA, getToolChain(),
1279                               [&Args, &CmdArgs](const ToolChain &TC) {
1280                                 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1281                               });
1282  else {
1283    // For IAMCU add special include arguments.
1284    getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1285  }
1286}
1287
1288// FIXME: Move to target hook.
1289static bool isSignedCharDefault(const llvm::Triple &Triple) {
1290  switch (Triple.getArch()) {
1291  default:
1292    return true;
1293
1294  case llvm::Triple::aarch64:
1295  case llvm::Triple::aarch64_be:
1296  case llvm::Triple::arm:
1297  case llvm::Triple::armeb:
1298  case llvm::Triple::thumb:
1299  case llvm::Triple::thumbeb:
1300    if (Triple.isOSDarwin() || Triple.isOSWindows())
1301      return true;
1302    return false;
1303
1304  case llvm::Triple::ppc:
1305  case llvm::Triple::ppc64:
1306    if (Triple.isOSDarwin())
1307      return true;
1308    return false;
1309
1310  case llvm::Triple::hexagon:
1311  case llvm::Triple::ppc64le:
1312  case llvm::Triple::riscv32:
1313  case llvm::Triple::riscv64:
1314  case llvm::Triple::systemz:
1315  case llvm::Triple::xcore:
1316    return false;
1317  }
1318}
1319
1320static bool isNoCommonDefault(const llvm::Triple &Triple) {
1321  switch (Triple.getArch()) {
1322  default:
1323    if (Triple.isOSFuchsia())
1324      return true;
1325    return false;
1326
1327  case llvm::Triple::xcore:
1328  case llvm::Triple::wasm32:
1329  case llvm::Triple::wasm64:
1330    return true;
1331  }
1332}
1333
1334namespace {
1335void RenderARMABI(const llvm::Triple &Tripleconst ArgList &Args,
1336                  ArgStringList &CmdArgs) {
1337  // Select the ABI to use.
1338  // FIXME: Support -meabi.
1339  // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1340  const char *ABIName = nullptr;
1341  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1342    ABIName = A->getValue();
1343  } else {
1344    std::string CPU = getCPUName(ArgsTriple/*FromAs*/ false);
1345    ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1346  }
1347
1348  CmdArgs.push_back("-target-abi");
1349  CmdArgs.push_back(ABIName);
1350}
1351}
1352
1353void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1354                             ArgStringList &CmdArgs, bool KernelOrKext) const {
1355  RenderARMABI(Triple, Args, CmdArgs);
1356
1357  // Determine floating point ABI from the options & target defaults.
1358  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1359  if (ABI == arm::FloatABI::Soft) {
1360    // Floating point operations and argument passing are soft.
1361    // FIXME: This changes CPP defines, we need -target-soft-float.
1362    CmdArgs.push_back("-msoft-float");
1363    CmdArgs.push_back("-mfloat-abi");
1364    CmdArgs.push_back("soft");
1365  } else if (ABI == arm::FloatABI::SoftFP) {
1366    // Floating point operations are hard, but argument passing is soft.
1367    CmdArgs.push_back("-mfloat-abi");
1368    CmdArgs.push_back("soft");
1369  } else {
1370    // Floating point operations and argument passing are hard.
1371     (0) . __assert_fail ("ABI == arm..FloatABI..Hard && \"Invalid float abi!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 1371, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1372    CmdArgs.push_back("-mfloat-abi");
1373    CmdArgs.push_back("hard");
1374  }
1375
1376  // Forward the -mglobal-merge option for explicit control over the pass.
1377  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1378                               options::OPT_mno_global_merge)) {
1379    CmdArgs.push_back("-mllvm");
1380    if (A->getOption().matches(options::OPT_mno_global_merge))
1381      CmdArgs.push_back("-arm-global-merge=false");
1382    else
1383      CmdArgs.push_back("-arm-global-merge=true");
1384  }
1385
1386  if (!Args.hasFlag(options::OPT_mimplicit_float,
1387                    options::OPT_mno_implicit_float, true))
1388    CmdArgs.push_back("-no-implicit-float");
1389}
1390
1391void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1392                                const ArgList &Args, bool KernelOrKext,
1393                                ArgStringList &CmdArgs) const {
1394  const ToolChain &TC = getToolChain();
1395
1396  // Add the target features
1397  getTargetFeatures(TC, EffectiveTriple, Args, CmdArgs, false);
1398
1399  // Add target specific flags.
1400  switch (TC.getArch()) {
1401  default:
1402    break;
1403
1404  case llvm::Triple::arm:
1405  case llvm::Triple::armeb:
1406  case llvm::Triple::thumb:
1407  case llvm::Triple::thumbeb:
1408    // Use the effective triple, which takes into account the deployment target.
1409    AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1410    CmdArgs.push_back("-fallow-half-arguments-and-returns");
1411    break;
1412
1413  case llvm::Triple::aarch64:
1414  case llvm::Triple::aarch64_be:
1415    AddAArch64TargetArgs(Args, CmdArgs);
1416    CmdArgs.push_back("-fallow-half-arguments-and-returns");
1417    break;
1418
1419  case llvm::Triple::mips:
1420  case llvm::Triple::mipsel:
1421  case llvm::Triple::mips64:
1422  case llvm::Triple::mips64el:
1423    AddMIPSTargetArgs(Args, CmdArgs);
1424    break;
1425
1426  case llvm::Triple::ppc:
1427  case llvm::Triple::ppc64:
1428  case llvm::Triple::ppc64le:
1429    AddPPCTargetArgs(Args, CmdArgs);
1430    break;
1431
1432  case llvm::Triple::riscv32:
1433  case llvm::Triple::riscv64:
1434    AddRISCVTargetArgs(Args, CmdArgs);
1435    break;
1436
1437  case llvm::Triple::sparc:
1438  case llvm::Triple::sparcel:
1439  case llvm::Triple::sparcv9:
1440    AddSparcTargetArgs(Args, CmdArgs);
1441    break;
1442
1443  case llvm::Triple::systemz:
1444    AddSystemZTargetArgs(Args, CmdArgs);
1445    break;
1446
1447  case llvm::Triple::x86:
1448  case llvm::Triple::x86_64:
1449    AddX86TargetArgs(Args, CmdArgs);
1450    break;
1451
1452  case llvm::Triple::lanai:
1453    AddLanaiTargetArgs(Args, CmdArgs);
1454    break;
1455
1456  case llvm::Triple::hexagon:
1457    AddHexagonTargetArgs(Args, CmdArgs);
1458    break;
1459
1460  case llvm::Triple::wasm32:
1461  case llvm::Triple::wasm64:
1462    AddWebAssemblyTargetArgs(Args, CmdArgs);
1463    break;
1464  }
1465}
1466
1467// Parse -mbranch-protection=<protection>[+<protection>]* where
1468//   <protection> ::= standard | none | [bti,pac-ret[+b-key,+leaf]*]
1469// Returns a triple of (return address signing Scope, signing key, require
1470// landing pads)
1471static std::tuple<StringRefStringRefbool>
1472ParseAArch64BranchProtection(const Driver &Dconst ArgList &Args,
1473                             const Arg *A) {
1474  StringRef Scope = "none";
1475  StringRef Key = "a_key";
1476  bool IndirectBranches = false;
1477
1478  StringRef Value = A->getValue();
1479  // This maps onto -mbranch-protection=<scope>+<key>
1480
1481  if (Value.equals("standard")) {
1482    Scope = "non-leaf";
1483    Key = "a_key";
1484    IndirectBranches = true;
1485
1486  } else if (!Value.equals("none")) {
1487    SmallVector<StringRef4BranchProtection;
1488    StringRef(A->getValue()).split(BranchProtection, '+');
1489
1490    auto Protection = BranchProtection.begin();
1491    while (Protection != BranchProtection.end()) {
1492      if (Protection->equals("bti"))
1493        IndirectBranches = true;
1494      else if (Protection->equals("pac-ret")) {
1495        Scope = "non-leaf";
1496        while (++Protection != BranchProtection.end()) {
1497          // Inner loop as "leaf" and "b-key" options must only appear attached
1498          // to pac-ret.
1499          if (Protection->equals("leaf"))
1500            Scope = "all";
1501          else if (Protection->equals("b-key"))
1502            Key = "b_key";
1503          else
1504            break;
1505        }
1506        Protection--;
1507      } else
1508        D.Diag(diag::err_invalid_branch_protection)
1509            << *Protection << A->getAsString(Args);
1510      Protection++;
1511    }
1512  }
1513
1514  return std::make_tuple(Scope, Key, IndirectBranches);
1515}
1516
1517namespace {
1518void RenderAArch64ABI(const llvm::Triple &Tripleconst ArgList &Args,
1519                      ArgStringList &CmdArgs) {
1520  const char *ABIName = nullptr;
1521  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1522    ABIName = A->getValue();
1523  else if (Triple.isOSDarwin())
1524    ABIName = "darwinpcs";
1525  else
1526    ABIName = "aapcs";
1527
1528  CmdArgs.push_back("-target-abi");
1529  CmdArgs.push_back(ABIName);
1530}
1531}
1532
1533void Clang::AddAArch64TargetArgs(const ArgList &Args,
1534                                 ArgStringList &CmdArgs) const {
1535  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1536
1537  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1538      Args.hasArg(options::OPT_mkernel) ||
1539      Args.hasArg(options::OPT_fapple_kext))
1540    CmdArgs.push_back("-disable-red-zone");
1541
1542  if (!Args.hasFlag(options::OPT_mimplicit_float,
1543                    options::OPT_mno_implicit_float, true))
1544    CmdArgs.push_back("-no-implicit-float");
1545
1546  RenderAArch64ABI(Triple, Args, CmdArgs);
1547
1548  if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1549                               options::OPT_mno_fix_cortex_a53_835769)) {
1550    CmdArgs.push_back("-mllvm");
1551    if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1552      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1553    else
1554      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1555  } else if (Triple.isAndroid()) {
1556    // Enabled A53 errata (835769) workaround by default on android
1557    CmdArgs.push_back("-mllvm");
1558    CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1559  }
1560
1561  // Forward the -mglobal-merge option for explicit control over the pass.
1562  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1563                               options::OPT_mno_global_merge)) {
1564    CmdArgs.push_back("-mllvm");
1565    if (A->getOption().matches(options::OPT_mno_global_merge))
1566      CmdArgs.push_back("-aarch64-enable-global-merge=false");
1567    else
1568      CmdArgs.push_back("-aarch64-enable-global-merge=true");
1569  }
1570
1571  // Enable/disable return address signing and indirect branch targets.
1572  if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1573                               options::OPT_mbranch_protection_EQ)) {
1574
1575    const Driver &D = getToolChain().getDriver();
1576
1577    StringRef Scope, Key;
1578    bool IndirectBranches;
1579
1580    if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1581      Scope = A->getValue();
1582      if (!Scope.equals("none") && !Scope.equals("non-leaf") &&
1583          !Scope.equals("all"))
1584        D.Diag(diag::err_invalid_branch_protection)
1585            << Scope << A->getAsString(Args);
1586      Key = "a_key";
1587      IndirectBranches = false;
1588    } else
1589      std::tie(Scope, Key, IndirectBranches) =
1590          ParseAArch64BranchProtection(D, Args, A);
1591
1592    CmdArgs.push_back(
1593        Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1594    CmdArgs.push_back(
1595        Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1596    if (IndirectBranches)
1597      CmdArgs.push_back("-mbranch-target-enforce");
1598  }
1599}
1600
1601void Clang::AddMIPSTargetArgs(const ArgList &Args,
1602                              ArgStringList &CmdArgs) const {
1603  const Driver &D = getToolChain().getDriver();
1604  StringRef CPUName;
1605  StringRef ABIName;
1606  const llvm::Triple &Triple = getToolChain().getTriple();
1607  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1608
1609  CmdArgs.push_back("-target-abi");
1610  CmdArgs.push_back(ABIName.data());
1611
1612  mips::FloatABI ABI = mips::getMipsFloatABI(D, Args);
1613  if (ABI == mips::FloatABI::Soft) {
1614    // Floating point operations and argument passing are soft.
1615    CmdArgs.push_back("-msoft-float");
1616    CmdArgs.push_back("-mfloat-abi");
1617    CmdArgs.push_back("soft");
1618  } else {
1619    // Floating point operations and argument passing are hard.
1620     (0) . __assert_fail ("ABI == mips..FloatABI..Hard && \"Invalid float abi!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 1620, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1621    CmdArgs.push_back("-mfloat-abi");
1622    CmdArgs.push_back("hard");
1623  }
1624
1625  if (Arg *A = Args.getLastArg(options::OPT_mxgot, options::OPT_mno_xgot)) {
1626    if (A->getOption().matches(options::OPT_mxgot)) {
1627      CmdArgs.push_back("-mllvm");
1628      CmdArgs.push_back("-mxgot");
1629    }
1630  }
1631
1632  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1633                               options::OPT_mno_ldc1_sdc1)) {
1634    if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1635      CmdArgs.push_back("-mllvm");
1636      CmdArgs.push_back("-mno-ldc1-sdc1");
1637    }
1638  }
1639
1640  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1641                               options::OPT_mno_check_zero_division)) {
1642    if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1643      CmdArgs.push_back("-mllvm");
1644      CmdArgs.push_back("-mno-check-zero-division");
1645    }
1646  }
1647
1648  if (Arg *A = Args.getLastArg(options::OPT_G)) {
1649    StringRef v = A->getValue();
1650    CmdArgs.push_back("-mllvm");
1651    CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1652    A->claim();
1653  }
1654
1655  Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1656  Arg *ABICalls =
1657      Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1658
1659  // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1660  // -mgpopt is the default for static, -fno-pic environments but these two
1661  // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1662  // the only case where -mllvm -mgpopt is passed.
1663  // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1664  //       passed explicitly when compiling something with -mabicalls
1665  //       (implictly) in affect. Currently the warning is in the backend.
1666  //
1667  // When the ABI in use is  N64, we also need to determine the PIC mode that
1668  // is in use, as -fno-pic for N64 implies -mno-abicalls.
1669  bool NoABICalls =
1670      ABICalls && ABICalls->getOption().matches(options::OPT_mno_abicalls);
1671
1672  llvm::Reloc::Model RelocationModel;
1673  unsigned PICLevel;
1674  bool IsPIE;
1675  std::tie(RelocationModel, PICLevel, IsPIE) =
1676      ParsePICArgs(getToolChain(), Args);
1677
1678  NoABICalls = NoABICalls ||
1679               (RelocationModel == llvm::Reloc::Static && ABIName == "n64");
1680
1681  bool WantGPOpt = GPOpt && GPOpt->getOption().matches(options::OPT_mgpopt);
1682  // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1683  if (NoABICalls && (!GPOpt || WantGPOpt)) {
1684    CmdArgs.push_back("-mllvm");
1685    CmdArgs.push_back("-mgpopt");
1686
1687    Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1688                                      options::OPT_mno_local_sdata);
1689    Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1690                                       options::OPT_mno_extern_sdata);
1691    Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1692                                        options::OPT_mno_embedded_data);
1693    if (LocalSData) {
1694      CmdArgs.push_back("-mllvm");
1695      if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1696        CmdArgs.push_back("-mlocal-sdata=1");
1697      } else {
1698        CmdArgs.push_back("-mlocal-sdata=0");
1699      }
1700      LocalSData->claim();
1701    }
1702
1703    if (ExternSData) {
1704      CmdArgs.push_back("-mllvm");
1705      if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1706        CmdArgs.push_back("-mextern-sdata=1");
1707      } else {
1708        CmdArgs.push_back("-mextern-sdata=0");
1709      }
1710      ExternSData->claim();
1711    }
1712
1713    if (EmbeddedData) {
1714      CmdArgs.push_back("-mllvm");
1715      if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1716        CmdArgs.push_back("-membedded-data=1");
1717      } else {
1718        CmdArgs.push_back("-membedded-data=0");
1719      }
1720      EmbeddedData->claim();
1721    }
1722
1723  } else if ((!ABICalls || (!NoABICalls && ABICalls)) && WantGPOpt)
1724    D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 0 : 1);
1725
1726  if (GPOpt)
1727    GPOpt->claim();
1728
1729  if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1730    StringRef Val = StringRef(A->getValue());
1731    if (mips::hasCompactBranches(CPUName)) {
1732      if (Val == "never" || Val == "always" || Val == "optimal") {
1733        CmdArgs.push_back("-mllvm");
1734        CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1735      } else
1736        D.Diag(diag::err_drv_unsupported_option_argument)
1737            << A->getOption().getName() << Val;
1738    } else
1739      D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1740  }
1741
1742  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1743                               options::OPT_mno_relax_pic_calls)) {
1744    if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1745      CmdArgs.push_back("-mllvm");
1746      CmdArgs.push_back("-mips-jalr-reloc=0");
1747    }
1748  }
1749}
1750
1751void Clang::AddPPCTargetArgs(const ArgList &Args,
1752                             ArgStringList &CmdArgs) const {
1753  // Select the ABI to use.
1754  const char *ABIName = nullptr;
1755  if (getToolChain().getTriple().isOSLinux())
1756    switch (getToolChain().getArch()) {
1757    case llvm::Triple::ppc64: {
1758      // When targeting a processor that supports QPX, or if QPX is
1759      // specifically enabled, default to using the ABI that supports QPX (so
1760      // long as it is not specifically disabled).
1761      bool HasQPX = false;
1762      if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
1763        HasQPX = A->getValue() == StringRef("a2q");
1764      HasQPX = Args.hasFlag(options::OPT_mqpx, options::OPT_mno_qpx, HasQPX);
1765      if (HasQPX) {
1766        ABIName = "elfv1-qpx";
1767        break;
1768      }
1769
1770      ABIName = "elfv1";
1771      break;
1772    }
1773    case llvm::Triple::ppc64le:
1774      ABIName = "elfv2";
1775      break;
1776    default:
1777      break;
1778    }
1779
1780  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1781    // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1782    // the option if given as we don't have backend support for any targets
1783    // that don't use the altivec abi.
1784    if (StringRef(A->getValue()) != "altivec")
1785      ABIName = A->getValue();
1786
1787  ppc::FloatABI FloatABI =
1788      ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1789
1790  if (FloatABI == ppc::FloatABI::Soft) {
1791    // Floating point operations and argument passing are soft.
1792    CmdArgs.push_back("-msoft-float");
1793    CmdArgs.push_back("-mfloat-abi");
1794    CmdArgs.push_back("soft");
1795  } else {
1796    // Floating point operations and argument passing are hard.
1797     (0) . __assert_fail ("FloatABI == ppc..FloatABI..Hard && \"Invalid float abi!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 1797, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1798    CmdArgs.push_back("-mfloat-abi");
1799    CmdArgs.push_back("hard");
1800  }
1801
1802  if (ABIName) {
1803    CmdArgs.push_back("-target-abi");
1804    CmdArgs.push_back(ABIName);
1805  }
1806}
1807
1808void Clang::AddRISCVTargetArgs(const ArgList &Args,
1809                               ArgStringList &CmdArgs) const {
1810  // FIXME: currently defaults to the soft-float ABIs. Will need to be
1811  // expanded to select ilp32f, ilp32d, lp64f, lp64d when appropriate.
1812  const char *ABIName = nullptr;
1813  const llvm::Triple &Triple = getToolChain().getTriple();
1814  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1815    ABIName = A->getValue();
1816  else if (Triple.getArch() == llvm::Triple::riscv32)
1817    ABIName = "ilp32";
1818  else if (Triple.getArch() == llvm::Triple::riscv64)
1819    ABIName = "lp64";
1820  else
1821    llvm_unreachable("Unexpected triple!");
1822
1823  CmdArgs.push_back("-target-abi");
1824  CmdArgs.push_back(ABIName);
1825}
1826
1827void Clang::AddSparcTargetArgs(const ArgList &Args,
1828                               ArgStringList &CmdArgs) const {
1829  sparc::FloatABI FloatABI =
1830      sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1831
1832  if (FloatABI == sparc::FloatABI::Soft) {
1833    // Floating point operations and argument passing are soft.
1834    CmdArgs.push_back("-msoft-float");
1835    CmdArgs.push_back("-mfloat-abi");
1836    CmdArgs.push_back("soft");
1837  } else {
1838    // Floating point operations and argument passing are hard.
1839     (0) . __assert_fail ("FloatABI == sparc..FloatABI..Hard && \"Invalid float abi!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 1839, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1840    CmdArgs.push_back("-mfloat-abi");
1841    CmdArgs.push_back("hard");
1842  }
1843}
1844
1845void Clang::AddSystemZTargetArgs(const ArgList &Args,
1846                                 ArgStringList &CmdArgs) const {
1847  if (Args.hasFlag(options::OPT_mbackchain, options::OPT_mno_backchain, false))
1848    CmdArgs.push_back("-mbackchain");
1849}
1850
1851void Clang::AddX86TargetArgs(const ArgList &Args,
1852                             ArgStringList &CmdArgs) const {
1853  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1854      Args.hasArg(options::OPT_mkernel) ||
1855      Args.hasArg(options::OPT_fapple_kext))
1856    CmdArgs.push_back("-disable-red-zone");
1857
1858  if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
1859                    options::OPT_mno_tls_direct_seg_refs, true))
1860    CmdArgs.push_back("-mno-tls-direct-seg-refs");
1861
1862  // Default to avoid implicit floating-point for kernel/kext code, but allow
1863  // that to be overridden with -mno-soft-float.
1864  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
1865                          Args.hasArg(options::OPT_fapple_kext));
1866  if (Arg *A = Args.getLastArg(
1867          options::OPT_msoft_float, options::OPT_mno_soft_float,
1868          options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
1869    const Option &O = A->getOption();
1870    NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
1871                       O.matches(options::OPT_msoft_float));
1872  }
1873  if (NoImplicitFloat)
1874    CmdArgs.push_back("-no-implicit-float");
1875
1876  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
1877    StringRef Value = A->getValue();
1878    if (Value == "intel" || Value == "att") {
1879      CmdArgs.push_back("-mllvm");
1880      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
1881    } else {
1882      getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
1883          << A->getOption().getName() << Value;
1884    }
1885  } else if (getToolChain().getDriver().IsCLMode()) {
1886    CmdArgs.push_back("-mllvm");
1887    CmdArgs.push_back("-x86-asm-syntax=intel");
1888  }
1889
1890  // Set flags to support MCU ABI.
1891  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
1892    CmdArgs.push_back("-mfloat-abi");
1893    CmdArgs.push_back("soft");
1894    CmdArgs.push_back("-mstack-alignment=4");
1895  }
1896}
1897
1898void Clang::AddHexagonTargetArgs(const ArgList &Args,
1899                                 ArgStringList &CmdArgs) const {
1900  CmdArgs.push_back("-mqdsp6-compat");
1901  CmdArgs.push_back("-Wreturn-type");
1902
1903  if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
1904    CmdArgs.push_back("-mllvm");
1905    CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
1906                                         Twine(G.getValue())));
1907  }
1908
1909  if (!Args.hasArg(options::OPT_fno_short_enums))
1910    CmdArgs.push_back("-fshort-enums");
1911  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
1912    CmdArgs.push_back("-mllvm");
1913    CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
1914  }
1915  CmdArgs.push_back("-mllvm");
1916  CmdArgs.push_back("-machine-sink-split=0");
1917}
1918
1919void Clang::AddLanaiTargetArgs(const ArgList &Args,
1920                               ArgStringList &CmdArgs) const {
1921  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
1922    StringRef CPUName = A->getValue();
1923
1924    CmdArgs.push_back("-target-cpu");
1925    CmdArgs.push_back(Args.MakeArgString(CPUName));
1926  }
1927  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
1928    StringRef Value = A->getValue();
1929    // Only support mregparm=4 to support old usage. Report error for all other
1930    // cases.
1931    int Mregparm;
1932    if (Value.getAsInteger(10, Mregparm)) {
1933      if (Mregparm != 4) {
1934        getToolChain().getDriver().Diag(
1935            diag::err_drv_unsupported_option_argument)
1936            << A->getOption().getName() << Value;
1937      }
1938    }
1939  }
1940}
1941
1942void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
1943                                     ArgStringList &CmdArgs) const {
1944  // Default to "hidden" visibility.
1945  if (!Args.hasArg(options::OPT_fvisibility_EQ,
1946                   options::OPT_fvisibility_ms_compat)) {
1947    CmdArgs.push_back("-fvisibility");
1948    CmdArgs.push_back("hidden");
1949  }
1950}
1951
1952void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
1953                                    StringRef Target, const InputInfo &Output,
1954                                    const InputInfo &Input, const ArgList &Args) const {
1955  // If this is a dry run, do not create the compilation database file.
1956  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
1957    return;
1958
1959  using llvm::yaml::escape;
1960  const Driver &D = getToolChain().getDriver();
1961
1962  if (!CompilationDatabase) {
1963    std::error_code EC;
1964    auto File = llvm::make_unique<llvm::raw_fd_ostream>(Filename, EC, llvm::sys::fs::F_Text);
1965    if (EC) {
1966      D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
1967                                                       << EC.message();
1968      return;
1969    }
1970    CompilationDatabase = std::move(File);
1971  }
1972  auto &CDB = *CompilationDatabase;
1973  SmallString<128> Buf;
1974  if (llvm::sys::fs::current_path(Buf))
1975    Buf = ".";
1976  CDB << "{ \"directory\": \"" << escape(Buf) << "\"";
1977  CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
1978  CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
1979  CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
1980  Buf = "-x";
1981  Buf += types::getTypeName(Input.getType());
1982  CDB << ", \"" << escape(Buf) << "\"";
1983  if (!D.SysRoot.empty() && !Args.hasArg(options::OPT__sysroot_EQ)) {
1984    Buf = "--sysroot=";
1985    Buf += D.SysRoot;
1986    CDB << ", \"" << escape(Buf) << "\"";
1987  }
1988  CDB << ", \"" << escape(Input.getFilename()) << "\"";
1989  for (auto &A: Args) {
1990    auto &O = A->getOption();
1991    // Skip language selection, which is positional.
1992    if (O.getID() == options::OPT_x)
1993      continue;
1994    // Skip writing dependency output and the compilation database itself.
1995    if (O.getGroup().isValid() && O.getGroup().getID() == options::OPT_M_Group)
1996      continue;
1997    // Skip inputs.
1998    if (O.getKind() == Option::InputClass)
1999      continue;
2000    // All other arguments are quoted and appended.
2001    ArgStringList ASL;
2002    A->render(Args, ASL);
2003    for (auto &it: ASL)
2004      CDB << ", \"" << escape(it) << "\"";
2005  }
2006  Buf = "--target=";
2007  Buf += Target;
2008  CDB << ", \"" << escape(Buf) << "\"]},\n";
2009}
2010
2011static void CollectArgsForIntegratedAssembler(Compilation &C,
2012                                              const ArgList &Args,
2013                                              ArgStringList &CmdArgs,
2014                                              const Driver &D) {
2015  if (UseRelaxAll(C, Args))
2016    CmdArgs.push_back("-mrelax-all");
2017
2018  // Only default to -mincremental-linker-compatible if we think we are
2019  // targeting the MSVC linker.
2020  bool DefaultIncrementalLinkerCompatible =
2021      C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2022  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2023                   options::OPT_mno_incremental_linker_compatible,
2024                   DefaultIncrementalLinkerCompatible))
2025    CmdArgs.push_back("-mincremental-linker-compatible");
2026
2027  switch (C.getDefaultToolChain().getArch()) {
2028  case llvm::Triple::arm:
2029  case llvm::Triple::armeb:
2030  case llvm::Triple::thumb:
2031  case llvm::Triple::thumbeb:
2032    if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2033      StringRef Value = A->getValue();
2034      if (Value == "always" || Value == "never" || Value == "arm" ||
2035          Value == "thumb") {
2036        CmdArgs.push_back("-mllvm");
2037        CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2038      } else {
2039        D.Diag(diag::err_drv_unsupported_option_argument)
2040            << A->getOption().getName() << Value;
2041      }
2042    }
2043    break;
2044  default:
2045    break;
2046  }
2047
2048  // When passing -I arguments to the assembler we sometimes need to
2049  // unconditionally take the next argument.  For example, when parsing
2050  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2051  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2052  // arg after parsing the '-I' arg.
2053  bool TakeNextArg = false;
2054
2055  bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2056  bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
2057  const char *MipsTargetFeature = nullptr;
2058  for (const Arg *A :
2059       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2060    A->claim();
2061
2062    for (StringRef Value : A->getValues()) {
2063      if (TakeNextArg) {
2064        CmdArgs.push_back(Value.data());
2065        TakeNextArg = false;
2066        continue;
2067      }
2068
2069      if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2070          Value == "-mbig-obj")
2071        continue// LLVM handles bigobj automatically
2072
2073      switch (C.getDefaultToolChain().getArch()) {
2074      default:
2075        break;
2076      case llvm::Triple::thumb:
2077      case llvm::Triple::thumbeb:
2078      case llvm::Triple::arm:
2079      case llvm::Triple::armeb:
2080        if (Value == "-mthumb")
2081          // -mthumb has already been processed in ComputeLLVMTriple()
2082          // recognize but skip over here.
2083          continue;
2084        break;
2085      case llvm::Triple::mips:
2086      case llvm::Triple::mipsel:
2087      case llvm::Triple::mips64:
2088      case llvm::Triple::mips64el:
2089        if (Value == "--trap") {
2090          CmdArgs.push_back("-target-feature");
2091          CmdArgs.push_back("+use-tcc-in-div");
2092          continue;
2093        }
2094        if (Value == "--break") {
2095          CmdArgs.push_back("-target-feature");
2096          CmdArgs.push_back("-use-tcc-in-div");
2097          continue;
2098        }
2099        if (Value.startswith("-msoft-float")) {
2100          CmdArgs.push_back("-target-feature");
2101          CmdArgs.push_back("+soft-float");
2102          continue;
2103        }
2104        if (Value.startswith("-mhard-float")) {
2105          CmdArgs.push_back("-target-feature");
2106          CmdArgs.push_back("-soft-float");
2107          continue;
2108        }
2109
2110        MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2111                                .Case("-mips1""+mips1")
2112                                .Case("-mips2""+mips2")
2113                                .Case("-mips3""+mips3")
2114                                .Case("-mips4""+mips4")
2115                                .Case("-mips5""+mips5")
2116                                .Case("-mips32""+mips32")
2117                                .Case("-mips32r2""+mips32r2")
2118                                .Case("-mips32r3""+mips32r3")
2119                                .Case("-mips32r5""+mips32r5")
2120                                .Case("-mips32r6""+mips32r6")
2121                                .Case("-mips64""+mips64")
2122                                .Case("-mips64r2""+mips64r2")
2123                                .Case("-mips64r3""+mips64r3")
2124                                .Case("-mips64r5""+mips64r5")
2125                                .Case("-mips64r6""+mips64r6")
2126                                .Default(nullptr);
2127        if (MipsTargetFeature)
2128          continue;
2129      }
2130
2131      if (Value == "-force_cpusubtype_ALL") {
2132        // Do nothing, this is the default and we don't support anything else.
2133      } else if (Value == "-L") {
2134        CmdArgs.push_back("-msave-temp-labels");
2135      } else if (Value == "--fatal-warnings") {
2136        CmdArgs.push_back("-massembler-fatal-warnings");
2137      } else if (Value == "--noexecstack") {
2138        UseNoExecStack = true;
2139      } else if (Value.startswith("-compress-debug-sections") ||
2140                 Value.startswith("--compress-debug-sections") ||
2141                 Value == "-nocompress-debug-sections" ||
2142                 Value == "--nocompress-debug-sections") {
2143        CmdArgs.push_back(Value.data());
2144      } else if (Value == "-mrelax-relocations=yes" ||
2145                 Value == "--mrelax-relocations=yes") {
2146        UseRelaxRelocations = true;
2147      } else if (Value == "-mrelax-relocations=no" ||
2148                 Value == "--mrelax-relocations=no") {
2149        UseRelaxRelocations = false;
2150      } else if (Value.startswith("-I")) {
2151        CmdArgs.push_back(Value.data());
2152        // We need to consume the next argument if the current arg is a plain
2153        // -I. The next arg will be the include directory.
2154        if (Value == "-I")
2155          TakeNextArg = true;
2156      } else if (Value.startswith("-gdwarf-")) {
2157        // "-gdwarf-N" options are not cc1as options.
2158        unsigned DwarfVersion = DwarfVersionNum(Value);
2159        if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2160          CmdArgs.push_back(Value.data());
2161        } else {
2162          RenderDebugEnablingArgs(Args, CmdArgs,
2163                                  codegenoptions::LimitedDebugInfo,
2164                                  DwarfVersion, llvm::DebuggerKind::Default);
2165        }
2166      } else if (Value.startswith("-mcpu") || Value.startswith("-mfpu") ||
2167                 Value.startswith("-mhwdiv") || Value.startswith("-march")) {
2168        // Do nothing, we'll validate it later.
2169      } else if (Value == "-defsym") {
2170          if (A->getNumValues() != 2) {
2171            D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2172            break;
2173          }
2174          const char *S = A->getValue(1);
2175          auto Pair = StringRef(S).split('=');
2176          auto Sym = Pair.first;
2177          auto SVal = Pair.second;
2178
2179          if (Sym.empty() || SVal.empty()) {
2180            D.Diag(diag::err_drv_defsym_invalid_format) << S;
2181            break;
2182          }
2183          int64_t IVal;
2184          if (SVal.getAsInteger(0, IVal)) {
2185            D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2186            break;
2187          }
2188          CmdArgs.push_back(Value.data());
2189          TakeNextArg = true;
2190      } else if (Value == "-fdebug-compilation-dir") {
2191        CmdArgs.push_back("-fdebug-compilation-dir");
2192        TakeNextArg = true;
2193      } else {
2194        D.Diag(diag::err_drv_unsupported_option_argument)
2195            << A->getOption().getName() << Value;
2196      }
2197    }
2198  }
2199  if (UseRelaxRelocations)
2200    CmdArgs.push_back("--mrelax-relocations");
2201  if (UseNoExecStack)
2202    CmdArgs.push_back("-mnoexecstack");
2203  if (MipsTargetFeature != nullptr) {
2204    CmdArgs.push_back("-target-feature");
2205    CmdArgs.push_back(MipsTargetFeature);
2206  }
2207
2208  // forward -fembed-bitcode to assmebler
2209  if (C.getDriver().embedBitcodeEnabled() ||
2210      C.getDriver().embedBitcodeMarkerOnly())
2211    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2212}
2213
2214static void RenderFloatingPointOptions(const ToolChain &TCconst Driver &D,
2215                                       bool OFastEnabledconst ArgList &Args,
2216                                       ArgStringList &CmdArgs) {
2217  // Handle various floating point optimization flags, mapping them to the
2218  // appropriate LLVM code generation flags. This is complicated by several
2219  // "umbrella" flags, so we do this by stepping through the flags incrementally
2220  // adjusting what we think is enabled/disabled, then at the end setting the
2221  // LLVM flags based on the final state.
2222  bool HonorINFs = true;
2223  bool HonorNaNs = true;
2224  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2225  bool MathErrno = TC.IsMathErrnoDefault();
2226  bool AssociativeMath = false;
2227  bool ReciprocalMath = false;
2228  bool SignedZeros = true;
2229  bool TrappingMath = true;
2230  StringRef DenormalFPMath = "";
2231  StringRef FPContract = "";
2232
2233  if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2234    CmdArgs.push_back("-mlimit-float-precision");
2235    CmdArgs.push_back(A->getValue());
2236  }
2237
2238  for (const Arg *A : Args) {
2239    switch (A->getOption().getID()) {
2240    // If this isn't an FP option skip the claim below
2241    defaultcontinue;
2242
2243    // Options controlling individual features
2244    case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2245    case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2246    case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2247    case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2248    case options::OPT_fmath_errno:          MathErrno = true;         break;
2249    case options::OPT_fno_math_errno:       MathErrno = false;        break;
2250    case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2251    case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2252    case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2253    case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2254    case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2255    case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2256    case options::OPT_ftrapping_math:       TrappingMath = true;      break;
2257    case options::OPT_fno_trapping_math:    TrappingMath = false;     break;
2258
2259    case options::OPT_fdenormal_fp_math_EQ:
2260      DenormalFPMath = A->getValue();
2261      break;
2262
2263    // Validate and pass through -fp-contract option.
2264    case options::OPT_ffp_contract: {
2265      StringRef Val = A->getValue();
2266      if (Val == "fast" || Val == "on" || Val == "off")
2267        FPContract = Val;
2268      else
2269        D.Diag(diag::err_drv_unsupported_option_argument)
2270            << A->getOption().getName() << Val;
2271      break;
2272    }
2273
2274    case options::OPT_ffinite_math_only:
2275      HonorINFs = false;
2276      HonorNaNs = false;
2277      break;
2278    case options::OPT_fno_finite_math_only:
2279      HonorINFs = true;
2280      HonorNaNs = true;
2281      break;
2282
2283    case options::OPT_funsafe_math_optimizations:
2284      AssociativeMath = true;
2285      ReciprocalMath = true;
2286      SignedZeros = false;
2287      TrappingMath = false;
2288      break;
2289    case options::OPT_fno_unsafe_math_optimizations:
2290      AssociativeMath = false;
2291      ReciprocalMath = false;
2292      SignedZeros = true;
2293      TrappingMath = true;
2294      // -fno_unsafe_math_optimizations restores default denormal handling
2295      DenormalFPMath = "";
2296      break;
2297
2298    case options::OPT_Ofast:
2299      // If -Ofast is the optimization level, then -ffast-math should be enabled
2300      if (!OFastEnabled)
2301        continue;
2302      LLVM_FALLTHROUGH;
2303    case options::OPT_ffast_math:
2304      HonorINFs = false;
2305      HonorNaNs = false;
2306      MathErrno = false;
2307      AssociativeMath = true;
2308      ReciprocalMath = true;
2309      SignedZeros = false;
2310      TrappingMath = false;
2311      // If fast-math is set then set the fp-contract mode to fast.
2312      FPContract = "fast";
2313      break;
2314    case options::OPT_fno_fast_math:
2315      HonorINFs = true;
2316      HonorNaNs = true;
2317      // Turning on -ffast-math (with either flag) removes the need for
2318      // MathErrno. However, turning *off* -ffast-math merely restores the
2319      // toolchain default (which may be false).
2320      MathErrno = TC.IsMathErrnoDefault();
2321      AssociativeMath = false;
2322      ReciprocalMath = false;
2323      SignedZeros = true;
2324      TrappingMath = true;
2325      // -fno_fast_math restores default denormal and fpcontract handling
2326      DenormalFPMath = "";
2327      FPContract = "";
2328      break;
2329    }
2330
2331    // If we handled this option claim it
2332    A->claim();
2333  }
2334
2335  if (!HonorINFs)
2336    CmdArgs.push_back("-menable-no-infs");
2337
2338  if (!HonorNaNs)
2339    CmdArgs.push_back("-menable-no-nans");
2340
2341  if (MathErrno)
2342    CmdArgs.push_back("-fmath-errno");
2343
2344  if (!MathErrno && AssociativeMath && ReciprocalMath && !SignedZeros &&
2345      !TrappingMath)
2346    CmdArgs.push_back("-menable-unsafe-fp-math");
2347
2348  if (!SignedZeros)
2349    CmdArgs.push_back("-fno-signed-zeros");
2350
2351  if (AssociativeMath && !SignedZeros && !TrappingMath)
2352    CmdArgs.push_back("-mreassociate");
2353
2354  if (ReciprocalMath)
2355    CmdArgs.push_back("-freciprocal-math");
2356
2357  if (!TrappingMath)
2358    CmdArgs.push_back("-fno-trapping-math");
2359
2360  if (!DenormalFPMath.empty())
2361    CmdArgs.push_back(
2362        Args.MakeArgString("-fdenormal-fp-math=" + DenormalFPMath));
2363
2364  if (!FPContract.empty())
2365    CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2366
2367  ParseMRecip(D, Args, CmdArgs);
2368
2369  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2370  // individual features enabled by -ffast-math instead of the option itself as
2371  // that's consistent with gcc's behaviour.
2372  if (!HonorINFs && !HonorNaNs && !MathErrno && AssociativeMath &&
2373      ReciprocalMath && !SignedZeros && !TrappingMath)
2374    CmdArgs.push_back("-ffast-math");
2375
2376  // Handle __FINITE_MATH_ONLY__ similarly.
2377  if (!HonorINFs && !HonorNaNs)
2378    CmdArgs.push_back("-ffinite-math-only");
2379
2380  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2381    CmdArgs.push_back("-mfpmath");
2382    CmdArgs.push_back(A->getValue());
2383  }
2384
2385  // Disable a codegen optimization for floating-point casts.
2386  if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2387                   options::OPT_fstrict_float_cast_overflow, false))
2388    CmdArgs.push_back("-fno-strict-float-cast-overflow");
2389}
2390
2391static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2392                                  const llvm::Triple &Triple,
2393                                  const InputInfo &Input) {
2394  // Enable region store model by default.
2395  CmdArgs.push_back("-analyzer-store=region");
2396
2397  // Treat blocks as analysis entry points.
2398  CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2399
2400  // Add default argument set.
2401  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2402    CmdArgs.push_back("-analyzer-checker=core");
2403    CmdArgs.push_back("-analyzer-checker=apiModeling");
2404
2405    if (!Triple.isWindowsMSVCEnvironment()) {
2406      CmdArgs.push_back("-analyzer-checker=unix");
2407    } else {
2408      // Enable "unix" checkers that also work on Windows.
2409      CmdArgs.push_back("-analyzer-checker=unix.API");
2410      CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2411      CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2412      CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2413      CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2414      CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2415    }
2416
2417    // Disable some unix checkers for PS4.
2418    if (Triple.isPS4CPU()) {
2419      CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2420      CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2421    }
2422
2423    if (Triple.isOSDarwin())
2424      CmdArgs.push_back("-analyzer-checker=osx");
2425
2426    CmdArgs.push_back("-analyzer-checker=deadcode");
2427
2428    if (types::isCXX(Input.getType()))
2429      CmdArgs.push_back("-analyzer-checker=cplusplus");
2430
2431    if (!Triple.isPS4CPU()) {
2432      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2433      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2434      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2435      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2436      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2437      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2438    }
2439
2440    // Default nullability checks.
2441    CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2442    CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2443  }
2444
2445  // Set the output format. The default is plist, for (lame) historical reasons.
2446  CmdArgs.push_back("-analyzer-output");
2447  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2448    CmdArgs.push_back(A->getValue());
2449  else
2450    CmdArgs.push_back("plist");
2451
2452  // Disable the presentation of standard compiler warnings when using
2453  // --analyze.  We only want to show static analyzer diagnostics or frontend
2454  // errors.
2455  CmdArgs.push_back("-w");
2456
2457  // Add -Xanalyzer arguments when running as analyzer.
2458  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2459}
2460
2461static void RenderSSPOptions(const ToolChain &TCconst ArgList &Args,
2462                             ArgStringList &CmdArgsbool KernelOrKext) {
2463  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2464
2465  // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2466  // doesn't even have a stack!
2467  if (EffectiveTriple.isNVPTX())
2468    return;
2469
2470  // -stack-protector=0 is default.
2471  unsigned StackProtectorLevel = 0;
2472  unsigned DefaultStackProtectorLevel =
2473      TC.GetDefaultStackProtectorLevel(KernelOrKext);
2474
2475  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2476                               options::OPT_fstack_protector_all,
2477                               options::OPT_fstack_protector_strong,
2478                               options::OPT_fstack_protector)) {
2479    if (A->getOption().matches(options::OPT_fstack_protector))
2480      StackProtectorLevel =
2481          std::max<unsigned>(LangOptions::SSPOnDefaultStackProtectorLevel);
2482    else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2483      StackProtectorLevel = LangOptions::SSPStrong;
2484    else if (A->getOption().matches(options::OPT_fstack_protector_all))
2485      StackProtectorLevel = LangOptions::SSPReq;
2486  } else {
2487    StackProtectorLevel = DefaultStackProtectorLevel;
2488  }
2489
2490  if (StackProtectorLevel) {
2491    CmdArgs.push_back("-stack-protector");
2492    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2493  }
2494
2495  // --param ssp-buffer-size=
2496  for (const Arg *A : Args.filtered(options::OPT__param)) {
2497    StringRef Str(A->getValue());
2498    if (Str.startswith("ssp-buffer-size=")) {
2499      if (StackProtectorLevel) {
2500        CmdArgs.push_back("-stack-protector-buffer-size");
2501        // FIXME: Verify the argument is a valid integer.
2502        CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2503      }
2504      A->claim();
2505    }
2506  }
2507}
2508
2509static void RenderTrivialAutoVarInitOptions(const Driver &D,
2510                                            const ToolChain &TC,
2511                                            const ArgList &Args,
2512                                            ArgStringList &CmdArgs) {
2513  auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
2514  StringRef TrivialAutoVarInit = "";
2515
2516  for (const Arg *A : Args) {
2517    switch (A->getOption().getID()) {
2518    default:
2519      continue;
2520    case options::OPT_ftrivial_auto_var_init: {
2521      A->claim();
2522      StringRef Val = A->getValue();
2523      if (Val == "uninitialized" || Val == "zero" || Val == "pattern")
2524        TrivialAutoVarInit = Val;
2525      else
2526        D.Diag(diag::err_drv_unsupported_option_argument)
2527            << A->getOption().getName() << Val;
2528      break;
2529    }
2530    }
2531  }
2532
2533  if (TrivialAutoVarInit.empty())
2534    switch (DefaultTrivialAutoVarInit) {
2535    case LangOptions::TrivialAutoVarInitKind::Uninitialized:
2536      break;
2537    case LangOptions::TrivialAutoVarInitKind::Pattern:
2538      TrivialAutoVarInit = "pattern";
2539      break;
2540    case LangOptions::TrivialAutoVarInitKind::Zero:
2541      TrivialAutoVarInit = "zero";
2542      break;
2543    }
2544
2545  if (!TrivialAutoVarInit.empty()) {
2546    if (TrivialAutoVarInit == "zero" && !Args.hasArg(options::OPT_enable_trivial_var_init_zero))
2547      D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
2548    CmdArgs.push_back(
2549        Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
2550  }
2551}
2552
2553static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
2554  const unsigned ForwardedArguments[] = {
2555      options::OPT_cl_opt_disable,
2556      options::OPT_cl_strict_aliasing,
2557      options::OPT_cl_single_precision_constant,
2558      options::OPT_cl_finite_math_only,
2559      options::OPT_cl_kernel_arg_info,
2560      options::OPT_cl_unsafe_math_optimizations,
2561      options::OPT_cl_fast_relaxed_math,
2562      options::OPT_cl_mad_enable,
2563      options::OPT_cl_no_signed_zeros,
2564      options::OPT_cl_denorms_are_zero,
2565      options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
2566      options::OPT_cl_uniform_work_group_size
2567  };
2568
2569  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
2570    std::string CLStdStr = std::string("-cl-std=") + A->getValue();
2571    CmdArgs.push_back(Args.MakeArgString(CLStdStr));
2572  }
2573
2574  for (const auto &Arg : ForwardedArguments)
2575    if (const auto *A = Args.getLastArg(Arg))
2576      CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
2577}
2578
2579static void RenderARCMigrateToolOptions(const Driver &Dconst ArgList &Args,
2580                                        ArgStringList &CmdArgs) {
2581  bool ARCMTEnabled = false;
2582  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
2583    if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
2584                                       options::OPT_ccc_arcmt_modify,
2585                                       options::OPT_ccc_arcmt_migrate)) {
2586      ARCMTEnabled = true;
2587      switch (A->getOption().getID()) {
2588      default: llvm_unreachable("missed a case");
2589      case options::OPT_ccc_arcmt_check:
2590        CmdArgs.push_back("-arcmt-check");
2591        break;
2592      case options::OPT_ccc_arcmt_modify:
2593        CmdArgs.push_back("-arcmt-modify");
2594        break;
2595      case options::OPT_ccc_arcmt_migrate:
2596        CmdArgs.push_back("-arcmt-migrate");
2597        CmdArgs.push_back("-mt-migrate-directory");
2598        CmdArgs.push_back(A->getValue());
2599
2600        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
2601        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
2602        break;
2603      }
2604    }
2605  } else {
2606    Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
2607    Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
2608    Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
2609  }
2610
2611  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
2612    if (ARCMTEnabled)
2613      D.Diag(diag::err_drv_argument_not_allowed_with)
2614          << A->getAsString(Args) << "-ccc-arcmt-migrate";
2615
2616    CmdArgs.push_back("-mt-migrate-directory");
2617    CmdArgs.push_back(A->getValue());
2618
2619    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
2620                     options::OPT_objcmt_migrate_subscripting,
2621                     options::OPT_objcmt_migrate_property)) {
2622      // None specified, means enable them all.
2623      CmdArgs.push_back("-objcmt-migrate-literals");
2624      CmdArgs.push_back("-objcmt-migrate-subscripting");
2625      CmdArgs.push_back("-objcmt-migrate-property");
2626    } else {
2627      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2628      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2629      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2630    }
2631  } else {
2632    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
2633    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
2634    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
2635    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
2636    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
2637    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
2638    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
2639    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
2640    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
2641    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
2642    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
2643    Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
2644    Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
2645    Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
2646    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
2647    Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
2648  }
2649}
2650
2651static void RenderBuiltinOptions(const ToolChain &TCconst llvm::Triple &T,
2652                                 const ArgList &Args, ArgStringList &CmdArgs) {
2653  // -fbuiltin is default unless -mkernel is used.
2654  bool UseBuiltins =
2655      Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
2656                   !Args.hasArg(options::OPT_mkernel));
2657  if (!UseBuiltins)
2658    CmdArgs.push_back("-fno-builtin");
2659
2660  // -ffreestanding implies -fno-builtin.
2661  if (Args.hasArg(options::OPT_ffreestanding))
2662    UseBuiltins = false;
2663
2664  // Process the -fno-builtin-* options.
2665  for (const auto &Arg : Args) {
2666    const Option &O = Arg->getOption();
2667    if (!O.matches(options::OPT_fno_builtin_))
2668      continue;
2669
2670    Arg->claim();
2671
2672    // If -fno-builtin is specified, then there's no need to pass the option to
2673    // the frontend.
2674    if (!UseBuiltins)
2675      continue;
2676
2677    StringRef FuncName = Arg->getValue();
2678    CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
2679  }
2680
2681  // le32-specific flags:
2682  //  -fno-math-builtin: clang should not convert math builtins to intrinsics
2683  //                     by default.
2684  if (TC.getArch() == llvm::Triple::le32)
2685    CmdArgs.push_back("-fno-math-builtin");
2686}
2687
2688void Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
2689  llvm::sys::path::system_temp_directory(/*erasedOnReboot=*/false, Result);
2690  llvm::sys::path::append(Result, "org.llvm.clang.");
2691  appendUserToPath(Result);
2692  llvm::sys::path::append(Result, "ModuleCache");
2693}
2694
2695static void RenderModulesOptions(Compilation &Cconst Driver &D,
2696                                 const ArgList &Argsconst InputInfo &Input,
2697                                 const InputInfo &Output,
2698                                 ArgStringList &CmdArgsbool &HaveModules) {
2699  // -fmodules enables the use of precompiled modules (off by default).
2700  // Users can pass -fno-cxx-modules to turn off modules support for
2701  // C++/Objective-C++ programs.
2702  bool HaveClangModules = false;
2703  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
2704    bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
2705                                     options::OPT_fno_cxx_modules, true);
2706    if (AllowedInCXX || !types::isCXX(Input.getType())) {
2707      CmdArgs.push_back("-fmodules");
2708      HaveClangModules = true;
2709    }
2710  }
2711
2712  HaveModules = HaveClangModules;
2713  if (Args.hasArg(options::OPT_fmodules_ts)) {
2714    CmdArgs.push_back("-fmodules-ts");
2715    HaveModules = true;
2716  }
2717
2718  // -fmodule-maps enables implicit reading of module map files. By default,
2719  // this is enabled if we are using Clang's flavor of precompiled modules.
2720  if (Args.hasFlag(options::OPT_fimplicit_module_maps,
2721                   options::OPT_fno_implicit_module_maps, HaveClangModules))
2722    CmdArgs.push_back("-fimplicit-module-maps");
2723
2724  // -fmodules-decluse checks that modules used are declared so (off by default)
2725  if (Args.hasFlag(options::OPT_fmodules_decluse,
2726                   options::OPT_fno_modules_decluse, false))
2727    CmdArgs.push_back("-fmodules-decluse");
2728
2729  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
2730  // all #included headers are part of modules.
2731  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
2732                   options::OPT_fno_modules_strict_decluse, false))
2733    CmdArgs.push_back("-fmodules-strict-decluse");
2734
2735  // -fno-implicit-modules turns off implicitly compiling modules on demand.
2736  bool ImplicitModules = false;
2737  if (!Args.hasFlag(options::OPT_fimplicit_modules,
2738                    options::OPT_fno_implicit_modules, HaveClangModules)) {
2739    if (HaveModules)
2740      CmdArgs.push_back("-fno-implicit-modules");
2741  } else if (HaveModules) {
2742    ImplicitModules = true;
2743    // -fmodule-cache-path specifies where our implicitly-built module files
2744    // should be written.
2745    SmallString<128Path;
2746    if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
2747      Path = A->getValue();
2748
2749    if (C.isForDiagnostics()) {
2750      // When generating crash reports, we want to emit the modules along with
2751      // the reproduction sources, so we ignore any provided module path.
2752      Path = Output.getFilename();
2753      llvm::sys::path::replace_extension(Path, ".cache");
2754      llvm::sys::path::append(Path, "modules");
2755    } else if (Path.empty()) {
2756      // No module path was provided: use the default.
2757      Driver::getDefaultModuleCachePath(Path);
2758    }
2759
2760    const char Arg[] = "-fmodules-cache-path=";
2761    Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
2762    CmdArgs.push_back(Args.MakeArgString(Path));
2763  }
2764
2765  if (HaveModules) {
2766    // -fprebuilt-module-path specifies where to load the prebuilt module files.
2767    for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
2768      CmdArgs.push_back(Args.MakeArgString(
2769          std::string("-fprebuilt-module-path=") + A->getValue()));
2770      A->claim();
2771    }
2772  }
2773
2774  // -fmodule-name specifies the module that is currently being built (or
2775  // used for header checking by -fmodule-maps).
2776  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
2777
2778  // -fmodule-map-file can be used to specify files containing module
2779  // definitions.
2780  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
2781
2782  // -fbuiltin-module-map can be used to load the clang
2783  // builtin headers modulemap file.
2784  if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
2785    SmallString<128BuiltinModuleMap(D.ResourceDir);
2786    llvm::sys::path::append(BuiltinModuleMap, "include");
2787    llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
2788    if (llvm::sys::fs::exists(BuiltinModuleMap))
2789      CmdArgs.push_back(
2790          Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
2791  }
2792
2793  // The -fmodule-file=<name>=<file> form specifies the mapping of module
2794  // names to precompiled module files (the module is loaded only if used).
2795  // The -fmodule-file=<file> form can be used to unconditionally load
2796  // precompiled module files (whether used or not).
2797  if (HaveModules)
2798    Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
2799  else
2800    Args.ClaimAllArgs(options::OPT_fmodule_file);
2801
2802  // When building modules and generating crashdumps, we need to dump a module
2803  // dependency VFS alongside the output.
2804  if (HaveClangModules && C.isForDiagnostics()) {
2805    SmallString<128VFSDir(Output.getFilename());
2806    llvm::sys::path::replace_extension(VFSDir, ".cache");
2807    // Add the cache directory as a temp so the crash diagnostics pick it up.
2808    C.addTempFile(Args.MakeArgString(VFSDir));
2809
2810    llvm::sys::path::append(VFSDir, "vfs");
2811    CmdArgs.push_back("-module-dependency-dir");
2812    CmdArgs.push_back(Args.MakeArgString(VFSDir));
2813  }
2814
2815  if (HaveClangModules)
2816    Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
2817
2818  // Pass through all -fmodules-ignore-macro arguments.
2819  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
2820  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
2821  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
2822
2823  Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
2824
2825  if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
2826    if (Args.hasArg(options::OPT_fbuild_session_timestamp))
2827      D.Diag(diag::err_drv_argument_not_allowed_with)
2828          << A->getAsString(Args) << "-fbuild-session-timestamp";
2829
2830    llvm::sys::fs::file_status Status;
2831    if (llvm::sys::fs::status(A->getValue(), Status))
2832      D.Diag(diag::err_drv_no_such_file) << A->getValue();
2833    CmdArgs.push_back(
2834        Args.MakeArgString("-fbuild-session-timestamp=" +
2835                           Twine((uint64_t)Status.getLastModificationTime()
2836                                     .time_since_epoch()
2837                                     .count())));
2838  }
2839
2840  if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
2841    if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
2842                         options::OPT_fbuild_session_file))
2843      D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
2844
2845    Args.AddLastArg(CmdArgs,
2846                    options::OPT_fmodules_validate_once_per_build_session);
2847  }
2848
2849  if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
2850                   options::OPT_fno_modules_validate_system_headers,
2851                   ImplicitModules))
2852    CmdArgs.push_back("-fmodules-validate-system-headers");
2853
2854  Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
2855}
2856
2857static void RenderCharacterOptions(const ArgList &Argsconst llvm::Triple &T,
2858                                   ArgStringList &CmdArgs) {
2859  // -fsigned-char is default.
2860  if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
2861                                     options::OPT_fno_signed_char,
2862                                     options::OPT_funsigned_char,
2863                                     options::OPT_fno_unsigned_char)) {
2864    if (A->getOption().matches(options::OPT_funsigned_char) ||
2865        A->getOption().matches(options::OPT_fno_signed_char)) {
2866      CmdArgs.push_back("-fno-signed-char");
2867    }
2868  } else if (!isSignedCharDefault(T)) {
2869    CmdArgs.push_back("-fno-signed-char");
2870  }
2871
2872  // The default depends on the language standard.
2873  if (const Arg *A =
2874          Args.getLastArg(options::OPT_fchar8__t, options::OPT_fno_char8__t))
2875    A->render(Args, CmdArgs);
2876
2877  if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
2878                                     options::OPT_fno_short_wchar)) {
2879    if (A->getOption().matches(options::OPT_fshort_wchar)) {
2880      CmdArgs.push_back("-fwchar-type=short");
2881      CmdArgs.push_back("-fno-signed-wchar");
2882    } else {
2883      bool IsARM = T.isARM() || T.isThumb() || T.isAArch64();
2884      CmdArgs.push_back("-fwchar-type=int");
2885      if (IsARM && !(T.isOSWindows() || T.isOSNetBSD() ||
2886                     T.isOSOpenBSD()))
2887        CmdArgs.push_back("-fno-signed-wchar");
2888      else
2889        CmdArgs.push_back("-fsigned-wchar");
2890    }
2891  }
2892}
2893
2894static void RenderObjCOptions(const ToolChain &TCconst Driver &D,
2895                              const llvm::Triple &Tconst ArgList &Args,
2896                              ObjCRuntime &Runtimebool InferCovariantReturns,
2897                              const InputInfo &Input, ArgStringList &CmdArgs) {
2898  const llvm::Triple::ArchType Arch = TC.getArch();
2899
2900  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
2901  // is the default. Except for deployment target of 10.5, next runtime is
2902  // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
2903  if (Runtime.isNonFragile()) {
2904    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
2905                      options::OPT_fno_objc_legacy_dispatch,
2906                      Runtime.isLegacyDispatchDefaultForArch(Arch))) {
2907      if (TC.UseObjCMixedDispatch())
2908        CmdArgs.push_back("-fobjc-dispatch-method=mixed");
2909      else
2910        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
2911    }
2912  }
2913
2914  // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
2915  // to do Array/Dictionary subscripting by default.
2916  if (Arch == llvm::Triple::x86 && T.isMacOSX() &&
2917      Runtime.getKind() == ObjCRuntime::FragileMacOSX && Runtime.isNeXTFamily())
2918    CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
2919
2920  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
2921  // NOTE: This logic is duplicated in ToolChains.cpp.
2922  if (isObjCAutoRefCount(Args)) {
2923    TC.CheckObjCARC();
2924
2925    CmdArgs.push_back("-fobjc-arc");
2926
2927    // FIXME: It seems like this entire block, and several around it should be
2928    // wrapped in isObjC, but for now we just use it here as this is where it
2929    // was being used previously.
2930    if (types::isCXX(Input.getType()) && types::isObjC(Input.getType())) {
2931      if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
2932        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
2933      else
2934        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
2935    }
2936
2937    // Allow the user to enable full exceptions code emission.
2938    // We default off for Objective-C, on for Objective-C++.
2939    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
2940                     options::OPT_fno_objc_arc_exceptions,
2941                     /*default=*/types::isCXX(Input.getType())))
2942      CmdArgs.push_back("-fobjc-arc-exceptions");
2943  }
2944
2945  // Silence warning for full exception code emission options when explicitly
2946  // set to use no ARC.
2947  if (Args.hasArg(options::OPT_fno_objc_arc)) {
2948    Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
2949    Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
2950  }
2951
2952  // Allow the user to control whether messages can be converted to runtime
2953  // functions.
2954  if (types::isObjC(Input.getType())) {
2955    auto *Arg = Args.getLastArg(
2956        options::OPT_fobjc_convert_messages_to_runtime_calls,
2957        options::OPT_fno_objc_convert_messages_to_runtime_calls);
2958    if (Arg &&
2959        Arg->getOption().matches(
2960            options::OPT_fno_objc_convert_messages_to_runtime_calls))
2961      CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
2962  }
2963
2964  // -fobjc-infer-related-result-type is the default, except in the Objective-C
2965  // rewriter.
2966  if (InferCovariantReturns)
2967    CmdArgs.push_back("-fno-objc-infer-related-result-type");
2968
2969  // Pass down -fobjc-weak or -fno-objc-weak if present.
2970  if (types::isObjC(Input.getType())) {
2971    auto WeakArg =
2972        Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
2973    if (!WeakArg) {
2974      // nothing to do
2975    } else if (!Runtime.allowsWeak()) {
2976      if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
2977        D.Diag(diag::err_objc_weak_unsupported);
2978    } else {
2979      WeakArg->render(Args, CmdArgs);
2980    }
2981  }
2982}
2983
2984static void RenderDiagnosticsOptions(const Driver &Dconst ArgList &Args,
2985                                     ArgStringList &CmdArgs) {
2986  bool CaretDefault = true;
2987  bool ColumnDefault = true;
2988
2989  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
2990                                     options::OPT__SLASH_diagnostics_column,
2991                                     options::OPT__SLASH_diagnostics_caret)) {
2992    switch (A->getOption().getID()) {
2993    case options::OPT__SLASH_diagnostics_caret:
2994      CaretDefault = true;
2995      ColumnDefault = true;
2996      break;
2997    case options::OPT__SLASH_diagnostics_column:
2998      CaretDefault = false;
2999      ColumnDefault = true;
3000      break;
3001    case options::OPT__SLASH_diagnostics_classic:
3002      CaretDefault = false;
3003      ColumnDefault = false;
3004      break;
3005    }
3006  }
3007
3008  // -fcaret-diagnostics is default.
3009  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3010                    options::OPT_fno_caret_diagnostics, CaretDefault))
3011    CmdArgs.push_back("-fno-caret-diagnostics");
3012
3013  // -fdiagnostics-fixit-info is default, only pass non-default.
3014  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3015                    options::OPT_fno_diagnostics_fixit_info))
3016    CmdArgs.push_back("-fno-diagnostics-fixit-info");
3017
3018  // Enable -fdiagnostics-show-option by default.
3019  if (Args.hasFlag(options::OPT_fdiagnostics_show_option,
3020                   options::OPT_fno_diagnostics_show_option))
3021    CmdArgs.push_back("-fdiagnostics-show-option");
3022
3023  if (const Arg *A =
3024          Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3025    CmdArgs.push_back("-fdiagnostics-show-category");
3026    CmdArgs.push_back(A->getValue());
3027  }
3028
3029  if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3030                   options::OPT_fno_diagnostics_show_hotness, false))
3031    CmdArgs.push_back("-fdiagnostics-show-hotness");
3032
3033  if (const Arg *A =
3034          Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3035    std::string Opt =
3036        std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3037    CmdArgs.push_back(Args.MakeArgString(Opt));
3038  }
3039
3040  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3041    CmdArgs.push_back("-fdiagnostics-format");
3042    CmdArgs.push_back(A->getValue());
3043  }
3044
3045  if (const Arg *A = Args.getLastArg(
3046          options::OPT_fdiagnostics_show_note_include_stack,
3047          options::OPT_fno_diagnostics_show_note_include_stack)) {
3048    const Option &O = A->getOption();
3049    if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3050      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3051    else
3052      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3053  }
3054
3055  // Color diagnostics are parsed by the driver directly from argv and later
3056  // re-parsed to construct this job; claim any possible color diagnostic here
3057  // to avoid warn_drv_unused_argument and diagnose bad
3058  // OPT_fdiagnostics_color_EQ values.
3059  for (const Arg *A : Args) {
3060    const Option &O = A->getOption();
3061    if (!O.matches(options::OPT_fcolor_diagnostics) &&
3062        !O.matches(options::OPT_fdiagnostics_color) &&
3063        !O.matches(options::OPT_fno_color_diagnostics) &&
3064        !O.matches(options::OPT_fno_diagnostics_color) &&
3065        !O.matches(options::OPT_fdiagnostics_color_EQ))
3066      continue;
3067
3068    if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3069      StringRef Value(A->getValue());
3070      if (Value != "always" && Value != "never" && Value != "auto")
3071        D.Diag(diag::err_drv_clang_unsupported)
3072            << ("-fdiagnostics-color=" + Value).str();
3073    }
3074    A->claim();
3075  }
3076
3077  if (D.getDiags().getDiagnosticOptions().ShowColors)
3078    CmdArgs.push_back("-fcolor-diagnostics");
3079
3080  if (Args.hasArg(options::OPT_fansi_escape_codes))
3081    CmdArgs.push_back("-fansi-escape-codes");
3082
3083  if (!Args.hasFlag(options::OPT_fshow_source_location,
3084                    options::OPT_fno_show_source_location))
3085    CmdArgs.push_back("-fno-show-source-location");
3086
3087  if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3088    CmdArgs.push_back("-fdiagnostics-absolute-paths");
3089
3090  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3091                    ColumnDefault))
3092    CmdArgs.push_back("-fno-show-column");
3093
3094  if (!Args.hasFlag(options::OPT_fspell_checking,
3095                    options::OPT_fno_spell_checking))
3096    CmdArgs.push_back("-fno-spell-checking");
3097}
3098
3099enum class DwarfFissionKind { NoneSplitSingle };
3100
3101static DwarfFissionKind getDebugFissionKind(const Driver &D,
3102                                            const ArgList &ArgsArg *&Arg) {
3103  Arg =
3104      Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3105  if (!Arg)
3106    return DwarfFissionKind::None;
3107
3108  if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3109    return DwarfFissionKind::Split;
3110
3111  StringRef Value = Arg->getValue();
3112  if (Value == "split")
3113    return DwarfFissionKind::Split;
3114  if (Value == "single")
3115    return DwarfFissionKind::Single;
3116
3117  D.Diag(diag::err_drv_unsupported_option_argument)
3118      << Arg->getOption().getName() << Arg->getValue();
3119  return DwarfFissionKind::None;
3120}
3121
3122static void RenderDebugOptions(const ToolChain &TCconst Driver &D,
3123                               const llvm::Triple &Tconst ArgList &Args,
3124                               bool EmitCodeViewbool IsWindowsMSVC,
3125                               ArgStringList &CmdArgs,
3126                               codegenoptions::DebugInfoKind &DebugInfoKind,
3127                               DwarfFissionKind &DwarfFission) {
3128  if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3129                   options::OPT_fno_debug_info_for_profiling, false) &&
3130      checkDebugInfoOption(
3131          Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3132    CmdArgs.push_back("-fdebug-info-for-profiling");
3133
3134  // The 'g' groups options involve a somewhat intricate sequence of decisions
3135  // about what to pass from the driver to the frontend, but by the time they
3136  // reach cc1 they've been factored into three well-defined orthogonal choices:
3137  //  * what level of debug info to generate
3138  //  * what dwarf version to write
3139  //  * what debugger tuning to use
3140  // This avoids having to monkey around further in cc1 other than to disable
3141  // codeview if not running in a Windows environment. Perhaps even that
3142  // decision should be made in the driver as well though.
3143  unsigned DWARFVersion = 0;
3144  llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3145
3146  bool SplitDWARFInlining =
3147      Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3148                   options::OPT_fno_split_dwarf_inlining, true);
3149
3150  Args.ClaimAllArgs(options::OPT_g_Group);
3151
3152  ArgSplitDWARFArg;
3153  DwarfFission = getDebugFissionKind(DArgsSplitDWARFArg);
3154
3155  if (DwarfFission != DwarfFissionKind::None &&
3156      !checkDebugInfoOption(SplitDWARFArgArgsDTC)) {
3157    DwarfFission = DwarfFissionKind::None;
3158    SplitDWARFInlining = false;
3159  }
3160
3161  if (const Arg *A = Args.getLastArg(options::OPT_g_Group)) {
3162    if (checkDebugInfoOption(AArgsDTC)) {
3163      // If the last option explicitly specified a debug-info level, use it.
3164      if (A->getOption().matches(options::OPT_gN_Group)) {
3165        DebugInfoKind = DebugLevelToInfoKind(*A);
3166        // If you say "-gsplit-dwarf -gline-tables-only", -gsplit-dwarf loses.
3167        // But -gsplit-dwarf is not a g_group option, hence we have to check the
3168        // order explicitly. If -gsplit-dwarf wins, we fix DebugInfoKind later.
3169        // This gets a bit more complicated if you've disabled inline info in
3170        // the skeleton CUs (SplitDWARFInlining) - then there's value in
3171        // composing split-dwarf and line-tables-only, so let those compose
3172        // naturally in that case. And if you just turned off debug info,
3173        // (-gsplit-dwarf -g0) - do that.
3174        if (DwarfFission != DwarfFissionKind::None) {
3175          if (A->getIndex() > SplitDWARFArg->getIndex()) {
3176            if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3177                DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3178                (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3179                 SplitDWARFInlining))
3180              DwarfFission = DwarfFissionKind::None;
3181          } else if (SplitDWARFInlining)
3182            DebugInfoKind = codegenoptions::NoDebugInfo;
3183        }
3184      } else {
3185        // For any other 'g' option, use Limited.
3186        DebugInfoKind = codegenoptions::LimitedDebugInfo;
3187      }
3188    } else {
3189      DebugInfoKind = codegenoptions::LimitedDebugInfo;
3190    }
3191  }
3192
3193  // If a debugger tuning argument appeared, remember it.
3194  if (const Arg *A =
3195          Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3196    if (checkDebugInfoOption(AArgsDTC)) {
3197      if (A->getOption().matches(options::OPT_glldb))
3198        DebuggerTuning = llvm::DebuggerKind::LLDB;
3199      else if (A->getOption().matches(options::OPT_gsce))
3200        DebuggerTuning = llvm::DebuggerKind::SCE;
3201      else
3202        DebuggerTuning = llvm::DebuggerKind::GDB;
3203    }
3204  }
3205
3206  // If a -gdwarf argument appeared, remember it.
3207  if (const Arg *A =
3208          Args.getLastArg(options::OPT_gdwarf_2, options::OPT_gdwarf_3,
3209                          options::OPT_gdwarf_4, options::OPT_gdwarf_5))
3210    if (checkDebugInfoOption(A, Args, D, TC))
3211      DWARFVersion = DwarfVersionNum(A->getSpelling());
3212
3213  if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3214    if (checkDebugInfoOption(AArgsDTC))
3215      EmitCodeView = true;
3216  }
3217
3218  // If the user asked for debug info but did not explicitly specify -gcodeview
3219  // or -gdwarf, ask the toolchain for the default format.
3220  if (!EmitCodeView && DWARFVersion == 0 &&
3221      DebugInfoKind != codegenoptions::NoDebugInfo) {
3222    switch (TC.getDefaultDebugFormat()) {
3223    case codegenoptions::DIF_CodeView:
3224      EmitCodeView = true;
3225      break;
3226    case codegenoptions::DIF_DWARF:
3227      DWARFVersion = TC.GetDefaultDwarfVersion();
3228      break;
3229    }
3230  }
3231
3232  // -gline-directives-only supported only for the DWARF debug info.
3233  if (DWARFVersion == 0 && DebugInfoKind == codegenoptions::DebugDirectivesOnly)
3234    DebugInfoKind = codegenoptions::NoDebugInfo;
3235
3236  // We ignore flag -gstrict-dwarf for now.
3237  // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3238  Args.ClaimAllArgs(options::OPT_g_flags_Group);
3239
3240  // Column info is included by default for everything except SCE and
3241  // CodeView. Clang doesn't track end columns, just starting columns, which,
3242  // in theory, is fine for CodeView (and PDB).  In practice, however, the
3243  // Microsoft debuggers don't handle missing end columns well, so it's better
3244  // not to include any column info.
3245  if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3246    (void)checkDebugInfoOption(AArgsDTC);
3247  if (Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3248                   /*Default=*/!EmitCodeView &&
3249                       DebuggerTuning != llvm::DebuggerKind::SCE))
3250    CmdArgs.push_back("-dwarf-column-info");
3251
3252  // FIXME: Move backend command line options to the module.
3253  // If -gline-tables-only or -gline-directives-only is the last option it wins.
3254  if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3255    if (checkDebugInfoOption(AArgsDTC)) {
3256      if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3257          DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3258        DebugInfoKind = codegenoptions::LimitedDebugInfo;
3259        CmdArgs.push_back("-dwarf-ext-refs");
3260        CmdArgs.push_back("-fmodule-format=obj");
3261      }
3262    }
3263
3264  // -gsplit-dwarf should turn on -g and enable the backend dwarf
3265  // splitting and extraction.
3266  if (T.isOSBinFormatELF()) {
3267    if (!SplitDWARFInlining)
3268      CmdArgs.push_back("-fno-split-dwarf-inlining");
3269
3270    if (DwarfFission != DwarfFissionKind::None) {
3271      if (DebugInfoKind == codegenoptions::NoDebugInfo)
3272        DebugInfoKind = codegenoptions::LimitedDebugInfo;
3273
3274      if (DwarfFission == DwarfFissionKind::Single)
3275        CmdArgs.push_back("-enable-split-dwarf=single");
3276      else
3277        CmdArgs.push_back("-enable-split-dwarf");
3278    }
3279  }
3280
3281  // After we've dealt with all combinations of things that could
3282  // make DebugInfoKind be other than None or DebugLineTablesOnly,
3283  // figure out if we need to "upgrade" it to standalone debug info.
3284  // We parse these two '-f' options whether or not they will be used,
3285  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3286  bool NeedFullDebug = Args.hasFlag(options::OPT_fstandalone_debug,
3287                                    options::OPT_fno_standalone_debug,
3288                                    TC.GetDefaultStandaloneDebug());
3289  if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3290    (void)checkDebugInfoOption(AArgsDTC);
3291  if (DebugInfoKind == codegenoptions::LimitedDebugInfo && NeedFullDebug)
3292    DebugInfoKind = codegenoptions::FullDebugInfo;
3293
3294  if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3295                   false)) {
3296    // Source embedding is a vendor extension to DWARF v5. By now we have
3297    // checked if a DWARF version was stated explicitly, and have otherwise
3298    // fallen back to the target default, so if this is still not at least 5
3299    // we emit an error.
3300    const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3301    if (DWARFVersion < 5)
3302      D.Diag(diag::err_drv_argument_only_allowed_with)
3303          << A->getAsString(Args) << "-gdwarf-5";
3304    else if (checkDebugInfoOption(A, Args, D, TC))
3305      CmdArgs.push_back("-gembed-source");
3306  }
3307
3308  if (EmitCodeView) {
3309    CmdArgs.push_back("-gcodeview");
3310
3311    // Emit codeview type hashes if requested.
3312    if (Args.hasFlag(options::OPT_gcodeview_ghash,
3313                     options::OPT_gno_codeview_ghash, false)) {
3314      CmdArgs.push_back("-gcodeview-ghash");
3315    }
3316  }
3317
3318  // Adjust the debug info kind for the given toolchain.
3319  TC.adjustDebugInfoKind(DebugInfoKindArgs);
3320
3321  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3322                          DebuggerTuning);
3323
3324  // -fdebug-macro turns on macro debug info generation.
3325  if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3326                   false))
3327    if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3328                             D, TC))
3329      CmdArgs.push_back("-debug-info-macro");
3330
3331  // -ggnu-pubnames turns on gnu style pubnames in the backend.
3332  const auto *PubnamesArg =
3333      Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3334                      options::OPT_gpubnames, options::OPT_gno_pubnames);
3335  if (DwarfFission != DwarfFissionKind::None ||
3336      DebuggerTuning == llvm::DebuggerKind::LLDB ||
3337      (PubnamesArg && checkDebugInfoOption(PubnamesArg, Args, D, TC)))
3338    if (!PubnamesArg ||
3339        (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3340         !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3341      CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3342                                           options::OPT_gpubnames)
3343                            ? "-gpubnames"
3344                            : "-ggnu-pubnames");
3345
3346  if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3347                   options::OPT_fno_debug_ranges_base_address, false)) {
3348    CmdArgs.push_back("-fdebug-ranges-base-address");
3349  }
3350
3351  // -gdwarf-aranges turns on the emission of the aranges section in the
3352  // backend.
3353  // Always enabled for SCE tuning.
3354  bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3355  if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3356    NeedAranges = checkDebugInfoOption(AArgsDTC) || NeedAranges;
3357  if (NeedAranges) {
3358    CmdArgs.push_back("-mllvm");
3359    CmdArgs.push_back("-generate-arange-section");
3360  }
3361
3362  if (Args.hasFlag(options::OPT_fdebug_types_section,
3363                   options::OPT_fno_debug_types_section, false)) {
3364    if (!T.isOSBinFormatELF()) {
3365      D.Diag(diag::err_drv_unsupported_opt_for_target)
3366          << Args.getLastArg(options::OPT_fdebug_types_section)
3367                 ->getAsString(Args)
3368          << T.getTriple();
3369    } else if (checkDebugInfoOption(
3370                   Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3371                   TC)) {
3372      CmdArgs.push_back("-mllvm");
3373      CmdArgs.push_back("-generate-type-units");
3374    }
3375  }
3376
3377  // Decide how to render forward declarations of template instantiations.
3378  // SCE wants full descriptions, others just get them in the name.
3379  if (DebuggerTuning == llvm::DebuggerKind::SCE)
3380    CmdArgs.push_back("-debug-forward-template-params");
3381
3382  // Do we need to explicitly import anonymous namespaces into the parent
3383  // scope?
3384  if (DebuggerTuning == llvm::DebuggerKind::SCE)
3385    CmdArgs.push_back("-dwarf-explicit-import");
3386
3387  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3388}
3389
3390void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3391                         const InputInfo &Output, const InputInfoList &Inputs,
3392                         const ArgList &Args, const char *LinkingOutput) const {
3393  const auto &TC = getToolChain();
3394  const llvm::Triple &RawTriple = TC.getTriple();
3395  const llvm::Triple &Triple = TC.getEffectiveTriple();
3396  const std::string &TripleStr = Triple.getTriple();
3397
3398  bool KernelOrKext =
3399      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3400  const Driver &D = TC.getDriver();
3401  ArgStringList CmdArgs;
3402
3403  // Check number of inputs for sanity. We need at least one input.
3404   (0) . __assert_fail ("Inputs.size() >= 1 && \"Must have at least one input.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3404, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Inputs.size() >= 1 && "Must have at least one input.");
3405  // CUDA/HIP compilation may have multiple inputs (source file + results of
3406  // device-side compilations). OpenMP device jobs also take the host IR as a
3407  // second input. Module precompilation accepts a list of header files to
3408  // include as part of the module. All other jobs are expected to have exactly
3409  // one input.
3410  bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3411  bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3412  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3413  bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3414
3415  // A header module compilation doesn't have a main input file, so invent a
3416  // fake one as a placeholder.
3417  const char *ModuleName = [&]{
3418    auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3419    return ModuleNameArg ? ModuleNameArg->getValue() : "";
3420  }();
3421  InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
3422
3423  const InputInfo &Input =
3424      IsHeaderModulePrecompile ? HeaderModuleInput : Inputs[0];
3425
3426  InputInfoList ModuleHeaderInputs;
3427  const InputInfo *CudaDeviceInput = nullptr;
3428  const InputInfo *OpenMPDeviceInput = nullptr;
3429  for (const InputInfo &I : Inputs) {
3430    if (&I == &Input) {
3431      // This is the primary input.
3432    } else if (IsHeaderModulePrecompile &&
3433               types::getPrecompiledType(I.getType()) == types::TY_PCH) {
3434      types::ID Expected = HeaderModuleInput.getType();
3435      if (I.getType() != Expected) {
3436        D.Diag(diag::err_drv_module_header_wrong_kind)
3437            << I.getFilename() << types::getTypeName(I.getType())
3438            << types::getTypeName(Expected);
3439      }
3440      ModuleHeaderInputs.push_back(I);
3441    } else if ((IsCuda || IsHIP) && !CudaDeviceInput) {
3442      CudaDeviceInput = &I;
3443    } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3444      OpenMPDeviceInput = &I;
3445    } else {
3446      llvm_unreachable("unexpectedly given multiple inputs");
3447    }
3448  }
3449
3450  const llvm::Triple *AuxTriple = IsCuda ? TC.getAuxTriple() : nullptr;
3451  bool IsWindowsGNU = RawTriple.isWindowsGNUEnvironment();
3452  bool IsWindowsCygnus = RawTriple.isWindowsCygwinEnvironment();
3453  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3454  bool IsIAMCU = RawTriple.isOSIAMCU();
3455
3456  // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
3457  // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
3458  // Windows), we need to pass Windows-specific flags to cc1.
3459  if (IsCuda || IsHIP) {
3460    IsWindowsMSVC |= AuxTriple && AuxTriple->isWindowsMSVCEnvironment();
3461    IsWindowsGNU |= AuxTriple && AuxTriple->isWindowsGNUEnvironment();
3462    IsWindowsCygnus |= AuxTriple && AuxTriple->isWindowsCygwinEnvironment();
3463  }
3464
3465  // C++ is not supported for IAMCU.
3466  if (IsIAMCU && types::isCXX(Input.getType()))
3467    D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
3468
3469  // Invoke ourselves in -cc1 mode.
3470  //
3471  // FIXME: Implement custom jobs for internal actions.
3472  CmdArgs.push_back("-cc1");
3473
3474  // Add the "effective" target triple.
3475  CmdArgs.push_back("-triple");
3476  CmdArgs.push_back(Args.MakeArgString(TripleStr));
3477
3478  if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
3479    DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
3480    Args.ClaimAllArgs(options::OPT_MJ);
3481  }
3482
3483  if (IsCuda || IsHIP) {
3484    // We have to pass the triple of the host if compiling for a CUDA/HIP device
3485    // and vice-versa.
3486    std::string NormalizedTriple;
3487    if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
3488        JA.isDeviceOffloading(Action::OFK_HIP))
3489      NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
3490                             ->getTriple()
3491                             .normalize();
3492    else {
3493      // Host-side compilation.
3494      NormalizedTriple =
3495          (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
3496                  : C.getSingleOffloadToolChain<Action::OFK_HIP>())
3497              ->getTriple()
3498              .normalize();
3499      if (IsCuda) {
3500        // We need to figure out which CUDA version we're compiling for, as that
3501        // determines how we load and launch GPU kernels.
3502        auto *CTC = static_cast<const toolchains::CudaToolChain *>(
3503            C.getSingleOffloadToolChain<Action::OFK_Cuda>());
3504         (0) . __assert_fail ("CTC && \"Expected valid CUDA Toolchain.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3504, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(CTC && "Expected valid CUDA Toolchain.");
3505        if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
3506          CmdArgs.push_back(Args.MakeArgString(
3507              Twine("-target-sdk-version=") +
3508              CudaVersionToString(CTC->CudaInstallation.version())));
3509      }
3510    }
3511    CmdArgs.push_back("-aux-triple");
3512    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3513  }
3514
3515  if (IsOpenMPDevice) {
3516    // We have to pass the triple of the host if compiling for an OpenMP device.
3517    std::string NormalizedTriple =
3518        C.getSingleOffloadToolChain<Action::OFK_Host>()
3519            ->getTriple()
3520            .normalize();
3521    CmdArgs.push_back("-aux-triple");
3522    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
3523  }
3524
3525  if (Triple.isOSWindows() && (Triple.getArch() == llvm::Triple::arm ||
3526                               Triple.getArch() == llvm::Triple::thumb)) {
3527    unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
3528    unsigned Version;
3529    Triple.getArchName().substr(Offset).getAsInteger(10, Version);
3530    if (Version < 7)
3531      D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
3532                                                << TripleStr;
3533  }
3534
3535  // Push all default warning arguments that are specific to
3536  // the given target.  These come before user provided warning options
3537  // are provided.
3538  TC.addClangWarningOptions(CmdArgs);
3539
3540  // Select the appropriate action.
3541  RewriteKind rewriteKind = RK_None;
3542
3543  if (isa<AnalyzeJobAction>(JA)) {
3544     (0) . __assert_fail ("JA.getType() == types..TY_Plist && \"Invalid output type.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3544, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(JA.getType() == types::TY_Plist && "Invalid output type.");
3545    CmdArgs.push_back("-analyze");
3546  } else if (isa<MigrateJobAction>(JA)) {
3547    CmdArgs.push_back("-migrate");
3548  } else if (isa<PreprocessJobAction>(JA)) {
3549    if (Output.getType() == types::TY_Dependencies)
3550      CmdArgs.push_back("-Eonly");
3551    else {
3552      CmdArgs.push_back("-E");
3553      if (Args.hasArg(options::OPT_rewrite_objc) &&
3554          !Args.hasArg(options::OPT_g_Group))
3555        CmdArgs.push_back("-P");
3556    }
3557  } else if (isa<AssembleJobAction>(JA)) {
3558    CmdArgs.push_back("-emit-obj");
3559
3560    CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
3561
3562    // Also ignore explicit -force_cpusubtype_ALL option.
3563    (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
3564  } else if (isa<PrecompileJobAction>(JA)) {
3565    if (JA.getType() == types::TY_Nothing)
3566      CmdArgs.push_back("-fsyntax-only");
3567    else if (JA.getType() == types::TY_ModuleFile)
3568      CmdArgs.push_back(IsHeaderModulePrecompile
3569                            ? "-emit-header-module"
3570                            : "-emit-module-interface");
3571    else
3572      CmdArgs.push_back("-emit-pch");
3573  } else if (isa<VerifyPCHJobAction>(JA)) {
3574    CmdArgs.push_back("-verify-pch");
3575  } else {
3576     (0) . __assert_fail ("(isa(JA) || isa(JA)) && \"Invalid action for clang tool.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3577, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
3577 (0) . __assert_fail ("(isa(JA) || isa(JA)) && \"Invalid action for clang tool.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3577, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">           "Invalid action for clang tool.");
3578    if (JA.getType() == types::TY_Nothing) {
3579      CmdArgs.push_back("-fsyntax-only");
3580    } else if (JA.getType() == types::TY_LLVM_IR ||
3581               JA.getType() == types::TY_LTO_IR) {
3582      CmdArgs.push_back("-emit-llvm");
3583    } else if (JA.getType() == types::TY_LLVM_BC ||
3584               JA.getType() == types::TY_LTO_BC) {
3585      CmdArgs.push_back("-emit-llvm-bc");
3586    } else if (JA.getType() == types::TY_PP_Asm) {
3587      CmdArgs.push_back("-S");
3588    } else if (JA.getType() == types::TY_AST) {
3589      CmdArgs.push_back("-emit-pch");
3590    } else if (JA.getType() == types::TY_ModuleFile) {
3591      CmdArgs.push_back("-module-file-info");
3592    } else if (JA.getType() == types::TY_RewrittenObjC) {
3593      CmdArgs.push_back("-rewrite-objc");
3594      rewriteKind = RK_NonFragile;
3595    } else if (JA.getType() == types::TY_RewrittenLegacyObjC) {
3596      CmdArgs.push_back("-rewrite-objc");
3597      rewriteKind = RK_Fragile;
3598    } else {
3599       (0) . __assert_fail ("JA.getType() == types..TY_PP_Asm && \"Unexpected output type!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3599, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
3600    }
3601
3602    // Preserve use-list order by default when emitting bitcode, so that
3603    // loading the bitcode up in 'opt' or 'llc' and running passes gives the
3604    // same result as running passes here.  For LTO, we don't need to preserve
3605    // the use-list order, since serialization to bitcode is part of the flow.
3606    if (JA.getType() == types::TY_LLVM_BC)
3607      CmdArgs.push_back("-emit-llvm-uselists");
3608
3609    // Device-side jobs do not support LTO.
3610    bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
3611                                   JA.isDeviceOffloading(Action::OFK_Host));
3612
3613    if (D.isUsingLTO() && !isDeviceOffloadAction) {
3614      Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
3615
3616      // The Darwin and PS4 linkers currently use the legacy LTO API, which
3617      // does not support LTO unit features (CFI, whole program vtable opt)
3618      // under ThinLTO.
3619      if (!(RawTriple.isOSDarwin() || RawTriple.isPS4()) ||
3620          D.getLTOMode() == LTOK_Full)
3621        CmdArgs.push_back("-flto-unit");
3622    }
3623  }
3624
3625  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
3626    if (!types::isLLVMIR(Input.getType()))
3627      D.Diag(diag::err_drv_argument_only_allowed_with) << A->getAsString(Args)
3628                                                       << "-x ir";
3629    Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
3630  }
3631
3632  if (Args.getLastArg(options::OPT_save_temps_EQ))
3633    Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
3634
3635  // Embed-bitcode option.
3636  // Only white-listed flags below are allowed to be embedded.
3637  if (C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO() &&
3638      (isa<BackendJobAction>(JA) || isa<AssembleJobAction>(JA))) {
3639    // Add flags implied by -fembed-bitcode.
3640    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
3641    // Disable all llvm IR level optimizations.
3642    CmdArgs.push_back("-disable-llvm-passes");
3643
3644    // reject options that shouldn't be supported in bitcode
3645    // also reject kernel/kext
3646    static const constexpr unsigned kBitcodeOptionBlacklist[] = {
3647        options::OPT_mkernel,
3648        options::OPT_fapple_kext,
3649        options::OPT_ffunction_sections,
3650        options::OPT_fno_function_sections,
3651        options::OPT_fdata_sections,
3652        options::OPT_fno_data_sections,
3653        options::OPT_funique_section_names,
3654        options::OPT_fno_unique_section_names,
3655        options::OPT_mrestrict_it,
3656        options::OPT_mno_restrict_it,
3657        options::OPT_mstackrealign,
3658        options::OPT_mno_stackrealign,
3659        options::OPT_mstack_alignment,
3660        options::OPT_mcmodel_EQ,
3661        options::OPT_mlong_calls,
3662        options::OPT_mno_long_calls,
3663        options::OPT_ggnu_pubnames,
3664        options::OPT_gdwarf_aranges,
3665        options::OPT_fdebug_types_section,
3666        options::OPT_fno_debug_types_section,
3667        options::OPT_fdwarf_directory_asm,
3668        options::OPT_fno_dwarf_directory_asm,
3669        options::OPT_mrelax_all,
3670        options::OPT_mno_relax_all,
3671        options::OPT_ftrap_function_EQ,
3672        options::OPT_ffixed_r9,
3673        options::OPT_mfix_cortex_a53_835769,
3674        options::OPT_mno_fix_cortex_a53_835769,
3675        options::OPT_ffixed_x18,
3676        options::OPT_mglobal_merge,
3677        options::OPT_mno_global_merge,
3678        options::OPT_mred_zone,
3679        options::OPT_mno_red_zone,
3680        options::OPT_Wa_COMMA,
3681        options::OPT_Xassembler,
3682        options::OPT_mllvm,
3683    };
3684    for (const auto &A : Args)
3685      if (std::find(std::begin(kBitcodeOptionBlacklist),
3686                    std::end(kBitcodeOptionBlacklist),
3687                    A->getOption().getID()) !=
3688          std::end(kBitcodeOptionBlacklist))
3689        D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
3690
3691    // Render the CodeGen options that need to be passed.
3692    if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3693                      options::OPT_fno_optimize_sibling_calls))
3694      CmdArgs.push_back("-mdisable-tail-calls");
3695
3696    RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
3697                               CmdArgs);
3698
3699    // Render ABI arguments
3700    switch (TC.getArch()) {
3701    defaultbreak;
3702    case llvm::Triple::arm:
3703    case llvm::Triple::armeb:
3704    case llvm::Triple::thumbeb:
3705      RenderARMABI(Triple, Args, CmdArgs);
3706      break;
3707    case llvm::Triple::aarch64:
3708    case llvm::Triple::aarch64_be:
3709      RenderAArch64ABI(Triple, Args, CmdArgs);
3710      break;
3711    }
3712
3713    // Optimization level for CodeGen.
3714    if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
3715      if (A->getOption().matches(options::OPT_O4)) {
3716        CmdArgs.push_back("-O3");
3717        D.Diag(diag::warn_O4_is_O3);
3718      } else {
3719        A->render(Args, CmdArgs);
3720      }
3721    }
3722
3723    // Input/Output file.
3724    if (Output.getType() == types::TY_Dependencies) {
3725      // Handled with other dependency code.
3726    } else if (Output.isFilename()) {
3727      CmdArgs.push_back("-o");
3728      CmdArgs.push_back(Output.getFilename());
3729    } else {
3730       (0) . __assert_fail ("Output.isNothing() && \"Input output.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3730, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Output.isNothing() && "Input output.");
3731    }
3732
3733    for (const auto &II : Inputs) {
3734      addDashXForInput(Args, II, CmdArgs);
3735      if (II.isFilename())
3736        CmdArgs.push_back(II.getFilename());
3737      else
3738        II.getInputArg().renderAsInput(Args, CmdArgs);
3739    }
3740
3741    C.addCommand(llvm::make_unique<Command>(JA, *this, D.getClangProgramPath(),
3742                                            CmdArgs, Inputs));
3743    return;
3744  }
3745
3746  if (C.getDriver().embedBitcodeMarkerOnly() && !C.getDriver().isUsingLTO())
3747    CmdArgs.push_back("-fembed-bitcode=marker");
3748
3749  // We normally speed up the clang process a bit by skipping destructors at
3750  // exit, but when we're generating diagnostics we can rely on some of the
3751  // cleanup.
3752  if (!C.isForDiagnostics())
3753    CmdArgs.push_back("-disable-free");
3754
3755#ifdef NDEBUG
3756  const bool IsAssertBuild = false;
3757#else
3758  const bool IsAssertBuild = true;
3759#endif
3760
3761  // Disable the verification pass in -asserts builds.
3762  if (!IsAssertBuild)
3763    CmdArgs.push_back("-disable-llvm-verifier");
3764
3765  // Discard value names in assert builds unless otherwise specified.
3766  if (Args.hasFlag(options::OPT_fdiscard_value_names,
3767                   options::OPT_fno_discard_value_names, !IsAssertBuild))
3768    CmdArgs.push_back("-discard-value-names");
3769
3770  // Set the main file name, so that debug info works even with
3771  // -save-temps.
3772  CmdArgs.push_back("-main-file-name");
3773  CmdArgs.push_back(getBaseInputName(Args, Input));
3774
3775  // Some flags which affect the language (via preprocessor
3776  // defines).
3777  if (Args.hasArg(options::OPT_static))
3778    CmdArgs.push_back("-static-define");
3779
3780  if (Args.hasArg(options::OPT_municode))
3781    CmdArgs.push_back("-DUNICODE");
3782
3783  if (isa<AnalyzeJobAction>(JA))
3784    RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
3785
3786  // Enable compatilibily mode to avoid analyzer-config related errors.
3787  // Since we can't access frontend flags through hasArg, let's manually iterate
3788  // through them.
3789  bool FoundAnalyzerConfig = false;
3790  for (auto Arg : Args.filtered(options::OPT_Xclang))
3791    if (StringRef(Arg->getValue()) == "-analyzer-config") {
3792      FoundAnalyzerConfig = true;
3793      break;
3794    }
3795  if (!FoundAnalyzerConfig)
3796    for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
3797      if (StringRef(Arg->getValue()) == "-analyzer-config") {
3798        FoundAnalyzerConfig = true;
3799        break;
3800      }
3801  if (FoundAnalyzerConfig)
3802    CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
3803
3804  CheckCodeGenerationOptions(D, Args);
3805
3806  unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
3807   (0) . __assert_fail ("FunctionAlignment <= 31 && \"function alignment will be truncated!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3807, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
3808  if (FunctionAlignment) {
3809    CmdArgs.push_back("-function-alignment");
3810    CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
3811  }
3812
3813  llvm::Reloc::Model RelocationModel;
3814  unsigned PICLevel;
3815  bool IsPIE;
3816  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
3817
3818  const char *RMName = RelocationModelName(RelocationModel);
3819
3820  if ((RelocationModel == llvm::Reloc::ROPI ||
3821       RelocationModel == llvm::Reloc::ROPI_RWPI) &&
3822      types::isCXX(Input.getType()) &&
3823      !Args.hasArg(options::OPT_fallow_unsupported))
3824    D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
3825
3826  if (RMName) {
3827    CmdArgs.push_back("-mrelocation-model");
3828    CmdArgs.push_back(RMName);
3829  }
3830  if (PICLevel > 0) {
3831    CmdArgs.push_back("-pic-level");
3832    CmdArgs.push_back(PICLevel == 1 ? "1" : "2");
3833    if (IsPIE)
3834      CmdArgs.push_back("-pic-is-pie");
3835  }
3836
3837  if (RelocationModel == llvm::Reloc::ROPI ||
3838      RelocationModel == llvm::Reloc::ROPI_RWPI)
3839    CmdArgs.push_back("-fropi");
3840  if (RelocationModel == llvm::Reloc::RWPI ||
3841      RelocationModel == llvm::Reloc::ROPI_RWPI)
3842    CmdArgs.push_back("-frwpi");
3843
3844  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
3845    CmdArgs.push_back("-meabi");
3846    CmdArgs.push_back(A->getValue());
3847  }
3848
3849  CmdArgs.push_back("-mthread-model");
3850  if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
3851    if (!TC.isThreadModelSupported(A->getValue()))
3852      D.Diag(diag::err_drv_invalid_thread_model_for_target)
3853          << A->getValue() << A->getAsString(Args);
3854    CmdArgs.push_back(A->getValue());
3855  }
3856  else
3857    CmdArgs.push_back(Args.MakeArgString(TC.getThreadModel()));
3858
3859  Args.AddLastArg(CmdArgs, options::OPT_fveclib);
3860
3861  if (Args.hasFlag(options::OPT_fmerge_all_constants,
3862                   options::OPT_fno_merge_all_constants, false))
3863    CmdArgs.push_back("-fmerge-all-constants");
3864
3865  if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
3866                   options::OPT_fdelete_null_pointer_checks, false))
3867    CmdArgs.push_back("-fno-delete-null-pointer-checks");
3868
3869  // LLVM Code Generator Options.
3870
3871  if (Args.hasArg(options::OPT_frewrite_map_file) ||
3872      Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
3873    for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
3874                                      options::OPT_frewrite_map_file_EQ)) {
3875      StringRef Map = A->getValue();
3876      if (!llvm::sys::fs::exists(Map)) {
3877        D.Diag(diag::err_drv_no_such_file) << Map;
3878      } else {
3879        CmdArgs.push_back("-frewrite-map-file");
3880        CmdArgs.push_back(A->getValue());
3881        A->claim();
3882      }
3883    }
3884  }
3885
3886  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
3887    StringRef v = A->getValue();
3888    CmdArgs.push_back("-mllvm");
3889    CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
3890    A->claim();
3891  }
3892
3893  if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
3894                    true))
3895    CmdArgs.push_back("-fno-jump-tables");
3896
3897  if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
3898                   options::OPT_fno_profile_sample_accurate, false))
3899    CmdArgs.push_back("-fprofile-sample-accurate");
3900
3901  if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
3902                    options::OPT_fno_preserve_as_comments, true))
3903    CmdArgs.push_back("-fno-preserve-as-comments");
3904
3905  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
3906    CmdArgs.push_back("-mregparm");
3907    CmdArgs.push_back(A->getValue());
3908  }
3909
3910  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
3911                               options::OPT_freg_struct_return)) {
3912    if (TC.getArch() != llvm::Triple::x86) {
3913      D.Diag(diag::err_drv_unsupported_opt_for_target)
3914          << A->getSpelling() << RawTriple.str();
3915    } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
3916      CmdArgs.push_back("-fpcc-struct-return");
3917    } else {
3918      getOption().matches(options..OPT_freg_struct_return)", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 3918, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(A->getOption().matches(options::OPT_freg_struct_return));
3919      CmdArgs.push_back("-freg-struct-return");
3920    }
3921  }
3922
3923  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
3924    CmdArgs.push_back("-fdefault-calling-conv=stdcall");
3925
3926  if (shouldUseFramePointer(Args, RawTriple))
3927    CmdArgs.push_back("-mdisable-fp-elim");
3928  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
3929                    options::OPT_fno_zero_initialized_in_bss))
3930    CmdArgs.push_back("-mno-zero-initialized-in-bss");
3931
3932  bool OFastEnabled = isOptimizationLevelFast(Args);
3933  // If -Ofast is the optimization level, then -fstrict-aliasing should be
3934  // enabled.  This alias option is being used to simplify the hasFlag logic.
3935  OptSpecifier StrictAliasingAliasOption =
3936      OFastEnabled ? options::OPT_Ofast : options::OPT_fstrict_aliasing;
3937  // We turn strict aliasing off by default if we're in CL mode, since MSVC
3938  // doesn't do any TBAA.
3939  bool TBAAOnByDefault = !D.IsCLMode();
3940  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
3941                    options::OPT_fno_strict_aliasing, TBAAOnByDefault))
3942    CmdArgs.push_back("-relaxed-aliasing");
3943  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
3944                    options::OPT_fno_struct_path_tbaa))
3945    CmdArgs.push_back("-no-struct-path-tbaa");
3946  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
3947                   false))
3948    CmdArgs.push_back("-fstrict-enums");
3949  if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
3950                    true))
3951    CmdArgs.push_back("-fno-strict-return");
3952  if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
3953                   options::OPT_fno_allow_editor_placeholders, false))
3954    CmdArgs.push_back("-fallow-editor-placeholders");
3955  if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
3956                   options::OPT_fno_strict_vtable_pointers,
3957                   false))
3958    CmdArgs.push_back("-fstrict-vtable-pointers");
3959  if (Args.hasFlag(options::OPT_fforce_emit_vtables,
3960                   options::OPT_fno_force_emit_vtables,
3961                   false))
3962    CmdArgs.push_back("-fforce-emit-vtables");
3963  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
3964                    options::OPT_fno_optimize_sibling_calls))
3965    CmdArgs.push_back("-mdisable-tail-calls");
3966  if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
3967                   options::OPT_fescaping_block_tail_calls, false))
3968    CmdArgs.push_back("-fno-escaping-block-tail-calls");
3969
3970  Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
3971                  options::OPT_fno_fine_grained_bitfield_accesses);
3972
3973  // Handle segmented stacks.
3974  if (Args.hasArg(options::OPT_fsplit_stack))
3975    CmdArgs.push_back("-split-stacks");
3976
3977  RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs);
3978
3979  // Decide whether to use verbose asm. Verbose assembly is the default on
3980  // toolchains which have the integrated assembler on by default.
3981  bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
3982  if (Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
3983                   IsIntegratedAssemblerDefault) ||
3984      Args.hasArg(options::OPT_dA))
3985    CmdArgs.push_back("-masm-verbose");
3986
3987  if (!TC.useIntegratedAs())
3988    CmdArgs.push_back("-no-integrated-as");
3989
3990  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
3991    CmdArgs.push_back("-mdebug-pass");
3992    CmdArgs.push_back("Structure");
3993  }
3994  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
3995    CmdArgs.push_back("-mdebug-pass");
3996    CmdArgs.push_back("Arguments");
3997  }
3998
3999  // Enable -mconstructor-aliases except on darwin, where we have to work around
4000  // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4001  // aliases aren't supported.
4002  if (!RawTriple.isOSDarwin() && !RawTriple.isNVPTX())
4003    CmdArgs.push_back("-mconstructor-aliases");
4004
4005  // Darwin's kernel doesn't support guard variables; just die if we
4006  // try to use them.
4007  if (KernelOrKext && RawTriple.isOSDarwin())
4008    CmdArgs.push_back("-fforbid-guard-variables");
4009
4010  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4011                   false)) {
4012    CmdArgs.push_back("-mms-bitfields");
4013  }
4014
4015  if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4016                   options::OPT_mno_pie_copy_relocations,
4017                   false)) {
4018    CmdArgs.push_back("-mpie-copy-relocations");
4019  }
4020
4021  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4022    CmdArgs.push_back("-fno-plt");
4023  }
4024
4025  // -fhosted is default.
4026  // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4027  // use Freestanding.
4028  bool Freestanding =
4029      Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4030      KernelOrKext;
4031  if (Freestanding)
4032    CmdArgs.push_back("-ffreestanding");
4033
4034  // This is a coarse approximation of what llvm-gcc actually does, both
4035  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4036  // complicated ways.
4037  bool AsynchronousUnwindTables =
4038      Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4039                   options::OPT_fno_asynchronous_unwind_tables,
4040                   (TC.IsUnwindTablesDefault(Args) ||
4041                    TC.getSanitizerArgs().needsUnwindTables()) &&
4042                       !Freestanding);
4043  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4044                   AsynchronousUnwindTables))
4045    CmdArgs.push_back("-munwind-tables");
4046
4047  TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4048
4049  // FIXME: Handle -mtune=.
4050  (void)Args.hasArg(options::OPT_mtune_EQ);
4051
4052  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4053    CmdArgs.push_back("-mcode-model");
4054    CmdArgs.push_back(A->getValue());
4055  }
4056
4057  // Add the target cpu
4058  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4059  if (!CPU.empty()) {
4060    CmdArgs.push_back("-target-cpu");
4061    CmdArgs.push_back(Args.MakeArgString(CPU));
4062  }
4063
4064  RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
4065
4066  // These two are potentially updated by AddClangCLArgs.
4067  codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4068  bool EmitCodeView = false;
4069
4070  // Add clang-cl arguments.
4071  types::ID InputType = Input.getType();
4072  if (D.IsCLMode())
4073    AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4074
4075  DwarfFissionKind DwarfFission;
4076  RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, IsWindowsMSVC,
4077                     CmdArgs, DebugInfoKind, DwarfFission);
4078
4079  // Add the split debug info name to the command lines here so we
4080  // can propagate it to the backend.
4081  bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
4082                    TC.getTriple().isOSBinFormatELF() &&
4083                    (isa<AssembleJobAction>(JA) || isa<CompileJobAction>(JA) ||
4084                     isa<BackendJobAction>(JA));
4085  const char *SplitDWARFOut;
4086  if (SplitDWARF) {
4087    CmdArgs.push_back("-split-dwarf-file");
4088    SplitDWARFOut = SplitDebugName(Args, Input, Output);
4089    CmdArgs.push_back(SplitDWARFOut);
4090  }
4091
4092  // Pass the linker version in use.
4093  if (Arg *A = Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4094    CmdArgs.push_back("-target-linker-version");
4095    CmdArgs.push_back(A->getValue());
4096  }
4097
4098  if (!shouldUseLeafFramePointer(Args, RawTriple))
4099    CmdArgs.push_back("-momit-leaf-frame-pointer");
4100
4101  // Explicitly error on some things we know we don't support and can't just
4102  // ignore.
4103  if (!Args.hasArg(options::OPT_fallow_unsupported)) {
4104    Arg *Unsupported;
4105    if (types::isCXX(InputType) && RawTriple.isOSDarwin() &&
4106        TC.getArch() == llvm::Triple::x86) {
4107      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4108          (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4109        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4110            << Unsupported->getOption().getName();
4111    }
4112    // The faltivec option has been superseded by the maltivec option.
4113    if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4114      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4115          << Unsupported->getOption().getName()
4116          << "please use -maltivec and include altivec.h explicitly";
4117    if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4118      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4119          << Unsupported->getOption().getName() << "please use -mno-altivec";
4120  }
4121
4122  Args.AddAllArgs(CmdArgs, options::OPT_v);
4123  Args.AddLastArg(CmdArgs, options::OPT_H);
4124  if (D.CCPrintHeaders && !D.CCGenDiagnostics) {
4125    CmdArgs.push_back("-header-include-file");
4126    CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4127                                               : "-");
4128  }
4129  Args.AddLastArg(CmdArgs, options::OPT_P);
4130  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4131
4132  if (D.CCLogDiagnostics && !D.CCGenDiagnostics) {
4133    CmdArgs.push_back("-diagnostic-log-file");
4134    CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4135                                                 : "-");
4136  }
4137
4138  bool UseSeparateSections = isUseSeparateSections(Triple);
4139
4140  if (Args.hasFlag(options::OPT_ffunction_sections,
4141                   options::OPT_fno_function_sections, UseSeparateSections)) {
4142    CmdArgs.push_back("-ffunction-sections");
4143  }
4144
4145  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4146                   UseSeparateSections)) {
4147    CmdArgs.push_back("-fdata-sections");
4148  }
4149
4150  if (!Args.hasFlag(options::OPT_funique_section_names,
4151                    options::OPT_fno_unique_section_names, true))
4152    CmdArgs.push_back("-fno-unique-section-names");
4153
4154  if (auto *A = Args.getLastArg(
4155      options::OPT_finstrument_functions,
4156      options::OPT_finstrument_functions_after_inlining,
4157      options::OPT_finstrument_function_entry_bare))
4158    A->render(Args, CmdArgs);
4159
4160  // NVPTX doesn't support PGO or coverage. There's no runtime support for
4161  // sampling, overhead of call arc collection is way too high and there's no
4162  // way to collect the output.
4163  if (!Triple.isNVPTX())
4164    addPGOAndCoverageFlags(C, D, Output, Args, CmdArgs);
4165
4166  if (auto *ABICompatArg = Args.getLastArg(options::OPT_fclang_abi_compat_EQ))
4167    ABICompatArg->render(Args, CmdArgs);
4168
4169  // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
4170  if (RawTriple.isPS4CPU() &&
4171      !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
4172    PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4173    PS4cpu::addSanitizerArgs(TC, CmdArgs);
4174  }
4175
4176  // Pass options for controlling the default header search paths.
4177  if (Args.hasArg(options::OPT_nostdinc)) {
4178    CmdArgs.push_back("-nostdsysteminc");
4179    CmdArgs.push_back("-nobuiltininc");
4180  } else {
4181    if (Args.hasArg(options::OPT_nostdlibinc))
4182      CmdArgs.push_back("-nostdsysteminc");
4183    Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4184    Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4185  }
4186
4187  // Pass the path to compiler resource files.
4188  CmdArgs.push_back("-resource-dir");
4189  CmdArgs.push_back(D.ResourceDir.c_str());
4190
4191  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4192
4193  RenderARCMigrateToolOptions(D, Args, CmdArgs);
4194
4195  // Add preprocessing options like -I, -D, etc. if we are using the
4196  // preprocessor.
4197  //
4198  // FIXME: Support -fpreprocessed
4199  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4200    AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4201
4202  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4203  // that "The compiler can only warn and ignore the option if not recognized".
4204  // When building with ccache, it will pass -D options to clang even on
4205  // preprocessed inputs and configure concludes that -fPIC is not supported.
4206  Args.ClaimAllArgs(options::OPT_D);
4207
4208  // Manually translate -O4 to -O3; let clang reject others.
4209  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4210    if (A->getOption().matches(options::OPT_O4)) {
4211      CmdArgs.push_back("-O3");
4212      D.Diag(diag::warn_O4_is_O3);
4213    } else {
4214      A->render(Args, CmdArgs);
4215    }
4216  }
4217
4218  // Warn about ignored options to clang.
4219  for (const Arg *A :
4220       Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4221    D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4222    A->claim();
4223  }
4224
4225  for (const Arg *A :
4226       Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4227    D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4228    A->claim();
4229  }
4230
4231  claimNoWarnArgs(Args);
4232
4233  Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4234
4235  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4236  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4237    CmdArgs.push_back("-pedantic");
4238  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4239  Args.AddLastArg(CmdArgs, options::OPT_w);
4240
4241  // Fixed point flags
4242  if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
4243                   /*Default=*/false))
4244    Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
4245
4246  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
4247  // (-ansi is equivalent to -std=c89 or -std=c++98).
4248  //
4249  // If a std is supplied, only add -trigraphs if it follows the
4250  // option.
4251  bool ImplyVCPPCXXVer = false;
4252  if (Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi)) {
4253    if (Std->getOption().matches(options::OPT_ansi))
4254      if (types::isCXX(InputType))
4255        CmdArgs.push_back("-std=c++98");
4256      else
4257        CmdArgs.push_back("-std=c89");
4258    else
4259      Std->render(Args, CmdArgs);
4260
4261    // If -f(no-)trigraphs appears after the language standard flag, honor it.
4262    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
4263                                 options::OPT_ftrigraphs,
4264                                 options::OPT_fno_trigraphs))
4265      if (A != Std)
4266        A->render(Args, CmdArgs);
4267  } else {
4268    // Honor -std-default.
4269    //
4270    // FIXME: Clang doesn't correctly handle -std= when the input language
4271    // doesn't match. For the time being just ignore this for C++ inputs;
4272    // eventually we want to do all the standard defaulting here instead of
4273    // splitting it between the driver and clang -cc1.
4274    if (!types::isCXX(InputType))
4275      Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
4276                                /*Joined=*/true);
4277    else if (IsWindowsMSVC)
4278      ImplyVCPPCXXVer = true;
4279
4280    Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
4281                    options::OPT_fno_trigraphs);
4282  }
4283
4284  // GCC's behavior for -Wwrite-strings is a bit strange:
4285  //  * In C, this "warning flag" changes the types of string literals from
4286  //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
4287  //    for the discarded qualifier.
4288  //  * In C++, this is just a normal warning flag.
4289  //
4290  // Implementing this warning correctly in C is hard, so we follow GCC's
4291  // behavior for now. FIXME: Directly diagnose uses of a string literal as
4292  // a non-const char* in C, rather than using this crude hack.
4293  if (!types::isCXX(InputType)) {
4294    // FIXME: This should behave just like a warning flag, and thus should also
4295    // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
4296    Arg *WriteStrings =
4297        Args.getLastArg(options::OPT_Wwrite_strings,
4298                        options::OPT_Wno_write_strings, options::OPT_w);
4299    if (WriteStrings &&
4300        WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
4301      CmdArgs.push_back("-fconst-strings");
4302  }
4303
4304  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
4305  // during C++ compilation, which it is by default. GCC keeps this define even
4306  // in the presence of '-w', match this behavior bug-for-bug.
4307  if (types::isCXX(InputType) &&
4308      Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
4309                   true)) {
4310    CmdArgs.push_back("-fdeprecated-macro");
4311  }
4312
4313  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
4314  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
4315    if (Asm->getOption().matches(options::OPT_fasm))
4316      CmdArgs.push_back("-fgnu-keywords");
4317    else
4318      CmdArgs.push_back("-fno-gnu-keywords");
4319  }
4320
4321  if (ShouldDisableDwarfDirectory(Args, TC))
4322    CmdArgs.push_back("-fno-dwarf-directory-asm");
4323
4324  if (ShouldDisableAutolink(Args, TC))
4325    CmdArgs.push_back("-fno-autolink");
4326
4327  // Add in -fdebug-compilation-dir if necessary.
4328  addDebugCompDirArg(Args, CmdArgs);
4329
4330  addDebugPrefixMapArg(D, Args, CmdArgs);
4331
4332  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
4333                               options::OPT_ftemplate_depth_EQ)) {
4334    CmdArgs.push_back("-ftemplate-depth");
4335    CmdArgs.push_back(A->getValue());
4336  }
4337
4338  if (Arg *A = Args.getLastArg(options::OPT_foperator_arrow_depth_EQ)) {
4339    CmdArgs.push_back("-foperator-arrow-depth");
4340    CmdArgs.push_back(A->getValue());
4341  }
4342
4343  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_depth_EQ)) {
4344    CmdArgs.push_back("-fconstexpr-depth");
4345    CmdArgs.push_back(A->getValue());
4346  }
4347
4348  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_steps_EQ)) {
4349    CmdArgs.push_back("-fconstexpr-steps");
4350    CmdArgs.push_back(A->getValue());
4351  }
4352
4353  if (Arg *A = Args.getLastArg(options::OPT_fbracket_depth_EQ)) {
4354    CmdArgs.push_back("-fbracket-depth");
4355    CmdArgs.push_back(A->getValue());
4356  }
4357
4358  if (Arg *A = Args.getLastArg(options::OPT_Wlarge_by_value_copy_EQ,
4359                               options::OPT_Wlarge_by_value_copy_def)) {
4360    if (A->getNumValues()) {
4361      StringRef bytes = A->getValue();
4362      CmdArgs.push_back(Args.MakeArgString("-Wlarge-by-value-copy=" + bytes));
4363    } else
4364      CmdArgs.push_back("-Wlarge-by-value-copy=64"); // default value
4365  }
4366
4367  if (Args.hasArg(options::OPT_relocatable_pch))
4368    CmdArgs.push_back("-relocatable-pch");
4369
4370  if (const Arg *A = Args.getLastArg(options::OPT_fcf_runtime_abi_EQ)) {
4371    static const char *kCFABIs[] = {
4372      "standalone""objc""swift""swift-5.0""swift-4.2""swift-4.1",
4373    };
4374
4375    if (find(kCFABIs, StringRef(A->getValue())) == std::end(kCFABIs))
4376      D.Diag(diag::err_drv_invalid_cf_runtime_abi) << A->getValue();
4377    else
4378      A->render(Args, CmdArgs);
4379  }
4380
4381  if (Arg *A = Args.getLastArg(options::OPT_fconstant_string_class_EQ)) {
4382    CmdArgs.push_back("-fconstant-string-class");
4383    CmdArgs.push_back(A->getValue());
4384  }
4385
4386  if (Arg *A = Args.getLastArg(options::OPT_ftabstop_EQ)) {
4387    CmdArgs.push_back("-ftabstop");
4388    CmdArgs.push_back(A->getValue());
4389  }
4390
4391  if (Args.hasFlag(options::OPT_fstack_size_section,
4392                   options::OPT_fno_stack_size_section, RawTriple.isPS4()))
4393    CmdArgs.push_back("-fstack-size-section");
4394
4395  CmdArgs.push_back("-ferror-limit");
4396  if (Arg *A = Args.getLastArg(options::OPT_ferror_limit_EQ))
4397    CmdArgs.push_back(A->getValue());
4398  else
4399    CmdArgs.push_back("19");
4400
4401  if (Arg *A = Args.getLastArg(options::OPT_fmacro_backtrace_limit_EQ)) {
4402    CmdArgs.push_back("-fmacro-backtrace-limit");
4403    CmdArgs.push_back(A->getValue());
4404  }
4405
4406  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_backtrace_limit_EQ)) {
4407    CmdArgs.push_back("-ftemplate-backtrace-limit");
4408    CmdArgs.push_back(A->getValue());
4409  }
4410
4411  if (Arg *A = Args.getLastArg(options::OPT_fconstexpr_backtrace_limit_EQ)) {
4412    CmdArgs.push_back("-fconstexpr-backtrace-limit");
4413    CmdArgs.push_back(A->getValue());
4414  }
4415
4416  if (Arg *A = Args.getLastArg(options::OPT_fspell_checking_limit_EQ)) {
4417    CmdArgs.push_back("-fspell-checking-limit");
4418    CmdArgs.push_back(A->getValue());
4419  }
4420
4421  // Pass -fmessage-length=.
4422  CmdArgs.push_back("-fmessage-length");
4423  if (Arg *A = Args.getLastArg(options::OPT_fmessage_length_EQ)) {
4424    CmdArgs.push_back(A->getValue());
4425  } else {
4426    // If -fmessage-length=N was not specified, determine whether this is a
4427    // terminal and, if so, implicitly define -fmessage-length appropriately.
4428    unsigned N = llvm::sys::Process::StandardErrColumns();
4429    CmdArgs.push_back(Args.MakeArgString(Twine(N)));
4430  }
4431
4432  // -fvisibility= and -fvisibility-ms-compat are of a piece.
4433  if (const Arg *A = Args.getLastArg(options::OPT_fvisibility_EQ,
4434                                     options::OPT_fvisibility_ms_compat)) {
4435    if (A->getOption().matches(options::OPT_fvisibility_EQ)) {
4436      CmdArgs.push_back("-fvisibility");
4437      CmdArgs.push_back(A->getValue());
4438    } else {
4439      getOption().matches(options..OPT_fvisibility_ms_compat)", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 4439, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(A->getOption().matches(options::OPT_fvisibility_ms_compat));
4440      CmdArgs.push_back("-fvisibility");
4441      CmdArgs.push_back("hidden");
4442      CmdArgs.push_back("-ftype-visibility");
4443      CmdArgs.push_back("default");
4444    }
4445  }
4446
4447  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_inlines_hidden);
4448  Args.AddLastArg(CmdArgs, options::OPT_fvisibility_global_new_delete_hidden);
4449
4450  Args.AddLastArg(CmdArgs, options::OPT_ftlsmodel_EQ);
4451
4452  // Forward -f (flag) options which we can pass directly.
4453  Args.AddLastArg(CmdArgs, options::OPT_femit_all_decls);
4454  Args.AddLastArg(CmdArgs, options::OPT_fheinous_gnu_extensions);
4455  Args.AddLastArg(CmdArgs, options::OPT_fdigraphs, options::OPT_fno_digraphs);
4456  Args.AddLastArg(CmdArgs, options::OPT_fno_operator_names);
4457  Args.AddLastArg(CmdArgs, options::OPT_femulated_tls,
4458                  options::OPT_fno_emulated_tls);
4459  Args.AddLastArg(CmdArgs, options::OPT_fkeep_static_consts);
4460
4461  // AltiVec-like language extensions aren't relevant for assembling.
4462  if (!isa<PreprocessJobAction>(JA) || Output.getType() != types::TY_PP_Asm)
4463    Args.AddLastArg(CmdArgs, options::OPT_fzvector);
4464
4465  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
4466  Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
4467
4468  // Forward flags for OpenMP. We don't do this if the current action is an
4469  // device offloading action other than OpenMP.
4470  if (Args.hasFlag(options::OPT_fopenmp, options::OPT_fopenmp_EQ,
4471                   options::OPT_fno_openmp, false) &&
4472      (JA.isDeviceOffloading(Action::OFK_None) ||
4473       JA.isDeviceOffloading(Action::OFK_OpenMP))) {
4474    switch (D.getOpenMPRuntime(Args)) {
4475    case Driver::OMPRT_OMP:
4476    case Driver::OMPRT_IOMP5:
4477      // Clang can generate useful OpenMP code for these two runtime libraries.
4478      CmdArgs.push_back("-fopenmp");
4479
4480      // If no option regarding the use of TLS in OpenMP codegeneration is
4481      // given, decide a default based on the target. Otherwise rely on the
4482      // options and pass the right information to the frontend.
4483      if (!Args.hasFlag(options::OPT_fopenmp_use_tls,
4484                        options::OPT_fnoopenmp_use_tls, /*Default=*/true))
4485        CmdArgs.push_back("-fnoopenmp-use-tls");
4486      Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4487                      options::OPT_fno_openmp_simd);
4488      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4489      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_number_of_sm_EQ);
4490      Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_cuda_blocks_per_sm_EQ);
4491      Args.AddAllArgs(CmdArgs,
4492                      options::OPT_fopenmp_cuda_teams_reduction_recs_num_EQ);
4493      if (Args.hasFlag(options::OPT_fopenmp_optimistic_collapse,
4494                       options::OPT_fno_openmp_optimistic_collapse,
4495                       /*Default=*/false))
4496        CmdArgs.push_back("-fopenmp-optimistic-collapse");
4497
4498      // When in OpenMP offloading mode with NVPTX target, forward
4499      // cuda-mode flag
4500      if (Args.hasFlag(options::OPT_fopenmp_cuda_mode,
4501                       options::OPT_fno_openmp_cuda_mode, /*Default=*/false))
4502        CmdArgs.push_back("-fopenmp-cuda-mode");
4503
4504      // When in OpenMP offloading mode with NVPTX target, check if full runtime
4505      // is required.
4506      if (Args.hasFlag(options::OPT_fopenmp_cuda_force_full_runtime,
4507                       options::OPT_fno_openmp_cuda_force_full_runtime,
4508                       /*Default=*/false))
4509        CmdArgs.push_back("-fopenmp-cuda-force-full-runtime");
4510      break;
4511    default:
4512      // By default, if Clang doesn't know how to generate useful OpenMP code
4513      // for a specific runtime library, we just don't pass the '-fopenmp' flag
4514      // down to the actual compilation.
4515      // FIXME: It would be better to have a mode which *only* omits IR
4516      // generation based on the OpenMP support so that we get consistent
4517      // semantic analysis, etc.
4518      break;
4519    }
4520  } else {
4521    Args.AddLastArg(CmdArgs, options::OPT_fopenmp_simd,
4522                    options::OPT_fno_openmp_simd);
4523    Args.AddAllArgs(CmdArgs, options::OPT_fopenmp_version_EQ);
4524  }
4525
4526  const SanitizerArgs &Sanitize = TC.getSanitizerArgs();
4527  Sanitize.addArgs(TC, Args, CmdArgs, InputType);
4528
4529  const XRayArgs &XRay = TC.getXRayArgs();
4530  XRay.addArgs(TC, Args, CmdArgs, InputType);
4531
4532  if (TC.SupportsProfiling())
4533    Args.AddLastArg(CmdArgs, options::OPT_pg);
4534
4535  if (TC.SupportsProfiling())
4536    Args.AddLastArg(CmdArgs, options::OPT_mfentry);
4537
4538  // -flax-vector-conversions is default.
4539  if (!Args.hasFlag(options::OPT_flax_vector_conversions,
4540                    options::OPT_fno_lax_vector_conversions))
4541    CmdArgs.push_back("-fno-lax-vector-conversions");
4542
4543  if (Args.getLastArg(options::OPT_fapple_kext) ||
4544      (Args.hasArg(options::OPT_mkernel) && types::isCXX(InputType)))
4545    CmdArgs.push_back("-fapple-kext");
4546
4547  Args.AddLastArg(CmdArgs, options::OPT_fobjc_sender_dependent_dispatch);
4548  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_print_source_range_info);
4549  Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_parseable_fixits);
4550  Args.AddLastArg(CmdArgs, options::OPT_ftime_report);
4551  Args.AddLastArg(CmdArgs, options::OPT_ftrapv);
4552  Args.AddLastArg(CmdArgs, options::OPT_malign_double);
4553
4554  if (Arg *A = Args.getLastArg(options::OPT_ftrapv_handler_EQ)) {
4555    CmdArgs.push_back("-ftrapv-handler");
4556    CmdArgs.push_back(A->getValue());
4557  }
4558
4559  Args.AddLastArg(CmdArgs, options::OPT_ftrap_function_EQ);
4560
4561  // -fno-strict-overflow implies -fwrapv if it isn't disabled, but
4562  // -fstrict-overflow won't turn off an explicitly enabled -fwrapv.
4563  if (Arg *A = Args.getLastArg(options::OPT_fwrapv, options::OPT_fno_wrapv)) {
4564    if (A->getOption().matches(options::OPT_fwrapv))
4565      CmdArgs.push_back("-fwrapv");
4566  } else if (Arg *A = Args.getLastArg(options::OPT_fstrict_overflow,
4567                                      options::OPT_fno_strict_overflow)) {
4568    if (A->getOption().matches(options::OPT_fno_strict_overflow))
4569      CmdArgs.push_back("-fwrapv");
4570  }
4571
4572  if (Arg *A = Args.getLastArg(options::OPT_freroll_loops,
4573                               options::OPT_fno_reroll_loops))
4574    if (A->getOption().matches(options::OPT_freroll_loops))
4575      CmdArgs.push_back("-freroll-loops");
4576
4577  Args.AddLastArg(CmdArgs, options::OPT_fwritable_strings);
4578  Args.AddLastArg(CmdArgs, options::OPT_funroll_loops,
4579                  options::OPT_fno_unroll_loops);
4580
4581  Args.AddLastArg(CmdArgs, options::OPT_pthread);
4582
4583  if (Args.hasFlag(options::OPT_mspeculative_load_hardening, options::OPT_mno_speculative_load_hardening,
4584                   false))
4585    CmdArgs.push_back(Args.MakeArgString("-mspeculative-load-hardening"));
4586
4587  RenderSSPOptions(TC, Args, CmdArgs, KernelOrKext);
4588  RenderTrivialAutoVarInitOptions(D, TC, Args, CmdArgs);
4589
4590  // Translate -mstackrealign
4591  if (Args.hasFlag(options::OPT_mstackrealign, options::OPT_mno_stackrealign,
4592                   false))
4593    CmdArgs.push_back(Args.MakeArgString("-mstackrealign"));
4594
4595  if (Args.hasArg(options::OPT_mstack_alignment)) {
4596    StringRef alignment = Args.getLastArgValue(options::OPT_mstack_alignment);
4597    CmdArgs.push_back(Args.MakeArgString("-mstack-alignment=" + alignment));
4598  }
4599
4600  if (Args.hasArg(options::OPT_mstack_probe_size)) {
4601    StringRef Size = Args.getLastArgValue(options::OPT_mstack_probe_size);
4602
4603    if (!Size.empty())
4604      CmdArgs.push_back(Args.MakeArgString("-mstack-probe-size=" + Size));
4605    else
4606      CmdArgs.push_back("-mstack-probe-size=0");
4607  }
4608
4609  if (!Args.hasFlag(options::OPT_mstack_arg_probe,
4610                    options::OPT_mno_stack_arg_probe, true))
4611    CmdArgs.push_back(Args.MakeArgString("-mno-stack-arg-probe"));
4612
4613  if (Arg *A = Args.getLastArg(options::OPT_mrestrict_it,
4614                               options::OPT_mno_restrict_it)) {
4615    if (A->getOption().matches(options::OPT_mrestrict_it)) {
4616      CmdArgs.push_back("-mllvm");
4617      CmdArgs.push_back("-arm-restrict-it");
4618    } else {
4619      CmdArgs.push_back("-mllvm");
4620      CmdArgs.push_back("-arm-no-restrict-it");
4621    }
4622  } else if (Triple.isOSWindows() &&
4623             (Triple.getArch() == llvm::Triple::arm ||
4624              Triple.getArch() == llvm::Triple::thumb)) {
4625    // Windows on ARM expects restricted IT blocks
4626    CmdArgs.push_back("-mllvm");
4627    CmdArgs.push_back("-arm-restrict-it");
4628  }
4629
4630  // Forward -cl options to -cc1
4631  RenderOpenCLOptions(Args, CmdArgs);
4632
4633  if (Arg *A = Args.getLastArg(options::OPT_fcf_protection_EQ)) {
4634    CmdArgs.push_back(
4635        Args.MakeArgString(Twine("-fcf-protection=") + A->getValue()));
4636  }
4637
4638  // Forward -f options with positive and negative forms; we translate
4639  // these by hand.
4640  if (Arg *A = getLastProfileSampleUseArg(Args)) {
4641    auto *PGOArg = Args.getLastArg(
4642        options::OPT_fprofile_generate, options::OPT_fprofile_generate_EQ,
4643        options::OPT_fcs_profile_generate, options::OPT_fcs_profile_generate_EQ,
4644        options::OPT_fprofile_use, options::OPT_fprofile_use_EQ);
4645    if (PGOArg)
4646      D.Diag(diag::err_drv_argument_not_allowed_with)
4647          << "SampleUse with PGO options";
4648
4649    StringRef fname = A->getValue();
4650    if (!llvm::sys::fs::exists(fname))
4651      D.Diag(diag::err_drv_no_such_file) << fname;
4652    else
4653      A->render(Args, CmdArgs);
4654  }
4655  Args.AddLastArg(CmdArgs, options::OPT_fprofile_remapping_file_EQ);
4656
4657  RenderBuiltinOptions(TC, RawTriple, Args, CmdArgs);
4658
4659  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4660                    options::OPT_fno_assume_sane_operator_new))
4661    CmdArgs.push_back("-fno-assume-sane-operator-new");
4662
4663  // -fblocks=0 is default.
4664  if (Args.hasFlag(options::OPT_fblocks, options::OPT_fno_blocks,
4665                   TC.IsBlocksDefault()) ||
4666      (Args.hasArg(options::OPT_fgnu_runtime) &&
4667       Args.hasArg(options::OPT_fobjc_nonfragile_abi) &&
4668       !Args.hasArg(options::OPT_fno_blocks))) {
4669    CmdArgs.push_back("-fblocks");
4670
4671    if (!Args.hasArg(options::OPT_fgnu_runtime) && !TC.hasBlocksRuntime())
4672      CmdArgs.push_back("-fblocks-runtime-optional");
4673  }
4674
4675  // -fencode-extended-block-signature=1 is default.
4676  if (TC.IsEncodeExtendedBlockSignatureDefault())
4677    CmdArgs.push_back("-fencode-extended-block-signature");
4678
4679  if (Args.hasFlag(options::OPT_fcoroutines_ts, options::OPT_fno_coroutines_ts,
4680                   false) &&
4681      types::isCXX(InputType)) {
4682    CmdArgs.push_back("-fcoroutines-ts");
4683  }
4684
4685  Args.AddLastArg(CmdArgs, options::OPT_fdouble_square_bracket_attributes,
4686                  options::OPT_fno_double_square_bracket_attributes);
4687
4688  bool HaveModules = false;
4689  RenderModulesOptions(C, D, Args, Input, Output, CmdArgs, HaveModules);
4690
4691  // -faccess-control is default.
4692  if (Args.hasFlag(options::OPT_fno_access_control,
4693                   options::OPT_faccess_control, false))
4694    CmdArgs.push_back("-fno-access-control");
4695
4696  // -felide-constructors is the default.
4697  if (Args.hasFlag(options::OPT_fno_elide_constructors,
4698                   options::OPT_felide_constructors, false))
4699    CmdArgs.push_back("-fno-elide-constructors");
4700
4701  ToolChain::RTTIMode RTTIMode = TC.getRTTIMode();
4702
4703  if (KernelOrKext || (types::isCXX(InputType) &&
4704                       (RTTIMode == ToolChain::RM_Disabled)))
4705    CmdArgs.push_back("-fno-rtti");
4706
4707  // -fshort-enums=0 is default for all architectures except Hexagon.
4708  if (Args.hasFlag(options::OPT_fshort_enums, options::OPT_fno_short_enums,
4709                   TC.getArch() == llvm::Triple::hexagon))
4710    CmdArgs.push_back("-fshort-enums");
4711
4712  RenderCharacterOptions(Args, AuxTriple ? *AuxTriple : RawTriple, CmdArgs);
4713
4714  // -fuse-cxa-atexit is default.
4715  if (!Args.hasFlag(
4716          options::OPT_fuse_cxa_atexit, options::OPT_fno_use_cxa_atexit,
4717          !RawTriple.isOSWindows() &&
4718              RawTriple.getOS() != llvm::Triple::Solaris &&
4719              TC.getArch() != llvm::Triple::xcore &&
4720              ((RawTriple.getVendor() != llvm::Triple::MipsTechnologies) ||
4721               RawTriple.hasEnvironment())) ||
4722      KernelOrKext)
4723    CmdArgs.push_back("-fno-use-cxa-atexit");
4724
4725  if (Args.hasFlag(options::OPT_fregister_global_dtors_with_atexit,
4726                   options::OPT_fno_register_global_dtors_with_atexit,
4727                   RawTriple.isOSDarwin() && !KernelOrKext))
4728    CmdArgs.push_back("-fregister-global-dtors-with-atexit");
4729
4730  // -fms-extensions=0 is default.
4731  if (Args.hasFlag(options::OPT_fms_extensions, options::OPT_fno_ms_extensions,
4732                   IsWindowsMSVC))
4733    CmdArgs.push_back("-fms-extensions");
4734
4735  // -fno-use-line-directives is default.
4736  if (Args.hasFlag(options::OPT_fuse_line_directives,
4737                   options::OPT_fno_use_line_directives, false))
4738    CmdArgs.push_back("-fuse-line-directives");
4739
4740  // -fms-compatibility=0 is default.
4741  if (Args.hasFlag(options::OPT_fms_compatibility,
4742                   options::OPT_fno_ms_compatibility,
4743                   (IsWindowsMSVC &&
4744                    Args.hasFlag(options::OPT_fms_extensions,
4745                                 options::OPT_fno_ms_extensions, true))))
4746    CmdArgs.push_back("-fms-compatibility");
4747
4748  VersionTuple MSVT = TC.computeMSVCVersion(&D, Args);
4749  if (!MSVT.empty())
4750    CmdArgs.push_back(
4751        Args.MakeArgString("-fms-compatibility-version=" + MSVT.getAsString()));
4752
4753  bool IsMSVC2015Compatible = MSVT.getMajor() >= 19;
4754  if (ImplyVCPPCXXVer) {
4755    StringRef LanguageStandard;
4756    if (const Arg *StdArg = Args.getLastArg(options::OPT__SLASH_std)) {
4757      LanguageStandard = llvm::StringSwitch<StringRef>(StdArg->getValue())
4758                             .Case("c++14""-std=c++14")
4759                             .Case("c++17""-std=c++17")
4760                             .Case("c++latest""-std=c++2a")
4761                             .Default("");
4762      if (LanguageStandard.empty())
4763        D.Diag(clang::diag::warn_drv_unused_argument)
4764            << StdArg->getAsString(Args);
4765    }
4766
4767    if (LanguageStandard.empty()) {
4768      if (IsMSVC2015Compatible)
4769        LanguageStandard = "-std=c++14";
4770      else
4771        LanguageStandard = "-std=c++11";
4772    }
4773
4774    CmdArgs.push_back(LanguageStandard.data());
4775  }
4776
4777  // -fno-borland-extensions is default.
4778  if (Args.hasFlag(options::OPT_fborland_extensions,
4779                   options::OPT_fno_borland_extensions, false))
4780    CmdArgs.push_back("-fborland-extensions");
4781
4782  // -fno-declspec is default, except for PS4.
4783  if (Args.hasFlag(options::OPT_fdeclspec, options::OPT_fno_declspec,
4784                   RawTriple.isPS4()))
4785    CmdArgs.push_back("-fdeclspec");
4786  else if (Args.hasArg(options::OPT_fno_declspec))
4787    CmdArgs.push_back("-fno-declspec"); // Explicitly disabling __declspec.
4788
4789  // -fthreadsafe-static is default, except for MSVC compatibility versions less
4790  // than 19.
4791  if (!Args.hasFlag(options::OPT_fthreadsafe_statics,
4792                    options::OPT_fno_threadsafe_statics,
4793                    !IsWindowsMSVC || IsMSVC2015Compatible))
4794    CmdArgs.push_back("-fno-threadsafe-statics");
4795
4796  // -fno-delayed-template-parsing is default, except when targeting MSVC.
4797  // Many old Windows SDK versions require this to parse.
4798  // FIXME: MSVC introduced /Zc:twoPhase- to disable this behavior in their
4799  // compiler. We should be able to disable this by default at some point.
4800  if (Args.hasFlag(options::OPT_fdelayed_template_parsing,
4801                   options::OPT_fno_delayed_template_parsing, IsWindowsMSVC))
4802    CmdArgs.push_back("-fdelayed-template-parsing");
4803
4804  // -fgnu-keywords default varies depending on language; only pass if
4805  // specified.
4806  if (Arg *A = Args.getLastArg(options::OPT_fgnu_keywords,
4807                               options::OPT_fno_gnu_keywords))
4808    A->render(Args, CmdArgs);
4809
4810  if (Args.hasFlag(options::OPT_fgnu89_inline, options::OPT_fno_gnu89_inline,
4811                   false))
4812    CmdArgs.push_back("-fgnu89-inline");
4813
4814  if (Args.hasArg(options::OPT_fno_inline))
4815    CmdArgs.push_back("-fno-inline");
4816
4817  if (Arg* InlineArg = Args.getLastArg(options::OPT_finline_functions,
4818                                       options::OPT_finline_hint_functions,
4819                                       options::OPT_fno_inline_functions))
4820    InlineArg->render(Args, CmdArgs);
4821
4822  Args.AddLastArg(CmdArgs, options::OPT_fexperimental_new_pass_manager,
4823                  options::OPT_fno_experimental_new_pass_manager);
4824
4825  ObjCRuntime Runtime = AddObjCRuntimeArgs(Args, CmdArgs, rewriteKind);
4826  RenderObjCOptions(TC, D, RawTriple, Args, Runtime, rewriteKind != RK_None,
4827                    Input, CmdArgs);
4828
4829  if (Args.hasFlag(options::OPT_fapplication_extension,
4830                   options::OPT_fno_application_extension, false))
4831    CmdArgs.push_back("-fapplication-extension");
4832
4833  // Handle GCC-style exception args.
4834  if (!C.getDriver().IsCLMode())
4835    addExceptionArgs(Args, InputType, TC, KernelOrKext, Runtime, CmdArgs);
4836
4837  // Handle exception personalities
4838  Arg *A = Args.getLastArg(options::OPT_fsjlj_exceptions,
4839                           options::OPT_fseh_exceptions,
4840                           options::OPT_fdwarf_exceptions);
4841  if (A) {
4842    const Option &Opt = A->getOption();
4843    if (Opt.matches(options::OPT_fsjlj_exceptions))
4844      CmdArgs.push_back("-fsjlj-exceptions");
4845    if (Opt.matches(options::OPT_fseh_exceptions))
4846      CmdArgs.push_back("-fseh-exceptions");
4847    if (Opt.matches(options::OPT_fdwarf_exceptions))
4848      CmdArgs.push_back("-fdwarf-exceptions");
4849  } else {
4850    switch (TC.GetExceptionModel(Args)) {
4851    default:
4852      break;
4853    case llvm::ExceptionHandling::DwarfCFI:
4854      CmdArgs.push_back("-fdwarf-exceptions");
4855      break;
4856    case llvm::ExceptionHandling::SjLj:
4857      CmdArgs.push_back("-fsjlj-exceptions");
4858      break;
4859    case llvm::ExceptionHandling::WinEH:
4860      CmdArgs.push_back("-fseh-exceptions");
4861      break;
4862    }
4863  }
4864
4865  // C++ "sane" operator new.
4866  if (!Args.hasFlag(options::OPT_fassume_sane_operator_new,
4867                    options::OPT_fno_assume_sane_operator_new))
4868    CmdArgs.push_back("-fno-assume-sane-operator-new");
4869
4870  // -frelaxed-template-template-args is off by default, as it is a severe
4871  // breaking change until a corresponding change to template partial ordering
4872  // is provided.
4873  if (Args.hasFlag(options::OPT_frelaxed_template_template_args,
4874                   options::OPT_fno_relaxed_template_template_args, false))
4875    CmdArgs.push_back("-frelaxed-template-template-args");
4876
4877  // -fsized-deallocation is off by default, as it is an ABI-breaking change for
4878  // most platforms.
4879  if (Args.hasFlag(options::OPT_fsized_deallocation,
4880                   options::OPT_fno_sized_deallocation, false))
4881    CmdArgs.push_back("-fsized-deallocation");
4882
4883  // -faligned-allocation is on by default in C++17 onwards and otherwise off
4884  // by default.
4885  if (Arg *A = Args.getLastArg(options::OPT_faligned_allocation,
4886                               options::OPT_fno_aligned_allocation,
4887                               options::OPT_faligned_new_EQ)) {
4888    if (A->getOption().matches(options::OPT_fno_aligned_allocation))
4889      CmdArgs.push_back("-fno-aligned-allocation");
4890    else
4891      CmdArgs.push_back("-faligned-allocation");
4892  }
4893
4894  // The default new alignment can be specified using a dedicated option or via
4895  // a GCC-compatible option that also turns on aligned allocation.
4896  if (Arg *A = Args.getLastArg(options::OPT_fnew_alignment_EQ,
4897                               options::OPT_faligned_new_EQ))
4898    CmdArgs.push_back(
4899        Args.MakeArgString(Twine("-fnew-alignment=") + A->getValue()));
4900
4901  // -fconstant-cfstrings is default, and may be subject to argument translation
4902  // on Darwin.
4903  if (!Args.hasFlag(options::OPT_fconstant_cfstrings,
4904                    options::OPT_fno_constant_cfstrings) ||
4905      !Args.hasFlag(options::OPT_mconstant_cfstrings,
4906                    options::OPT_mno_constant_cfstrings))
4907    CmdArgs.push_back("-fno-constant-cfstrings");
4908
4909  // -fno-pascal-strings is default, only pass non-default.
4910  if (Args.hasFlag(options::OPT_fpascal_strings,
4911                   options::OPT_fno_pascal_strings, false))
4912    CmdArgs.push_back("-fpascal-strings");
4913
4914  // Honor -fpack-struct= and -fpack-struct, if given. Note that
4915  // -fno-pack-struct doesn't apply to -fpack-struct=.
4916  if (Arg *A = Args.getLastArg(options::OPT_fpack_struct_EQ)) {
4917    std::string PackStructStr = "-fpack-struct=";
4918    PackStructStr += A->getValue();
4919    CmdArgs.push_back(Args.MakeArgString(PackStructStr));
4920  } else if (Args.hasFlag(options::OPT_fpack_struct,
4921                          options::OPT_fno_pack_struct, false)) {
4922    CmdArgs.push_back("-fpack-struct=1");
4923  }
4924
4925  // Handle -fmax-type-align=N and -fno-type-align
4926  bool SkipMaxTypeAlign = Args.hasArg(options::OPT_fno_max_type_align);
4927  if (Arg *A = Args.getLastArg(options::OPT_fmax_type_align_EQ)) {
4928    if (!SkipMaxTypeAlign) {
4929      std::string MaxTypeAlignStr = "-fmax-type-align=";
4930      MaxTypeAlignStr += A->getValue();
4931      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4932    }
4933  } else if (RawTriple.isOSDarwin()) {
4934    if (!SkipMaxTypeAlign) {
4935      std::string MaxTypeAlignStr = "-fmax-type-align=16";
4936      CmdArgs.push_back(Args.MakeArgString(MaxTypeAlignStr));
4937    }
4938  }
4939
4940  if (!Args.hasFlag(options::OPT_Qy, options::OPT_Qn, true))
4941    CmdArgs.push_back("-Qn");
4942
4943  // -fcommon is the default unless compiling kernel code or the target says so
4944  bool NoCommonDefault = KernelOrKext || isNoCommonDefault(RawTriple);
4945  if (!Args.hasFlag(options::OPT_fcommon, options::OPT_fno_common,
4946                    !NoCommonDefault))
4947    CmdArgs.push_back("-fno-common");
4948
4949  // -fsigned-bitfields is default, and clang doesn't yet support
4950  // -funsigned-bitfields.
4951  if (!Args.hasFlag(options::OPT_fsigned_bitfields,
4952                    options::OPT_funsigned_bitfields))
4953    D.Diag(diag::warn_drv_clang_unsupported)
4954        << Args.getLastArg(options::OPT_funsigned_bitfields)->getAsString(Args);
4955
4956  // -fsigned-bitfields is default, and clang doesn't support -fno-for-scope.
4957  if (!Args.hasFlag(options::OPT_ffor_scope, options::OPT_fno_for_scope))
4958    D.Diag(diag::err_drv_clang_unsupported)
4959        << Args.getLastArg(options::OPT_fno_for_scope)->getAsString(Args);
4960
4961  // -finput_charset=UTF-8 is default. Reject others
4962  if (Arg *inputCharset = Args.getLastArg(options::OPT_finput_charset_EQ)) {
4963    StringRef value = inputCharset->getValue();
4964    if (!value.equals_lower("utf-8"))
4965      D.Diag(diag::err_drv_invalid_value) << inputCharset->getAsString(Args)
4966                                          << value;
4967  }
4968
4969  // -fexec_charset=UTF-8 is default. Reject others
4970  if (Arg *execCharset = Args.getLastArg(options::OPT_fexec_charset_EQ)) {
4971    StringRef value = execCharset->getValue();
4972    if (!value.equals_lower("utf-8"))
4973      D.Diag(diag::err_drv_invalid_value) << execCharset->getAsString(Args)
4974                                          << value;
4975  }
4976
4977  RenderDiagnosticsOptions(D, Args, CmdArgs);
4978
4979  // -fno-asm-blocks is default.
4980  if (Args.hasFlag(options::OPT_fasm_blocks, options::OPT_fno_asm_blocks,
4981                   false))
4982    CmdArgs.push_back("-fasm-blocks");
4983
4984  // -fgnu-inline-asm is default.
4985  if (!Args.hasFlag(options::OPT_fgnu_inline_asm,
4986                    options::OPT_fno_gnu_inline_asm, true))
4987    CmdArgs.push_back("-fno-gnu-inline-asm");
4988
4989  // Enable vectorization per default according to the optimization level
4990  // selected. For optimization levels that want vectorization we use the alias
4991  // option to simplify the hasFlag logic.
4992  bool EnableVec = shouldEnableVectorizerAtOLevel(Args, false);
4993  OptSpecifier VectorizeAliasOption =
4994      EnableVec ? options::OPT_O_Group : options::OPT_fvectorize;
4995  if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
4996                   options::OPT_fno_vectorize, EnableVec))
4997    CmdArgs.push_back("-vectorize-loops");
4998
4999  // -fslp-vectorize is enabled based on the optimization level selected.
5000  bool EnableSLPVec = shouldEnableVectorizerAtOLevel(Args, true);
5001  OptSpecifier SLPVectAliasOption =
5002      EnableSLPVec ? options::OPT_O_Group : options::OPT_fslp_vectorize;
5003  if (Args.hasFlag(options::OPT_fslp_vectorize, SLPVectAliasOption,
5004                   options::OPT_fno_slp_vectorize, EnableSLPVec))
5005    CmdArgs.push_back("-vectorize-slp");
5006
5007  ParseMPreferVectorWidth(D, Args, CmdArgs);
5008
5009  if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
5010    A->render(Args, CmdArgs);
5011
5012  if (Arg *A = Args.getLastArg(
5013          options::OPT_fsanitize_undefined_strip_path_components_EQ))
5014    A->render(Args, CmdArgs);
5015
5016  // -fdollars-in-identifiers default varies depending on platform and
5017  // language; only pass if specified.
5018  if (Arg *A = Args.getLastArg(options::OPT_fdollars_in_identifiers,
5019                               options::OPT_fno_dollars_in_identifiers)) {
5020    if (A->getOption().matches(options::OPT_fdollars_in_identifiers))
5021      CmdArgs.push_back("-fdollars-in-identifiers");
5022    else
5023      CmdArgs.push_back("-fno-dollars-in-identifiers");
5024  }
5025
5026  // -funit-at-a-time is default, and we don't support -fno-unit-at-a-time for
5027  // practical purposes.
5028  if (Arg *A = Args.getLastArg(options::OPT_funit_at_a_time,
5029                               options::OPT_fno_unit_at_a_time)) {
5030    if (A->getOption().matches(options::OPT_fno_unit_at_a_time))
5031      D.Diag(diag::warn_drv_clang_unsupported) << A->getAsString(Args);
5032  }
5033
5034  if (Args.hasFlag(options::OPT_fapple_pragma_pack,
5035                   options::OPT_fno_apple_pragma_pack, false))
5036    CmdArgs.push_back("-fapple-pragma-pack");
5037
5038  // Remarks can be enabled with any of the `-f.*optimization-record.*` flags.
5039  if (Args.hasFlag(options::OPT_fsave_optimization_record,
5040                   options::OPT_foptimization_record_file_EQ,
5041                   options::OPT_fno_save_optimization_record, false) ||
5042      Args.hasFlag(options::OPT_foptimization_record_passes_EQ,
5043                   options::OPT_fno_save_optimization_record, false)) {
5044    CmdArgs.push_back("-opt-record-file");
5045
5046    const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
5047    if (A) {
5048      CmdArgs.push_back(A->getValue());
5049    } else {
5050      SmallString<128> F;
5051
5052      if (Args.hasArg(options::OPT_c) || Args.hasArg(options::OPT_S)) {
5053        if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
5054          F = FinalOutput->getValue();
5055      }
5056
5057      if (F.empty()) {
5058        // Use the input filename.
5059        F = llvm::sys::path::stem(Input.getBaseInput());
5060
5061        // If we're compiling for an offload architecture (i.e. a CUDA device),
5062        // we need to make the file name for the device compilation different
5063        // from the host compilation.
5064        if (!JA.isDeviceOffloading(Action::OFK_None) &&
5065            !JA.isDeviceOffloading(Action::OFK_Host)) {
5066          llvm::sys::path::replace_extension(F, "");
5067          F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
5068                                                   Triple.normalize());
5069          F += "-";
5070          F += JA.getOffloadingArch();
5071        }
5072      }
5073
5074      llvm::sys::path::replace_extension(F, "opt.yaml");
5075      CmdArgs.push_back(Args.MakeArgString(F));
5076    }
5077    if (const Arg *A =
5078            Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
5079      CmdArgs.push_back("-opt-record-passes");
5080      CmdArgs.push_back(A->getValue());
5081    }
5082  }
5083
5084  bool RewriteImports = Args.hasFlag(options::OPT_frewrite_imports,
5085                                     options::OPT_fno_rewrite_imports, false);
5086  if (RewriteImports)
5087    CmdArgs.push_back("-frewrite-imports");
5088
5089  // Enable rewrite includes if the user's asked for it or if we're generating
5090  // diagnostics.
5091  // TODO: Once -module-dependency-dir works with -frewrite-includes it'd be
5092  // nice to enable this when doing a crashdump for modules as well.
5093  if (Args.hasFlag(options::OPT_frewrite_includes,
5094                   options::OPT_fno_rewrite_includes, false) ||
5095      (C.isForDiagnostics() && !HaveModules))
5096    CmdArgs.push_back("-frewrite-includes");
5097
5098  // Only allow -traditional or -traditional-cpp outside in preprocessing modes.
5099  if (Arg *A = Args.getLastArg(options::OPT_traditional,
5100                               options::OPT_traditional_cpp)) {
5101    if (isa<PreprocessJobAction>(JA))
5102      CmdArgs.push_back("-traditional-cpp");
5103    else
5104      D.Diag(diag::err_drv_clang_unsupported) << A->getAsString(Args);
5105  }
5106
5107  Args.AddLastArg(CmdArgs, options::OPT_dM);
5108  Args.AddLastArg(CmdArgs, options::OPT_dD);
5109
5110  // Handle serialized diagnostics.
5111  if (Arg *A = Args.getLastArg(options::OPT__serialize_diags)) {
5112    CmdArgs.push_back("-serialize-diagnostic-file");
5113    CmdArgs.push_back(Args.MakeArgString(A->getValue()));
5114  }
5115
5116  if (Args.hasArg(options::OPT_fretain_comments_from_system_headers))
5117    CmdArgs.push_back("-fretain-comments-from-system-headers");
5118
5119  // Forward -fcomment-block-commands to -cc1.
5120  Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
5121  // Forward -fparse-all-comments to -cc1.
5122  Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
5123
5124  // Turn -fplugin=name.so into -load name.so
5125  for (const Arg *A : Args.filtered(options::OPT_fplugin_EQ)) {
5126    CmdArgs.push_back("-load");
5127    CmdArgs.push_back(A->getValue());
5128    A->claim();
5129  }
5130
5131  // Forward -fpass-plugin=name.so to -cc1.
5132  for (const Arg *A : Args.filtered(options::OPT_fpass_plugin_EQ)) {
5133    CmdArgs.push_back(
5134        Args.MakeArgString(Twine("-fpass-plugin=") + A->getValue()));
5135    A->claim();
5136  }
5137
5138  // Setup statistics file output.
5139  SmallString<128> StatsFile = getStatsFileName(Args, Output, Input, D);
5140  if (!StatsFile.empty())
5141    CmdArgs.push_back(Args.MakeArgString(Twine("-stats-file=") + StatsFile));
5142
5143  // Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
5144  // parser.
5145  // -finclude-default-header flag is for preprocessor,
5146  // do not pass it to other cc1 commands when save-temps is enabled
5147  if (C.getDriver().isSaveTempsEnabled() &&
5148      !isa<PreprocessJobAction>(JA)) {
5149    for (auto Arg : Args.filtered(options::OPT_Xclang)) {
5150      Arg->claim();
5151      if (StringRef(Arg->getValue()) != "-finclude-default-header")
5152        CmdArgs.push_back(Arg->getValue());
5153    }
5154  }
5155  else {
5156    Args.AddAllArgValues(CmdArgs, options::OPT_Xclang);
5157  }
5158  for (const Arg *A : Args.filtered(options::OPT_mllvm)) {
5159    A->claim();
5160
5161    // We translate this by hand to the -cc1 argument, since nightly test uses
5162    // it and developers have been trained to spell it with -mllvm. Both
5163    // spellings are now deprecated and should be removed.
5164    if (StringRef(A->getValue(0)) == "-disable-llvm-optzns") {
5165      CmdArgs.push_back("-disable-llvm-optzns");
5166    } else {
5167      A->render(Args, CmdArgs);
5168    }
5169  }
5170
5171  // With -save-temps, we want to save the unoptimized bitcode output from the
5172  // CompileJobAction, use -disable-llvm-passes to get pristine IR generated
5173  // by the frontend.
5174  // When -fembed-bitcode is enabled, optimized bitcode is emitted because it
5175  // has slightly different breakdown between stages.
5176  // FIXME: -fembed-bitcode -save-temps will save optimized bitcode instead of
5177  // pristine IR generated by the frontend. Ideally, a new compile action should
5178  // be added so both IR can be captured.
5179  if (C.getDriver().isSaveTempsEnabled() &&
5180      !(C.getDriver().embedBitcodeInObject() && !C.getDriver().isUsingLTO()) &&
5181      isa<CompileJobAction>(JA))
5182    CmdArgs.push_back("-disable-llvm-passes");
5183
5184  if (Output.getType() == types::TY_Dependencies) {
5185    // Handled with other dependency code.
5186  } else if (Output.isFilename()) {
5187    CmdArgs.push_back("-o");
5188    CmdArgs.push_back(Output.getFilename());
5189  } else {
5190     (0) . __assert_fail ("Output.isNothing() && \"Invalid output.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 5190, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Output.isNothing() && "Invalid output.");
5191  }
5192
5193  addDashXForInput(Args, Input, CmdArgs);
5194
5195  ArrayRef<InputInfo> FrontendInputs = Input;
5196  if (IsHeaderModulePrecompile)
5197    FrontendInputs = ModuleHeaderInputs;
5198  else if (Input.isNothing())
5199    FrontendInputs = {};
5200
5201  for (const InputInfo &Input : FrontendInputs) {
5202    if (Input.isFilename())
5203      CmdArgs.push_back(Input.getFilename());
5204    else
5205      Input.getInputArg().renderAsInput(Args, CmdArgs);
5206  }
5207
5208  Args.AddAllArgs(CmdArgs, options::OPT_undef);
5209
5210  const char *Exec = D.getClangProgramPath();
5211
5212  // Optionally embed the -cc1 level arguments into the debug info or a
5213  // section, for build analysis.
5214  // Also record command line arguments into the debug info if
5215  // -grecord-gcc-switches options is set on.
5216  // By default, -gno-record-gcc-switches is set on and no recording.
5217  auto GRecordSwitches =
5218      Args.hasFlag(options::OPT_grecord_command_line,
5219                   options::OPT_gno_record_command_line, false);
5220  auto FRecordSwitches =
5221      Args.hasFlag(options::OPT_frecord_command_line,
5222                   options::OPT_fno_record_command_line, false);
5223  if (FRecordSwitches && !Triple.isOSBinFormatELF())
5224    D.Diag(diag::err_drv_unsupported_opt_for_target)
5225        << Args.getLastArg(options::OPT_frecord_command_line)->getAsString(Args)
5226        << TripleStr;
5227  if (TC.UseDwarfDebugFlags() || GRecordSwitches || FRecordSwitches) {
5228    ArgStringList OriginalArgs;
5229    for (const auto &Arg : Args)
5230      Arg->render(Args, OriginalArgs);
5231
5232    SmallString<256> Flags;
5233    Flags += Exec;
5234    for (const char *OriginalArg : OriginalArgs) {
5235      SmallString<128> EscapedArg;
5236      EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
5237      Flags += " ";
5238      Flags += EscapedArg;
5239    }
5240    auto FlagsArgString = Args.MakeArgString(Flags);
5241    if (TC.UseDwarfDebugFlags() || GRecordSwitches) {
5242      CmdArgs.push_back("-dwarf-debug-flags");
5243      CmdArgs.push_back(FlagsArgString);
5244    }
5245    if (FRecordSwitches) {
5246      CmdArgs.push_back("-record-command-line");
5247      CmdArgs.push_back(FlagsArgString);
5248    }
5249  }
5250
5251  // Host-side cuda compilation receives all device-side outputs in a single
5252  // fatbin as Inputs[1]. Include the binary with -fcuda-include-gpubinary.
5253  if ((IsCuda || IsHIP) && CudaDeviceInput) {
5254      CmdArgs.push_back("-fcuda-include-gpubinary");
5255      CmdArgs.push_back(CudaDeviceInput->getFilename());
5256      if (Args.hasFlag(options::OPT_fgpu_rdc, options::OPT_fno_gpu_rdc, false))
5257        CmdArgs.push_back("-fgpu-rdc");
5258  }
5259
5260  if (IsCuda) {
5261    if (Args.hasFlag(options::OPT_fcuda_short_ptr,
5262                     options::OPT_fno_cuda_short_ptr, false))
5263      CmdArgs.push_back("-fcuda-short-ptr");
5264  }
5265
5266  // OpenMP offloading device jobs take the argument -fopenmp-host-ir-file-path
5267  // to specify the result of the compile phase on the host, so the meaningful
5268  // device declarations can be identified. Also, -fopenmp-is-device is passed
5269  // along to tell the frontend that it is generating code for a device, so that
5270  // only the relevant declarations are emitted.
5271  if (IsOpenMPDevice) {
5272    CmdArgs.push_back("-fopenmp-is-device");
5273    if (OpenMPDeviceInput) {
5274      CmdArgs.push_back("-fopenmp-host-ir-file-path");
5275      CmdArgs.push_back(Args.MakeArgString(OpenMPDeviceInput->getFilename()));
5276    }
5277  }
5278
5279  // For all the host OpenMP offloading compile jobs we need to pass the targets
5280  // information using -fopenmp-targets= option.
5281  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
5282    SmallString<128> TargetInfo("-fopenmp-targets=");
5283
5284    Arg *Tgts = Args.getLastArg(options::OPT_fopenmp_targets_EQ);
5285     (0) . __assert_fail ("Tgts && Tgts->getNumValues() && \"OpenMP offloading has to have targets specified.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 5286, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Tgts && Tgts->getNumValues() &&
5286 (0) . __assert_fail ("Tgts && Tgts->getNumValues() && \"OpenMP offloading has to have targets specified.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 5286, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">           "OpenMP offloading has to have targets specified.");
5287    for (unsigned i = 0; i < Tgts->getNumValues(); ++i) {
5288      if (i)
5289        TargetInfo += ',';
5290      // We need to get the string from the triple because it may be not exactly
5291      // the same as the one we get directly from the arguments.
5292      llvm::Triple T(Tgts->getValue(i));
5293      TargetInfo += T.getTriple();
5294    }
5295    CmdArgs.push_back(Args.MakeArgString(TargetInfo.str()));
5296  }
5297
5298  bool WholeProgramVTables =
5299      Args.hasFlag(options::OPT_fwhole_program_vtables,
5300                   options::OPT_fno_whole_program_vtables, false);
5301  if (WholeProgramVTables) {
5302    if (!D.isUsingLTO())
5303      D.Diag(diag::err_drv_argument_only_allowed_with)
5304          << "-fwhole-program-vtables"
5305          << "-flto";
5306    CmdArgs.push_back("-fwhole-program-vtables");
5307  }
5308
5309  bool RequiresSplitLTOUnit = WholeProgramVTables || Sanitize.needsLTO();
5310  bool SplitLTOUnit =
5311      Args.hasFlag(options::OPT_fsplit_lto_unit,
5312                   options::OPT_fno_split_lto_unit, RequiresSplitLTOUnit);
5313  if (RequiresSplitLTOUnit && !SplitLTOUnit)
5314    D.Diag(diag::err_drv_argument_not_allowed_with)
5315        << "-fno-split-lto-unit"
5316        << (WholeProgramVTables ? "-fwhole-program-vtables" : "-fsanitize=cfi");
5317  if (SplitLTOUnit)
5318    CmdArgs.push_back("-fsplit-lto-unit");
5319
5320  if (Arg *A = Args.getLastArg(options::OPT_fexperimental_isel,
5321                               options::OPT_fno_experimental_isel)) {
5322    CmdArgs.push_back("-mllvm");
5323    if (A->getOption().matches(options::OPT_fexperimental_isel)) {
5324      CmdArgs.push_back("-global-isel=1");
5325
5326      // GISel is on by default on AArch64 -O0, so don't bother adding
5327      // the fallback remarks for it. Other combinations will add a warning of
5328      // some kind.
5329      bool IsArchSupported = Triple.getArch() == llvm::Triple::aarch64;
5330      bool IsOptLevelSupported = false;
5331
5332      Arg *A = Args.getLastArg(options::OPT_O_Group);
5333      if (Triple.getArch() == llvm::Triple::aarch64) {
5334        if (!A || A->getOption().matches(options::OPT_O0))
5335          IsOptLevelSupported = true;
5336      }
5337      if (!IsArchSupported || !IsOptLevelSupported) {
5338        CmdArgs.push_back("-mllvm");
5339        CmdArgs.push_back("-global-isel-abort=2");
5340
5341        if (!IsArchSupported)
5342          D.Diag(diag::warn_drv_experimental_isel_incomplete) << Triple.getArchName();
5343        else
5344          D.Diag(diag::warn_drv_experimental_isel_incomplete_opt);
5345      }
5346    } else {
5347      CmdArgs.push_back("-global-isel=0");
5348    }
5349  }
5350
5351  if (Args.hasArg(options::OPT_forder_file_instrumentation)) {
5352     CmdArgs.push_back("-forder-file-instrumentation");
5353     // Enable order file instrumentation when ThinLTO is not on. When ThinLTO is
5354     // on, we need to pass these flags as linker flags and that will be handled
5355     // outside of the compiler.
5356     if (!D.isUsingLTO()) {
5357       CmdArgs.push_back("-mllvm");
5358       CmdArgs.push_back("-enable-order-file-instrumentation");
5359     }
5360  }
5361
5362  if (Arg *A = Args.getLastArg(options::OPT_fforce_enable_int128,
5363                               options::OPT_fno_force_enable_int128)) {
5364    if (A->getOption().matches(options::OPT_fforce_enable_int128))
5365      CmdArgs.push_back("-fforce-enable-int128");
5366  }
5367
5368  if (Args.hasFlag(options::OPT_fcomplete_member_pointers,
5369                   options::OPT_fno_complete_member_pointers, false))
5370    CmdArgs.push_back("-fcomplete-member-pointers");
5371
5372  if (!Args.hasFlag(options::OPT_fcxx_static_destructors,
5373                    options::OPT_fno_cxx_static_destructors, true))
5374    CmdArgs.push_back("-fno-c++-static-destructors");
5375
5376  if (Arg *A = Args.getLastArg(options::OPT_moutline,
5377                               options::OPT_mno_outline)) {
5378    if (A->getOption().matches(options::OPT_moutline)) {
5379      // We only support -moutline in AArch64 right now. If we're not compiling
5380      // for AArch64, emit a warning and ignore the flag. Otherwise, add the
5381      // proper mllvm flags.
5382      if (Triple.getArch() != llvm::Triple::aarch64) {
5383        D.Diag(diag::warn_drv_moutline_unsupported_opt) << Triple.getArchName();
5384      } else {
5385          CmdArgs.push_back("-mllvm");
5386          CmdArgs.push_back("-enable-machine-outliner");
5387      }
5388    } else {
5389      // Disable all outlining behaviour.
5390      CmdArgs.push_back("-mllvm");
5391      CmdArgs.push_back("-enable-machine-outliner=never");
5392    }
5393  }
5394
5395  if (Args.hasFlag(options::OPT_faddrsig, options::OPT_fno_addrsig,
5396                   (TC.getTriple().isOSBinFormatELF() ||
5397                    TC.getTriple().isOSBinFormatCOFF()) &&
5398                      !TC.getTriple().isPS4() &&
5399                      !TC.getTriple().isOSNetBSD() &&
5400                      !Distro(D.getVFS()).IsGentoo() &&
5401                      !TC.getTriple().isAndroid() &&
5402                       TC.useIntegratedAs()))
5403    CmdArgs.push_back("-faddrsig");
5404
5405  // Finally add the compile command to the compilation.
5406  if (Args.hasArg(options::OPT__SLASH_fallback) &&
5407      Output.getType() == types::TY_Object &&
5408      (InputType == types::TY_C || InputType == types::TY_CXX)) {
5409    auto CLCommand =
5410        getCLFallback()->GetCommand(C, JA, Output, Inputs, Args, LinkingOutput);
5411    C.addCommand(llvm::make_unique<FallbackCommand>(
5412        JA, *this, Exec, CmdArgs, Inputs, std::move(CLCommand)));
5413  } else if (Args.hasArg(options::OPT__SLASH_fallback) &&
5414             isa<PrecompileJobAction>(JA)) {
5415    // In /fallback builds, run the main compilation even if the pch generation
5416    // fails, so that the main compilation's fallback to cl.exe runs.
5417    C.addCommand(llvm::make_unique<ForceSuccessCommand>(JA, *this, Exec,
5418                                                        CmdArgs, Inputs));
5419  } else {
5420    C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
5421  }
5422
5423  // Make the compile command echo its inputs for /showFilenames.
5424  if (Output.getType() == types::TY_Object &&
5425      Args.hasFlag(options::OPT__SLASH_showFilenames,
5426                   options::OPT__SLASH_showFilenames_, false)) {
5427    C.getJobs().getJobs().back()->setPrintInputFilenames(true);
5428  }
5429
5430  if (Arg *A = Args.getLastArg(options::OPT_pg))
5431    if (!shouldUseFramePointer(Args, Triple))
5432      D.Diag(diag::err_drv_argument_not_allowed_with) << "-fomit-frame-pointer"
5433                                                      << A->getAsString(Args);
5434
5435  // Claim some arguments which clang supports automatically.
5436
5437  // -fpch-preprocess is used with gcc to add a special marker in the output to
5438  // include the PCH file.
5439  Args.ClaimAllArgs(options::OPT_fpch_preprocess);
5440
5441  // Claim some arguments which clang doesn't support, but we don't
5442  // care to warn the user about.
5443  Args.ClaimAllArgs(options::OPT_clang_ignored_f_Group);
5444  Args.ClaimAllArgs(options::OPT_clang_ignored_m_Group);
5445
5446  // Disable warnings for clang -E -emit-llvm foo.c
5447  Args.ClaimAllArgs(options::OPT_emit_llvm);
5448}
5449
5450Clang::Clang(const ToolChain &TC)
5451    // CAUTION! The first constructor argument ("clang") is not arbitrary,
5452    // as it is for other tools. Some operations on a Tool actually test
5453    // whether that tool is Clang based on the Tool's Name as a string.
5454    : Tool("clang""clang frontend", TC, RF_Full) {}
5455
5456Clang::~Clang() {}
5457
5458/// Add options related to the Objective-C runtime/ABI.
5459///
5460/// Returns true if the runtime is non-fragile.
5461ObjCRuntime Clang::AddObjCRuntimeArgs(const ArgList &args,
5462                                      ArgStringList &cmdArgs,
5463                                      RewriteKind rewriteKind) const {
5464  // Look for the controlling runtime option.
5465  Arg *runtimeArg =
5466      args.getLastArg(options::OPT_fnext_runtime, options::OPT_fgnu_runtime,
5467                      options::OPT_fobjc_runtime_EQ);
5468
5469  // Just forward -fobjc-runtime= to the frontend.  This supercedes
5470  // options about fragility.
5471  if (runtimeArg &&
5472      runtimeArg->getOption().matches(options::OPT_fobjc_runtime_EQ)) {
5473    ObjCRuntime runtime;
5474    StringRef value = runtimeArg->getValue();
5475    if (runtime.tryParse(value)) {
5476      getToolChain().getDriver().Diag(diag::err_drv_unknown_objc_runtime)
5477          << value;
5478    }
5479    if ((runtime.getKind() == ObjCRuntime::GNUstep) &&
5480        (runtime.getVersion() >= VersionTuple(20)))
5481      if (!getToolChain().getTriple().isOSBinFormatELF() &&
5482          !getToolChain().getTriple().isOSBinFormatCOFF()) {
5483        getToolChain().getDriver().Diag(
5484            diag::err_drv_gnustep_objc_runtime_incompatible_binary)
5485          << runtime.getVersion().getMajor();
5486      }
5487
5488    runtimeArg->render(args, cmdArgs);
5489    return runtime;
5490  }
5491
5492  // Otherwise, we'll need the ABI "version".  Version numbers are
5493  // slightly confusing for historical reasons:
5494  //   1 - Traditional "fragile" ABI
5495  //   2 - Non-fragile ABI, version 1
5496  //   3 - Non-fragile ABI, version 2
5497  unsigned objcABIVersion = 1;
5498  // If -fobjc-abi-version= is present, use that to set the version.
5499  if (Arg *abiArg = args.getLastArg(options::OPT_fobjc_abi_version_EQ)) {
5500    StringRef value = abiArg->getValue();
5501    if (value == "1")
5502      objcABIVersion = 1;
5503    else if (value == "2")
5504      objcABIVersion = 2;
5505    else if (value == "3")
5506      objcABIVersion = 3;
5507    else
5508      getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported) << value;
5509  } else {
5510    // Otherwise, determine if we are using the non-fragile ABI.
5511    bool nonFragileABIIsDefault =
5512        (rewriteKind == RK_NonFragile ||
5513         (rewriteKind == RK_None &&
5514          getToolChain().IsObjCNonFragileABIDefault()));
5515    if (args.hasFlag(options::OPT_fobjc_nonfragile_abi,
5516                     options::OPT_fno_objc_nonfragile_abi,
5517                     nonFragileABIIsDefault)) {
5518// Determine the non-fragile ABI version to use.
5519#ifdef DISABLE_DEFAULT_NONFRAGILEABI_TWO
5520      unsigned nonFragileABIVersion = 1;
5521#else
5522      unsigned nonFragileABIVersion = 2;
5523#endif
5524
5525      if (Arg *abiArg =
5526              args.getLastArg(options::OPT_fobjc_nonfragile_abi_version_EQ)) {
5527        StringRef value = abiArg->getValue();
5528        if (value == "1")
5529          nonFragileABIVersion = 1;
5530        else if (value == "2")
5531          nonFragileABIVersion = 2;
5532        else
5533          getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
5534              << value;
5535      }
5536
5537      objcABIVersion = 1 + nonFragileABIVersion;
5538    } else {
5539      objcABIVersion = 1;
5540    }
5541  }
5542
5543  // We don't actually care about the ABI version other than whether
5544  // it's non-fragile.
5545  bool isNonFragile = objcABIVersion != 1;
5546
5547  // If we have no runtime argument, ask the toolchain for its default runtime.
5548  // However, the rewriter only really supports the Mac runtime, so assume that.
5549  ObjCRuntime runtime;
5550  if (!runtimeArg) {
5551    switch (rewriteKind) {
5552    case RK_None:
5553      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5554      break;
5555    case RK_Fragile:
5556      runtime = ObjCRuntime(ObjCRuntime::FragileMacOSX, VersionTuple());
5557      break;
5558    case RK_NonFragile:
5559      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5560      break;
5561    }
5562
5563    // -fnext-runtime
5564  } else if (runtimeArg->getOption().matches(options::OPT_fnext_runtime)) {
5565    // On Darwin, make this use the default behavior for the toolchain.
5566    if (getToolChain().getTriple().isOSDarwin()) {
5567      runtime = getToolChain().getDefaultObjCRuntime(isNonFragile);
5568
5569      // Otherwise, build for a generic macosx port.
5570    } else {
5571      runtime = ObjCRuntime(ObjCRuntime::MacOSX, VersionTuple());
5572    }
5573
5574    // -fgnu-runtime
5575  } else {
5576    getOption().matches(options..OPT_fgnu_runtime)", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 5576, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(runtimeArg->getOption().matches(options::OPT_fgnu_runtime));
5577    // Legacy behaviour is to target the gnustep runtime if we are in
5578    // non-fragile mode or the GCC runtime in fragile mode.
5579    if (isNonFragile)
5580      runtime = ObjCRuntime(ObjCRuntime::GNUstep, VersionTuple(20));
5581    else
5582      runtime = ObjCRuntime(ObjCRuntime::GCC, VersionTuple());
5583  }
5584
5585  cmdArgs.push_back(
5586      args.MakeArgString("-fobjc-runtime=" + runtime.getAsString()));
5587  return runtime;
5588}
5589
5590static bool maybeConsumeDash(const std::string &EH, size_t &I) {
5591  bool HaveDash = (I + 1 < EH.size() && EH[I + 1] == '-');
5592  I += HaveDash;
5593  return !HaveDash;
5594}
5595
5596namespace {
5597struct EHFlags {
5598  bool Synch = false;
5599  bool Asynch = false;
5600  bool NoUnwindC = false;
5601};
5602// end anonymous namespace
5603
5604/// /EH controls whether to run destructor cleanups when exceptions are
5605/// thrown.  There are three modifiers:
5606/// - s: Cleanup after "synchronous" exceptions, aka C++ exceptions.
5607/// - a: Cleanup after "asynchronous" exceptions, aka structured exceptions.
5608///      The 'a' modifier is unimplemented and fundamentally hard in LLVM IR.
5609/// - c: Assume that extern "C" functions are implicitly nounwind.
5610/// The default is /EHs-c-, meaning cleanups are disabled.
5611static EHFlags parseClangCLEHFlags(const Driver &Dconst ArgList &Args) {
5612  EHFlags EH;
5613
5614  std::vector<std::stringEHArgs =
5615      Args.getAllArgValues(options::OPT__SLASH_EH);
5616  for (auto EHVal : EHArgs) {
5617    for (size_t I = 0, E = EHVal.size(); I != E; ++I) {
5618      switch (EHVal[I]) {
5619      case 'a':
5620        EH.Asynch = maybeConsumeDash(EHVal, I);
5621        if (EH.Asynch)
5622          EH.Synch = false;
5623        continue;
5624      case 'c':
5625        EH.NoUnwindC = maybeConsumeDash(EHVal, I);
5626        continue;
5627      case 's':
5628        EH.Synch = maybeConsumeDash(EHVal, I);
5629        if (EH.Synch)
5630          EH.Asynch = false;
5631        continue;
5632      default:
5633        break;
5634      }
5635      D.Diag(clang::diag::err_drv_invalid_value) << "/EH" << EHVal;
5636      break;
5637    }
5638  }
5639  // The /GX, /GX- flags are only processed if there are not /EH flags.
5640  // The default is that /GX is not specified.
5641  if (EHArgs.empty() &&
5642      Args.hasFlag(options::OPT__SLASH_GX, options::OPT__SLASH_GX_,
5643                   /*default=*/false)) {
5644    EH.Synch = true;
5645    EH.NoUnwindC = true;
5646  }
5647
5648  return EH;
5649}
5650
5651void Clang::AddClangCLArgs(const ArgList &Args, types::ID InputType,
5652                           ArgStringList &CmdArgs,
5653                           codegenoptions::DebugInfoKind *DebugInfoKind,
5654                           bool *EmitCodeView) const {
5655  unsigned RTOptionID = options::OPT__SLASH_MT;
5656
5657  if (Args.hasArg(options::OPT__SLASH_LDd))
5658    // The /LDd option implies /MTd. The dependent lib part can be overridden,
5659    // but defining _DEBUG is sticky.
5660    RTOptionID = options::OPT__SLASH_MTd;
5661
5662  if (Arg *A = Args.getLastArg(options::OPT__SLASH_M_Group))
5663    RTOptionID = A->getOption().getID();
5664
5665  StringRef FlagForCRT;
5666  switch (RTOptionID) {
5667  case options::OPT__SLASH_MD:
5668    if (Args.hasArg(options::OPT__SLASH_LDd))
5669      CmdArgs.push_back("-D_DEBUG");
5670    CmdArgs.push_back("-D_MT");
5671    CmdArgs.push_back("-D_DLL");
5672    FlagForCRT = "--dependent-lib=msvcrt";
5673    break;
5674  case options::OPT__SLASH_MDd:
5675    CmdArgs.push_back("-D_DEBUG");
5676    CmdArgs.push_back("-D_MT");
5677    CmdArgs.push_back("-D_DLL");
5678    FlagForCRT = "--dependent-lib=msvcrtd";
5679    break;
5680  case options::OPT__SLASH_MT:
5681    if (Args.hasArg(options::OPT__SLASH_LDd))
5682      CmdArgs.push_back("-D_DEBUG");
5683    CmdArgs.push_back("-D_MT");
5684    CmdArgs.push_back("-flto-visibility-public-std");
5685    FlagForCRT = "--dependent-lib=libcmt";
5686    break;
5687  case options::OPT__SLASH_MTd:
5688    CmdArgs.push_back("-D_DEBUG");
5689    CmdArgs.push_back("-D_MT");
5690    CmdArgs.push_back("-flto-visibility-public-std");
5691    FlagForCRT = "--dependent-lib=libcmtd";
5692    break;
5693  default:
5694    llvm_unreachable("Unexpected option ID.");
5695  }
5696
5697  if (Args.hasArg(options::OPT__SLASH_Zl)) {
5698    CmdArgs.push_back("-D_VC_NODEFAULTLIB");
5699  } else {
5700    CmdArgs.push_back(FlagForCRT.data());
5701
5702    // This provides POSIX compatibility (maps 'open' to '_open'), which most
5703    // users want.  The /Za flag to cl.exe turns this off, but it's not
5704    // implemented in clang.
5705    CmdArgs.push_back("--dependent-lib=oldnames");
5706  }
5707
5708  if (Arg *A = Args.getLastArg(options::OPT_show_includes))
5709    A->render(Args, CmdArgs);
5710
5711  // This controls whether or not we emit RTTI data for polymorphic types.
5712  if (Args.hasFlag(options::OPT__SLASH_GR_, options::OPT__SLASH_GR,
5713                   /*default=*/false))
5714    CmdArgs.push_back("-fno-rtti-data");
5715
5716  // This controls whether or not we emit stack-protector instrumentation.
5717  // In MSVC, Buffer Security Check (/GS) is on by default.
5718  if (Args.hasFlag(options::OPT__SLASH_GS, options::OPT__SLASH_GS_,
5719                   /*default=*/true)) {
5720    CmdArgs.push_back("-stack-protector");
5721    CmdArgs.push_back(Args.MakeArgString(Twine(LangOptions::SSPStrong)));
5722  }
5723
5724  // Emit CodeView if -Z7, -Zd, or -gline-tables-only are present.
5725  if (Arg *DebugInfoArg =
5726          Args.getLastArg(options::OPT__SLASH_Z7, options::OPT__SLASH_Zd,
5727                          options::OPT_gline_tables_only)) {
5728    *EmitCodeView = true;
5729    if (DebugInfoArg->getOption().matches(options::OPT__SLASH_Z7))
5730      *DebugInfoKind = codegenoptions::LimitedDebugInfo;
5731    else
5732      *DebugInfoKind = codegenoptions::DebugLineTablesOnly;
5733  } else {
5734    *EmitCodeView = false;
5735  }
5736
5737  const Driver &D = getToolChain().getDriver();
5738  EHFlags EH = parseClangCLEHFlags(D, Args);
5739  if (EH.Synch || EH.Asynch) {
5740    if (types::isCXX(InputType))
5741      CmdArgs.push_back("-fcxx-exceptions");
5742    CmdArgs.push_back("-fexceptions");
5743  }
5744  if (types::isCXX(InputType) && EH.Synch && EH.NoUnwindC)
5745    CmdArgs.push_back("-fexternc-nounwind");
5746
5747  // /EP should expand to -E -P.
5748  if (Args.hasArg(options::OPT__SLASH_EP)) {
5749    CmdArgs.push_back("-E");
5750    CmdArgs.push_back("-P");
5751  }
5752
5753  unsigned VolatileOptionID;
5754  if (getToolChain().getArch() == llvm::Triple::x86_64 ||
5755      getToolChain().getArch() == llvm::Triple::x86)
5756    VolatileOptionID = options::OPT__SLASH_volatile_ms;
5757  else
5758    VolatileOptionID = options::OPT__SLASH_volatile_iso;
5759
5760  if (Arg *A = Args.getLastArg(options::OPT__SLASH_volatile_Group))
5761    VolatileOptionID = A->getOption().getID();
5762
5763  if (VolatileOptionID == options::OPT__SLASH_volatile_ms)
5764    CmdArgs.push_back("-fms-volatile");
5765
5766 if (Args.hasFlag(options::OPT__SLASH_Zc_dllexportInlines_,
5767                  options::OPT__SLASH_Zc_dllexportInlines,
5768                  false)) {
5769   if (Args.hasArg(options::OPT__SLASH_fallback)) {
5770     D.Diag(clang::diag::err_drv_dllexport_inlines_and_fallback);
5771   } else {
5772    CmdArgs.push_back("-fno-dllexport-inlines");
5773   }
5774 }
5775
5776  Arg *MostGeneralArg = Args.getLastArg(options::OPT__SLASH_vmg);
5777  Arg *BestCaseArg = Args.getLastArg(options::OPT__SLASH_vmb);
5778  if (MostGeneralArg && BestCaseArg)
5779    D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5780        << MostGeneralArg->getAsString(Args) << BestCaseArg->getAsString(Args);
5781
5782  if (MostGeneralArg) {
5783    Arg *SingleArg = Args.getLastArg(options::OPT__SLASH_vms);
5784    Arg *MultipleArg = Args.getLastArg(options::OPT__SLASH_vmm);
5785    Arg *VirtualArg = Args.getLastArg(options::OPT__SLASH_vmv);
5786
5787    Arg *FirstConflict = SingleArg ? SingleArg : MultipleArg;
5788    Arg *SecondConflict = VirtualArg ? VirtualArg : MultipleArg;
5789    if (FirstConflict && SecondConflict && FirstConflict != SecondConflict)
5790      D.Diag(clang::diag::err_drv_argument_not_allowed_with)
5791          << FirstConflict->getAsString(Args)
5792          << SecondConflict->getAsString(Args);
5793
5794    if (SingleArg)
5795      CmdArgs.push_back("-fms-memptr-rep=single");
5796    else if (MultipleArg)
5797      CmdArgs.push_back("-fms-memptr-rep=multiple");
5798    else
5799      CmdArgs.push_back("-fms-memptr-rep=virtual");
5800  }
5801
5802  // Parse the default calling convention options.
5803  if (Arg *CCArg =
5804          Args.getLastArg(options::OPT__SLASH_Gd, options::OPT__SLASH_Gr,
5805                          options::OPT__SLASH_Gz, options::OPT__SLASH_Gv,
5806                          options::OPT__SLASH_Gregcall)) {
5807    unsigned DCCOptId = CCArg->getOption().getID();
5808    const char *DCCFlag = nullptr;
5809    bool ArchSupported = true;
5810    llvm::Triple::ArchType Arch = getToolChain().getArch();
5811    switch (DCCOptId) {
5812    case options::OPT__SLASH_Gd:
5813      DCCFlag = "-fdefault-calling-conv=cdecl";
5814      break;
5815    case options::OPT__SLASH_Gr:
5816      ArchSupported = Arch == llvm::Triple::x86;
5817      DCCFlag = "-fdefault-calling-conv=fastcall";
5818      break;
5819    case options::OPT__SLASH_Gz:
5820      ArchSupported = Arch == llvm::Triple::x86;
5821      DCCFlag = "-fdefault-calling-conv=stdcall";
5822      break;
5823    case options::OPT__SLASH_Gv:
5824      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5825      DCCFlag = "-fdefault-calling-conv=vectorcall";
5826      break;
5827    case options::OPT__SLASH_Gregcall:
5828      ArchSupported = Arch == llvm::Triple::x86 || Arch == llvm::Triple::x86_64;
5829      DCCFlag = "-fdefault-calling-conv=regcall";
5830      break;
5831    }
5832
5833    // MSVC doesn't warn if /Gr or /Gz is used on x64, so we don't either.
5834    if (ArchSupported && DCCFlag)
5835      CmdArgs.push_back(DCCFlag);
5836  }
5837
5838  if (Arg *A = Args.getLastArg(options::OPT_vtordisp_mode_EQ))
5839    A->render(Args, CmdArgs);
5840
5841  if (!Args.hasArg(options::OPT_fdiagnostics_format_EQ)) {
5842    CmdArgs.push_back("-fdiagnostics-format");
5843    if (Args.hasArg(options::OPT__SLASH_fallback))
5844      CmdArgs.push_back("msvc-fallback");
5845    else
5846      CmdArgs.push_back("msvc");
5847  }
5848
5849  if (Arg *A = Args.getLastArg(options::OPT__SLASH_guard)) {
5850    SmallVector<StringRef, 1> SplitArgs;
5851    StringRef(A->getValue()).split(SplitArgs, ",");
5852    bool Instrument = false;
5853    bool NoChecks = false;
5854    for (StringRef Arg : SplitArgs) {
5855      if (Arg.equals_lower("cf"))
5856        Instrument = true;
5857      else if (Arg.equals_lower("cf-"))
5858        Instrument = false;
5859      else if (Arg.equals_lower("nochecks"))
5860        NoChecks = true;
5861      else if (Arg.equals_lower("nochecks-"))
5862        NoChecks = false;
5863      else
5864        D.Diag(diag::err_drv_invalid_value) << A->getSpelling() << Arg;
5865    }
5866    // Currently there's no support emitting CFG instrumentation; the flag only
5867    // emits the table of address-taken functions.
5868    if (Instrument || NoChecks)
5869      CmdArgs.push_back("-cfguard");
5870  }
5871}
5872
5873visualstudio::Compiler *Clang::getCLFallback() const {
5874  if (!CLFallback)
5875    CLFallback.reset(new visualstudio::Compiler(getToolChain()));
5876  return CLFallback.get();
5877}
5878
5879
5880const char *Clang::getBaseInputName(const ArgList &Args,
5881                                    const InputInfo &Input) {
5882  return Args.MakeArgString(llvm::sys::path::filename(Input.getBaseInput()));
5883}
5884
5885const char *Clang::getBaseInputStem(const ArgList &Args,
5886                                    const InputInfoList &Inputs) {
5887  const char *Str = getBaseInputName(Args, Inputs[0]);
5888
5889  if (const char *End = strrchr(Str, '.'))
5890    return Args.MakeArgString(std::string(Str, End));
5891
5892  return Str;
5893}
5894
5895const char *Clang::getDependencyFileName(const ArgList &Args,
5896                                         const InputInfoList &Inputs) {
5897  // FIXME: Think about this more.
5898  std::string Res;
5899
5900  if (Arg *OutputOpt = Args.getLastArg(options::OPT_o)) {
5901    std::string Str(OutputOpt->getValue());
5902    Res = Str.substr(0, Str.rfind('.'));
5903  } else {
5904    Res = getBaseInputStem(Args, Inputs);
5905  }
5906  return Args.MakeArgString(Res + ".d");
5907}
5908
5909// Begin ClangAs
5910
5911void ClangAs::AddMIPSTargetArgs(const ArgList &Args,
5912                                ArgStringList &CmdArgs) const {
5913  StringRef CPUName;
5914  StringRef ABIName;
5915  const llvm::Triple &Triple = getToolChain().getTriple();
5916  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
5917
5918  CmdArgs.push_back("-target-abi");
5919  CmdArgs.push_back(ABIName.data());
5920}
5921
5922void ClangAs::AddX86TargetArgs(const ArgList &Args,
5923                               ArgStringList &CmdArgs) const {
5924  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
5925    StringRef Value = A->getValue();
5926    if (Value == "intel" || Value == "att") {
5927      CmdArgs.push_back("-mllvm");
5928      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
5929    } else {
5930      getToolChain().getDriver().Diag(diag::err_drv_unsupported_option_argument)
5931          << A->getOption().getName() << Value;
5932    }
5933  }
5934}
5935
5936void ClangAs::AddRISCVTargetArgs(const ArgList &Args,
5937                               ArgStringList &CmdArgs) const {
5938  const llvm::Triple &Triple = getToolChain().getTriple();
5939  StringRef ABIName = riscv::getRISCVABI(Args, Triple);
5940
5941  CmdArgs.push_back("-target-abi");
5942  CmdArgs.push_back(ABIName.data());
5943}
5944
5945void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
5946                           const InputInfo &Output, const InputInfoList &Inputs,
5947                           const ArgList &Args,
5948                           const char *LinkingOutput) const {
5949  ArgStringList CmdArgs;
5950
5951   (0) . __assert_fail ("Inputs.size() == 1 && \"Unexpected number of inputs.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 5951, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Inputs.size() == 1 && "Unexpected number of inputs.");
5952  const InputInfo &Input = Inputs[0];
5953
5954  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
5955  const std::string &TripleStr = Triple.getTriple();
5956  const auto &D = getToolChain().getDriver();
5957
5958  // Don't warn about "clang -w -c foo.s"
5959  Args.ClaimAllArgs(options::OPT_w);
5960  // and "clang -emit-llvm -c foo.s"
5961  Args.ClaimAllArgs(options::OPT_emit_llvm);
5962
5963  claimNoWarnArgs(Args);
5964
5965  // Invoke ourselves in -cc1as mode.
5966  //
5967  // FIXME: Implement custom jobs for internal actions.
5968  CmdArgs.push_back("-cc1as");
5969
5970  // Add the "effective" target triple.
5971  CmdArgs.push_back("-triple");
5972  CmdArgs.push_back(Args.MakeArgString(TripleStr));
5973
5974  // Set the output mode, we currently only expect to be used as a real
5975  // assembler.
5976  CmdArgs.push_back("-filetype");
5977  CmdArgs.push_back("obj");
5978
5979  // Set the main file name, so that debug info works even with
5980  // -save-temps or preprocessed assembly.
5981  CmdArgs.push_back("-main-file-name");
5982  CmdArgs.push_back(Clang::getBaseInputName(Args, Input));
5983
5984  // Add the target cpu
5985  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ true);
5986  if (!CPU.empty()) {
5987    CmdArgs.push_back("-target-cpu");
5988    CmdArgs.push_back(Args.MakeArgString(CPU));
5989  }
5990
5991  // Add the target features
5992  getTargetFeatures(getToolChain(), Triple, Args, CmdArgs, true);
5993
5994  // Ignore explicit -force_cpusubtype_ALL option.
5995  (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
5996
5997  // Pass along any -I options so we get proper .include search paths.
5998  Args.AddAllArgs(CmdArgs, options::OPT_I_Group);
5999
6000  // Determine the original source input.
6001  const Action *SourceAction = &JA;
6002  while (SourceAction->getKind() != Action::InputClass) {
6003     (0) . __assert_fail ("!SourceAction->getInputs().empty() && \"unexpected root action!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6003, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(!SourceAction->getInputs().empty() && "unexpected root action!");
6004    SourceAction = SourceAction->getInputs()[0];
6005  }
6006
6007  // Forward -g and handle debug info related flags, assuming we are dealing
6008  // with an actual assembly file.
6009  bool WantDebug = false;
6010  unsigned DwarfVersion = 0;
6011  Args.ClaimAllArgs(options::OPT_g_Group);
6012  if (Arg *A = Args.getLastArg(options::OPT_g_Group)) {
6013    WantDebug = !A->getOption().matches(options::OPT_g0) &&
6014                !A->getOption().matches(options::OPT_ggdb0);
6015    if (WantDebug)
6016      DwarfVersion = DwarfVersionNum(A->getSpelling());
6017  }
6018  if (DwarfVersion == 0)
6019    DwarfVersion = getToolChain().GetDefaultDwarfVersion();
6020
6021  codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
6022
6023  if (SourceAction->getType() == types::TY_Asm ||
6024      SourceAction->getType() == types::TY_PP_Asm) {
6025    // You might think that it would be ok to set DebugInfoKind outside of
6026    // the guard for source type, however there is a test which asserts
6027    // that some assembler invocation receives no -debug-info-kind,
6028    // and it's not clear whether that test is just overly restrictive.
6029    DebugInfoKind = (WantDebug ? codegenoptions::LimitedDebugInfo
6030                               : codegenoptions::NoDebugInfo);
6031    // Add the -fdebug-compilation-dir flag if needed.
6032    addDebugCompDirArg(Args, CmdArgs);
6033
6034    addDebugPrefixMapArg(getToolChain().getDriver(), Args, CmdArgs);
6035
6036    // Set the AT_producer to the clang version when using the integrated
6037    // assembler on assembly source files.
6038    CmdArgs.push_back("-dwarf-debug-producer");
6039    CmdArgs.push_back(Args.MakeArgString(getClangFullVersion()));
6040
6041    // And pass along -I options
6042    Args.AddAllArgs(CmdArgs, options::OPT_I);
6043  }
6044  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DwarfVersion,
6045                          llvm::DebuggerKind::Default);
6046  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, getToolChain());
6047
6048
6049  // Handle -fPIC et al -- the relocation-model affects the assembler
6050  // for some targets.
6051  llvm::Reloc::Model RelocationModel;
6052  unsigned PICLevel;
6053  bool IsPIE;
6054  std::tie(RelocationModel, PICLevel, IsPIE) =
6055      ParsePICArgs(getToolChain(), Args);
6056
6057  const char *RMName = RelocationModelName(RelocationModel);
6058  if (RMName) {
6059    CmdArgs.push_back("-mrelocation-model");
6060    CmdArgs.push_back(RMName);
6061  }
6062
6063  // Optionally embed the -cc1as level arguments into the debug info, for build
6064  // analysis.
6065  if (getToolChain().UseDwarfDebugFlags()) {
6066    ArgStringList OriginalArgs;
6067    for (const auto &Arg : Args)
6068      Arg->render(Args, OriginalArgs);
6069
6070    SmallString<256> Flags;
6071    const char *Exec = getToolChain().getDriver().getClangProgramPath();
6072    Flags += Exec;
6073    for (const char *OriginalArg : OriginalArgs) {
6074      SmallString<128> EscapedArg;
6075      EscapeSpacesAndBackslashes(OriginalArg, EscapedArg);
6076      Flags += " ";
6077      Flags += EscapedArg;
6078    }
6079    CmdArgs.push_back("-dwarf-debug-flags");
6080    CmdArgs.push_back(Args.MakeArgString(Flags));
6081  }
6082
6083  // FIXME: Add -static support, once we have it.
6084
6085  // Add target specific flags.
6086  switch (getToolChain().getArch()) {
6087  default:
6088    break;
6089
6090  case llvm::Triple::mips:
6091  case llvm::Triple::mipsel:
6092  case llvm::Triple::mips64:
6093  case llvm::Triple::mips64el:
6094    AddMIPSTargetArgs(Args, CmdArgs);
6095    break;
6096
6097  case llvm::Triple::x86:
6098  case llvm::Triple::x86_64:
6099    AddX86TargetArgs(Args, CmdArgs);
6100    break;
6101
6102  case llvm::Triple::arm:
6103  case llvm::Triple::armeb:
6104  case llvm::Triple::thumb:
6105  case llvm::Triple::thumbeb:
6106    // This isn't in AddARMTargetArgs because we want to do this for assembly
6107    // only, not C/C++.
6108    if (Args.hasFlag(options::OPT_mdefault_build_attributes,
6109                     options::OPT_mno_default_build_attributes, true)) {
6110        CmdArgs.push_back("-mllvm");
6111        CmdArgs.push_back("-arm-add-build-attributes");
6112    }
6113    break;
6114
6115  case llvm::Triple::riscv32:
6116  case llvm::Triple::riscv64:
6117    AddRISCVTargetArgs(Args, CmdArgs);
6118    break;
6119  }
6120
6121  // Consume all the warning flags. Usually this would be handled more
6122  // gracefully by -cc1 (warning about unknown warning flags, etc) but -cc1as
6123  // doesn't handle that so rather than warning about unused flags that are
6124  // actually used, we'll lie by omission instead.
6125  // FIXME: Stop lying and consume only the appropriate driver flags
6126  Args.ClaimAllArgs(options::OPT_W_Group);
6127
6128  CollectArgsForIntegratedAssembler(C, Args, CmdArgs,
6129                                    getToolChain().getDriver());
6130
6131  Args.AddAllArgs(CmdArgs, options::OPT_mllvm);
6132
6133   (0) . __assert_fail ("Output.isFilename() && \"Unexpected lipo output.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6133, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Output.isFilename() && "Unexpected lipo output.");
6134  CmdArgs.push_back("-o");
6135  CmdArgs.push_back(Output.getFilename());
6136
6137  const llvm::Triple &T = getToolChain().getTriple();
6138  Arg *A;
6139  if (getDebugFissionKind(D, Args, A) == DwarfFissionKind::Split &&
6140      T.isOSBinFormatELF()) {
6141    CmdArgs.push_back("-split-dwarf-file");
6142    CmdArgs.push_back(SplitDebugName(Args, Input, Output));
6143  }
6144
6145   (0) . __assert_fail ("Input.isFilename() && \"Invalid input.\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6145, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Input.isFilename() && "Invalid input.");
6146  CmdArgs.push_back(Input.getFilename());
6147
6148  const char *Exec = getToolChain().getDriver().getClangProgramPath();
6149  C.addCommand(llvm::make_unique<Command>(JA, *this, Exec, CmdArgs, Inputs));
6150}
6151
6152// Begin OffloadBundler
6153
6154void OffloadBundler::ConstructJob(Compilation &C, const JobAction &JA,
6155                                  const InputInfo &Output,
6156                                  const InputInfoList &Inputs,
6157                                  const llvm::opt::ArgList &TCArgs,
6158                                  const char *LinkingOutput) const {
6159  // The version with only one output is expected to refer to a bundling job.
6160   (0) . __assert_fail ("isa(JA) && \"Expecting bundling job!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6160, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(isa<OffloadBundlingJobAction>(JA) && "Expecting bundling job!");
6161
6162  // The bundling command looks like this:
6163  // clang-offload-bundler -type=bc
6164  //   -targets=host-triple,openmp-triple1,openmp-triple2
6165  //   -outputs=input_file
6166  //   -inputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6167
6168  ArgStringList CmdArgs;
6169
6170  // Get the type.
6171  CmdArgs.push_back(TCArgs.MakeArgString(
6172      Twine("-type=") + types::getTypeTempSuffix(Output.getType())));
6173
6174   (0) . __assert_fail ("JA.getInputs().size() == Inputs.size() && \"Not have inputs for all dependence actions??\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6175, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(JA.getInputs().size() == Inputs.size() &&
6175 (0) . __assert_fail ("JA.getInputs().size() == Inputs.size() && \"Not have inputs for all dependence actions??\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6175, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">         "Not have inputs for all dependence actions??");
6176
6177  // Get the targets.
6178  SmallString<128> Triples;
6179  Triples += "-targets=";
6180  for (unsigned I = 0; I < Inputs.size(); ++I) {
6181    if (I)
6182      Triples += ',';
6183
6184    // Find ToolChain for this input.
6185    Action::OffloadKind CurKind = Action::OFK_Host;
6186    const ToolChain *CurTC = &getToolChain();
6187    const Action *CurDep = JA.getInputs()[I];
6188
6189    if (const auto *OA = dyn_cast<OffloadAction>(CurDep)) {
6190      CurTC = nullptr;
6191      OA->doOnEachDependence([&](Action *A, const ToolChain *TC, const char *) {
6192         (0) . __assert_fail ("CurTC == nullptr && \"Expected one dependence!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6192, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(CurTC == nullptr && "Expected one dependence!");
6193        CurKind = A->getOffloadingDeviceKind();
6194        CurTC = TC;
6195      });
6196    }
6197    Triples += Action::GetOffloadKindName(CurKind);
6198    Triples += '-';
6199    Triples += CurTC->getTriple().normalize();
6200    if (CurKind == Action::OFK_HIP && CurDep->getOffloadingArch()) {
6201      Triples += '-';
6202      Triples += CurDep->getOffloadingArch();
6203    }
6204  }
6205  CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6206
6207  // Get bundled file command.
6208  CmdArgs.push_back(
6209      TCArgs.MakeArgString(Twine("-outputs=") + Output.getFilename()));
6210
6211  // Get unbundled files command.
6212  SmallString<128> UB;
6213  UB += "-inputs=";
6214  for (unsigned I = 0; I < Inputs.size(); ++I) {
6215    if (I)
6216      UB += ',';
6217
6218    // Find ToolChain for this input.
6219    const ToolChain *CurTC = &getToolChain();
6220    if (const auto *OA = dyn_cast<OffloadAction>(JA.getInputs()[I])) {
6221      CurTC = nullptr;
6222      OA->doOnEachDependence([&](Action *, const ToolChain *TC, const char *) {
6223         (0) . __assert_fail ("CurTC == nullptr && \"Expected one dependence!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6223, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(CurTC == nullptr && "Expected one dependence!");
6224        CurTC = TC;
6225      });
6226    }
6227    UB += CurTC->getInputFilename(Inputs[I]);
6228  }
6229  CmdArgs.push_back(TCArgs.MakeArgString(UB));
6230
6231  // All the inputs are encoded as commands.
6232  C.addCommand(llvm::make_unique<Command>(
6233      JA, *this,
6234      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6235      CmdArgs, None));
6236}
6237
6238void OffloadBundler::ConstructJobMultipleOutputs(
6239    Compilation &C, const JobAction &JA, const InputInfoList &Outputs,
6240    const InputInfoList &Inputs, const llvm::opt::ArgList &TCArgs,
6241    const char *LinkingOutput) const {
6242  // The version with multiple outputs is expected to refer to a unbundling job.
6243  auto &UA = cast<OffloadUnbundlingJobAction>(JA);
6244
6245  // The unbundling command looks like this:
6246  // clang-offload-bundler -type=bc
6247  //   -targets=host-triple,openmp-triple1,openmp-triple2
6248  //   -inputs=input_file
6249  //   -outputs=unbundle_file_host,unbundle_file_tgt1,unbundle_file_tgt2"
6250  //   -unbundle
6251
6252  ArgStringList CmdArgs;
6253
6254   (0) . __assert_fail ("Inputs.size() == 1 && \"Expecting to unbundle a single file!\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Clang.cpp", 6254, __PRETTY_FUNCTION__))" file_link="../../../../include/assert.h.html#88" macro="true">assert(Inputs.size() == 1 && "Expecting to unbundle a single file!");
6255  InputInfo Input = Inputs.front();
6256
6257  // Get the type.
6258  CmdArgs.push_back(TCArgs.MakeArgString(
6259      Twine("-type=") + types::getTypeTempSuffix(Input.getType())));
6260
6261  // Get the targets.
6262  SmallString<128> Triples;
6263  Triples += "-targets=";
6264  auto DepInfo = UA.getDependentActionsInfo();
6265  for (unsigned I = 0; I < DepInfo.size(); ++I) {
6266    if (I)
6267      Triples += ',';
6268
6269    auto &Dep = DepInfo[I];
6270    Triples += Action::GetOffloadKindName(Dep.DependentOffloadKind);
6271    Triples += '-';
6272    Triples += Dep.DependentToolChain->getTriple().normalize();
6273    if (Dep.DependentOffloadKind == Action::OFK_HIP &&
6274        !Dep.DependentBoundArch.empty()) {
6275      Triples += '-';
6276      Triples += Dep.DependentBoundArch;
6277    }
6278  }
6279
6280  CmdArgs.push_back(TCArgs.MakeArgString(Triples));
6281
6282  // Get bundled file command.
6283  CmdArgs.push_back(
6284      TCArgs.MakeArgString(Twine("-inputs=") + Input.getFilename()));
6285
6286  // Get unbundled files command.
6287  SmallString<128> UB;
6288  UB += "-outputs=";
6289  for (unsigned I = 0; I < Outputs.size(); ++I) {
6290    if (I)
6291      UB += ',';
6292    UB += DepInfo[I].DependentToolChain->getInputFilename(Outputs[I]);
6293  }
6294  CmdArgs.push_back(TCArgs.MakeArgString(UB));
6295  CmdArgs.push_back("-unbundle");
6296
6297  // All the inputs are encoded as commands.
6298  C.addCommand(llvm::make_unique<Command>(
6299      JA, *this,
6300      TCArgs.MakeArgString(getToolChain().GetProgramPath(getShortName())),
6301      CmdArgs, None));
6302}
6303
clang::driver::Driver::getDefaultModuleCachePath