Coverage Report

Created: 2020-09-15 12:33

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Driver/ToolChains/Clang.cpp
Line
Count
Source (jump to first uncovered line)
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 "AMDGPU.h"
11
#include "Arch/AArch64.h"
12
#include "Arch/ARM.h"
13
#include "Arch/Mips.h"
14
#include "Arch/PPC.h"
15
#include "Arch/RISCV.h"
16
#include "Arch/Sparc.h"
17
#include "Arch/SystemZ.h"
18
#include "Arch/VE.h"
19
#include "Arch/X86.h"
20
#include "CommonArgs.h"
21
#include "Hexagon.h"
22
#include "InputInfo.h"
23
#include "MSP430.h"
24
#include "PS4CPU.h"
25
#include "clang/Basic/CharInfo.h"
26
#include "clang/Basic/CodeGenOptions.h"
27
#include "clang/Basic/LangOptions.h"
28
#include "clang/Basic/ObjCRuntime.h"
29
#include "clang/Basic/Version.h"
30
#include "clang/Driver/Distro.h"
31
#include "clang/Driver/DriverDiagnostic.h"
32
#include "clang/Driver/Options.h"
33
#include "clang/Driver/SanitizerArgs.h"
34
#include "clang/Driver/XRayArgs.h"
35
#include "llvm/ADT/StringExtras.h"
36
#include "llvm/Config/llvm-config.h"
37
#include "llvm/Option/ArgList.h"
38
#include "llvm/Support/CodeGen.h"
39
#include "llvm/Support/Compiler.h"
40
#include "llvm/Support/Compression.h"
41
#include "llvm/Support/FileSystem.h"
42
#include "llvm/Support/Host.h"
43
#include "llvm/Support/Path.h"
44
#include "llvm/Support/Process.h"
45
#include "llvm/Support/TargetParser.h"
46
#include "llvm/Support/YAMLParser.h"
47
48
#ifdef LLVM_ON_UNIX
49
#include <unistd.h> // For getuid().
50
#endif
51
52
using namespace clang::driver;
53
using namespace clang::driver::tools;
54
using namespace clang;
55
using namespace llvm::opt;
56
57
42.4k
static void CheckPreprocessingOptions(const Driver &D, const ArgList &Args) {
58
42.4k
  if (Arg *A =
59
5
          Args.getLastArg(clang::driver::options::OPT_C, options::OPT_CC)) {
60
5
    if (!Args.hasArg(options::OPT_E) && 
!Args.hasArg(options::OPT__SLASH_P)2
&&
61
1
        !Args.hasArg(options::OPT__SLASH_EP) && !D.CCCIsCPP()) {
62
1
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
63
1
          << A->getBaseArg().getAsString(Args)
64
1
          << (D.IsCLMode() ? "/E, /P or /EP" : 
"-E"0
);
65
1
    }
66
5
  }
67
42.4k
}
68
69
42.7k
static void CheckCodeGenerationOptions(const Driver &D, const ArgList &Args) {
70
  // In gcc, only ARM checks this, but it seems reasonable to check universally.
71
42.7k
  if (Args.hasArg(options::OPT_static))
72
105
    if (const Arg *A =
73
1
            Args.getLastArg(options::OPT_dynamic, options::OPT_mdynamic_no_pic))
74
1
      D.Diag(diag::err_drv_argument_not_allowed_with) << A->getAsString(Args)
75
1
                                                      << "-static";
76
42.7k
}
77
78
// Add backslashes to escape spaces and other backslashes.
79
// This is used for the space-separated argument list specified with
80
// the -dwarf-debug-flags option.
81
static void EscapeSpacesAndBackslashes(const char *Arg,
82
1.29k
                                       SmallVectorImpl<char> &Res) {
83
34.8k
  for (; *Arg; 
++Arg33.5k
) {
84
33.5k
    switch (*Arg) {
85
33.4k
    default:
86
33.4k
      break;
87
18
    case ' ':
88
18
    case '\\':
89
18
      Res.push_back('\\');
90
18
      break;
91
33.5k
    }
92
33.5k
    Res.push_back(*Arg);
93
33.5k
  }
94
1.29k
}
95
96
// Quote target names for inclusion in GNU Make dependency files.
97
// Only the characters '$', '#', ' ', '\t' are quoted.
98
42
static void QuoteTarget(StringRef Target, SmallVectorImpl<char> &Res) {
99
1.27k
  for (unsigned i = 0, e = Target.size(); i != e; 
++i1.22k
) {
100
1.22k
    switch (Target[i]) {
101
5
    case ' ':
102
5
    case '\t':
103
      // Escape the preceding backslashes
104
8
      for (int j = i - 1; j >= 0 && 
Target[j] == '\\'7
;
--j3
)
105
3
        Res.push_back('\\');
106
5
107
      // Escape the space/tab
108
5
      Res.push_back('\\');
109
5
      break;
110
2
    case '$':
111
2
      Res.push_back('$');
112
2
      break;
113
1
    case '#':
114
1
      Res.push_back('\\');
115
1
      break;
116
1.22k
    default:
117
1.22k
      break;
118
1.22k
    }
119
1.22k
120
1.22k
    Res.push_back(Target[i]);
121
1.22k
  }
122
42
}
123
124
/// Apply \a Work on the current tool chain \a RegularToolChain and any other
125
/// offloading tool chain that is associated with the current action \a JA.
126
static void
127
forAllAssociatedToolChains(Compilation &C, const JobAction &JA,
128
                           const ToolChain &RegularToolChain,
129
70.8k
                           llvm::function_ref<void(const ToolChain &)> Work) {
130
  // Apply Work on the current/regular tool chain.
131
70.8k
  Work(RegularToolChain);
132
70.8k
133
  // Apply Work on all the offloading tool chains associated with the current
134
  // action.
135
70.8k
  if (JA.isHostOffloading(Action::OFK_Cuda))
136
426
    Work(*C.getSingleOffloadToolChain<Action::OFK_Cuda>());
137
70.3k
  else if (JA.isDeviceOffloading(Action::OFK_Cuda))
138
524
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
139
69.8k
  else if (JA.isHostOffloading(Action::OFK_HIP))
140
184
    Work(*C.getSingleOffloadToolChain<Action::OFK_HIP>());
141
69.6k
  else if (JA.isDeviceOffloading(Action::OFK_HIP))
142
292
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
143
70.8k
144
70.8k
  if (JA.isHostOffloading(Action::OFK_OpenMP)) {
145
114
    auto TCs = C.getOffloadToolChains<Action::OFK_OpenMP>();
146
236
    for (auto II = TCs.first, IE = TCs.second; II != IE; 
++II122
)
147
122
      Work(*II->second);
148
70.6k
  } else if (JA.isDeviceOffloading(Action::OFK_OpenMP))
149
69
    Work(*C.getSingleOffloadToolChain<Action::OFK_Host>());
150
70.8k
151
  //
152
  // TODO: Add support for other offloading programming models here.
153
  //
154
70.8k
}
155
156
/// This is a helper function for validating the optional refinement step
157
/// parameter in reciprocal argument strings. Return false if there is an error
158
/// parsing the refinement step. Otherwise, return true and set the Position
159
/// of the refinement step in the input string.
160
static bool getRefinementStep(StringRef In, const Driver &D,
161
32
                              const Arg &A, size_t &Position) {
162
32
  const char RefinementStepToken = ':';
163
32
  Position = In.find(RefinementStepToken);
164
32
  if (Position != StringRef::npos) {
165
12
    StringRef Option = A.getOption().getName();
166
12
    StringRef RefStep = In.substr(Position + 1);
167
    // Allow exactly one numeric character for the additional refinement
168
    // step parameter. This is reasonable for all currently-supported
169
    // operations and architectures because we would expect that a larger value
170
    // of refinement steps would cause the estimate "optimization" to
171
    // under-perform the native operation. Also, if the estimate does not
172
    // converge quickly, it probably will not ever converge, so further
173
    // refinement steps will not produce a better answer.
174
12
    if (RefStep.size() != 1) {
175
2
      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
176
2
      return false;
177
2
    }
178
10
    char RefStepChar = RefStep[0];
179
10
    if (RefStepChar < '0' || RefStepChar > '9') {
180
0
      D.Diag(diag::err_drv_invalid_value) << Option << RefStep;
181
0
      return false;
182
0
    }
183
30
  }
184
30
  return true;
185
30
}
186
187
/// The -mrecip flag requires processing of many optional parameters.
188
static void ParseMRecip(const Driver &D, const ArgList &Args,
189
42.7k
                        ArgStringList &OutStrings) {
190
42.7k
  StringRef DisabledPrefixIn = "!";
191
42.7k
  StringRef DisabledPrefixOut = "!";
192
42.7k
  StringRef EnabledPrefixOut = "";
193
42.7k
  StringRef Out = "-mrecip=";
194
42.7k
195
42.7k
  Arg *A = Args.getLastArg(options::OPT_mrecip, options::OPT_mrecip_EQ);
196
42.7k
  if (!A)
197
42.7k
    return;
198
18
199
18
  unsigned NumOptions = A->getNumValues();
200
18
  if (NumOptions == 0) {
201
    // No option is the same as "all".
202
1
    OutStrings.push_back(Args.MakeArgString(Out + "all"));
203
1
    return;
204
1
  }
205
17
206
  // Pass through "all", "none", or "default" with an optional refinement step.
207
17
  if (NumOptions == 1) {
208
12
    StringRef Val = A->getValue(0);
209
12
    size_t RefStepLoc;
210
12
    if (!getRefinementStep(Val, D, *A, RefStepLoc))
211
2
      return;
212
10
    StringRef ValBase = Val.slice(0, RefStepLoc);
213
10
    if (ValBase == "all" || 
ValBase == "none"8
||
ValBase == "default"7
) {
214
4
      OutStrings.push_back(Args.MakeArgString(Out + Val));
215
4
      return;
216
4
    }
217
11
  }
218
11
219
  // Each reciprocal type may be enabled or disabled individually.
220
  // Check each input value for validity, concatenate them all back together,
221
  // and pass through.
222
11
223
11
  llvm::StringMap<bool> OptionStrings;
224
11
  OptionStrings.insert(std::make_pair("divd", false));
225
11
  OptionStrings.insert(std::make_pair("divf", false));
226
11
  OptionStrings.insert(std::make_pair("vec-divd", false));
227
11
  OptionStrings.insert(std::make_pair("vec-divf", false));
228
11
  OptionStrings.insert(std::make_pair("sqrtd", false));
229
11
  OptionStrings.insert(std::make_pair("sqrtf", false));
230
11
  OptionStrings.insert(std::make_pair("vec-sqrtd", false));
231
11
  OptionStrings.insert(std::make_pair("vec-sqrtf", false));
232
11
233
28
  for (unsigned i = 0; i != NumOptions; 
++i17
) {
234
20
    StringRef Val = A->getValue(i);
235
20
236
20
    bool IsDisabled = Val.startswith(DisabledPrefixIn);
237
    // Ignore the disablement token for string matching.
238
20
    if (IsDisabled)
239
3
      Val = Val.substr(1);
240
20
241
20
    size_t RefStep;
242
20
    if (!getRefinementStep(Val, D, *A, RefStep))
243
0
      return;
244
20
245
20
    StringRef ValBase = Val.slice(0, RefStep);
246
20
    llvm::StringMap<bool>::iterator OptionIter = OptionStrings.find(ValBase);
247
20
    if (OptionIter == OptionStrings.end()) {
248
      // Try again specifying float suffix.
249
6
      OptionIter = OptionStrings.find(ValBase.str() + 'f');
250
6
      if (OptionIter == OptionStrings.end()) {
251
        // The input name did not match any known option string.
252
1
        D.Diag(diag::err_drv_unknown_argument) << Val;
253
1
        return;
254
1
      }
255
      // The option was specified without a float or double suffix.
256
      // Make sure that the double entry was not already specified.
257
      // The float entry will be checked below.
258
5
      if (OptionStrings[ValBase.str() + 'd']) {
259
0
        D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
260
0
        return;
261
0
      }
262
19
    }
263
19
264
19
    if (OptionIter->second == true) {
265
      // Duplicate option specified.
266
2
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Val;
267
2
      return;
268
2
    }
269
17
270
    // Mark the matched option as found. Do not allow duplicate specifiers.
271
17
    OptionIter->second = true;
272
17
273
    // If the precision was not specified, also mark the double entry as found.
274
17
    if (ValBase.back() != 'f' && 
ValBase.back() != 'd'11
)
275
5
      OptionStrings[ValBase.str() + 'd'] = true;
276
17
277
    // Build the output string.
278
14
    StringRef Prefix = IsDisabled ? 
DisabledPrefixOut3
: EnabledPrefixOut;
279
17
    Out = Args.MakeArgString(Out + Prefix + Val);
280
17
    if (i != NumOptions - 1)
281
9
      Out = Args.MakeArgString(Out + ",");
282
17
  }
283
11
284
8
  OutStrings.push_back(Args.MakeArgString(Out));
285
8
}
286
287
/// The -mprefer-vector-width option accepts either a positive integer
288
/// or the string "none".
289
static void ParseMPreferVectorWidth(const Driver &D, const ArgList &Args,
290
42.7k
                                    ArgStringList &CmdArgs) {
291
42.7k
  Arg *A = Args.getLastArg(options::OPT_mprefer_vector_width_EQ);
292
42.7k
  if (!A)
293
42.7k
    return;
294
5
295
5
  StringRef Value = A->getValue();
296
5
  if (Value == "none") {
297
1
    CmdArgs.push_back("-mprefer-vector-width=none");
298
4
  } else {
299
4
    unsigned Width;
300
4
    if (Value.getAsInteger(10, Width)) {
301
3
      D.Diag(diag::err_drv_invalid_value) << A->getOption().getName() << Value;
302
3
      return;
303
3
    }
304
1
    CmdArgs.push_back(Args.MakeArgString("-mprefer-vector-width=" + Value));
305
1
  }
306
5
}
307
308
static void getWebAssemblyTargetFeatures(const ArgList &Args,
309
73
                                         std::vector<StringRef> &Features) {
310
73
  handleTargetFeaturesGroup(Args, Features, options::OPT_m_wasm_Features_Group);
311
73
}
312
313
static void getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
314
                              const ArgList &Args, ArgStringList &CmdArgs,
315
43.5k
                              bool ForAS, bool IsAux = false) {
316
43.5k
  std::vector<StringRef> Features;
317
43.5k
  switch (Triple.getArch()) {
318
420
  default:
319
420
    break;
320
672
  case llvm::Triple::mips:
321
672
  case llvm::Triple::mipsel:
322
672
  case llvm::Triple::mips64:
323
672
  case llvm::Triple::mips64el:
324
672
    mips::getMIPSTargetFeatures(D, Triple, Args, Features);
325
672
    break;
326
672
327
1.76k
  case llvm::Triple::arm:
328
1.76k
  case llvm::Triple::armeb:
329
1.76k
  case llvm::Triple::thumb:
330
1.76k
  case llvm::Triple::thumbeb:
331
1.76k
    arm::getARMTargetFeatures(D, Triple, Args, CmdArgs, Features, ForAS);
332
1.76k
    break;
333
1.76k
334
430
  case llvm::Triple::ppc:
335
430
  case llvm::Triple::ppc64:
336
430
  case llvm::Triple::ppc64le:
337
430
    ppc::getPPCTargetFeatures(D, Triple, Args, Features);
338
430
    break;
339
315
  case llvm::Triple::riscv32:
340
315
  case llvm::Triple::riscv64:
341
315
    riscv::getRISCVTargetFeatures(D, Triple, Args, Features);
342
315
    break;
343
60
  case llvm::Triple::systemz:
344
60
    systemz::getSystemZTargetFeatures(D, Args, Features);
345
60
    break;
346
1.13k
  case llvm::Triple::aarch64:
347
1.13k
  case llvm::Triple::aarch64_32:
348
1.13k
  case llvm::Triple::aarch64_be:
349
1.13k
    aarch64::getAArch64TargetFeatures(D, Triple, Args, Features);
350
1.13k
    break;
351
37.9k
  case llvm::Triple::x86:
352
37.9k
  case llvm::Triple::x86_64:
353
37.9k
    x86::getX86TargetFeatures(D, Triple, Args, Features);
354
37.9k
    break;
355
96
  case llvm::Triple::hexagon:
356
96
    hexagon::getHexagonTargetFeatures(D, Args, Features);
357
96
    break;
358
73
  case llvm::Triple::wasm32:
359
73
  case llvm::Triple::wasm64:
360
73
    getWebAssemblyTargetFeatures(Args, Features);
361
73
    break;
362
168
  case llvm::Triple::sparc:
363
168
  case llvm::Triple::sparcel:
364
168
  case llvm::Triple::sparcv9:
365
168
    sparc::getSparcTargetFeatures(D, Args, Features);
366
168
    break;
367
422
  case llvm::Triple::r600:
368
422
  case llvm::Triple::amdgcn:
369
422
    amdgpu::getAMDGPUTargetFeatures(D, Triple, Args, Features);
370
422
    break;
371
51
  case llvm::Triple::msp430:
372
51
    msp430::getMSP430TargetFeatures(D, Args, Features);
373
51
    break;
374
0
  case llvm::Triple::ve:
375
0
    ve::getVETargetFeatures(D, Args, Features);
376
43.5k
  }
377
43.5k
378
44.2k
  
for (auto Feature : unifyTargetFeatures(Features))43.5k
{
379
44.2k
    CmdArgs.push_back(IsAux ? 
"-aux-target-feature"2
: "-target-feature");
380
44.2k
    CmdArgs.push_back(Feature.data());
381
44.2k
  }
382
43.5k
}
383
384
static bool
385
shouldUseExceptionTablesForObjCExceptions(const ObjCRuntime &runtime,
386
3.52k
                                          const llvm::Triple &Triple) {
387
  // We use the zero-cost exception tables for Objective-C if the non-fragile
388
  // ABI is enabled or when compiling for x86_64 and ARM on Snow Leopard and
389
  // later.
390
3.52k
  if (runtime.isNonFragile())
391
3.50k
    return true;
392
28
393
28
  if (!Triple.isMacOSX())
394
12
    return false;
395
16
396
16
  return (!Triple.isMacOSXVersionLT(10, 5) &&
397
13
          (Triple.getArch() == llvm::Triple::x86_64 ||
398
9
           Triple.getArch() == llvm::Triple::arm));
399
16
}
400
401
/// Adds exception related arguments to the driver command arguments. There's a
402
/// master flag, -fexceptions and also language specific flags to enable/disable
403
/// C++ and Objective-C exceptions. This makes it possible to for example
404
/// disable C++ exceptions but enable Objective-C exceptions.
405
static void addExceptionArgs(const ArgList &Args, types::ID InputType,
406
                             const ToolChain &TC, bool KernelOrKext,
407
                             const ObjCRuntime &objcRuntime,
408
42.2k
                             ArgStringList &CmdArgs) {
409
42.2k
  const llvm::Triple &Triple = TC.getTriple();
410
42.2k
411
42.2k
  if (KernelOrKext) {
412
    // -mkernel and -fapple-kext imply no exceptions, so claim exception related
413
    // arguments now to avoid warnings about unused arguments.
414
23
    Args.ClaimAllArgs(options::OPT_fexceptions);
415
23
    Args.ClaimAllArgs(options::OPT_fno_exceptions);
416
23
    Args.ClaimAllArgs(options::OPT_fobjc_exceptions);
417
23
    Args.ClaimAllArgs(options::OPT_fno_objc_exceptions);
418
23
    Args.ClaimAllArgs(options::OPT_fcxx_exceptions);
419
23
    Args.ClaimAllArgs(options::OPT_fno_cxx_exceptions);
420
23
    return;
421
23
  }
422
42.2k
423
  // See if the user explicitly enabled exceptions.
424
42.2k
  bool EH = Args.hasFlag(options::OPT_fexceptions, options::OPT_fno_exceptions,
425
42.2k
                         false);
426
42.2k
427
  // Obj-C exceptions are enabled by default, regardless of -fexceptions. This
428
  // is not necessarily sensible, but follows GCC.
429
42.2k
  if (types::isObjC(InputType) &&
430
3.52k
      Args.hasFlag(options::OPT_fobjc_exceptions,
431
3.52k
                   options::OPT_fno_objc_exceptions, true)) {
432
3.52k
    CmdArgs.push_back("-fobjc-exceptions");
433
3.52k
434
3.52k
    EH |= shouldUseExceptionTablesForObjCExceptions(objcRuntime, Triple);
435
3.52k
  }
436
42.2k
437
42.2k
  if (types::isCXX(InputType)) {
438
    // Disable C++ EH by default on XCore and PS4.
439
28.3k
    bool CXXExceptionsEnabled =
440
28.3k
        Triple.getArch() != llvm::Triple::xcore && 
!Triple.isPS4CPU()28.3k
;
441
28.3k
    Arg *ExceptionArg = Args.getLastArg(
442
28.3k
        options::OPT_fcxx_exceptions, options::OPT_fno_cxx_exceptions,
443
28.3k
        options::OPT_fexceptions, options::OPT_fno_exceptions);
444
28.3k
    if (ExceptionArg)
445
12.0k
      CXXExceptionsEnabled =
446
12.0k
          ExceptionArg->getOption().matches(options::OPT_fcxx_exceptions) ||
447
11.9k
          ExceptionArg->getOption().matches(options::OPT_fexceptions);
448
28.3k
449
28.3k
    if (CXXExceptionsEnabled) {
450
28.2k
      CmdArgs.push_back("-fcxx-exceptions");
451
28.2k
452
28.2k
      EH = true;
453
28.2k
    }
454
28.3k
  }
455
42.2k
456
  // OPT_fignore_exceptions means exception could still be thrown,
457
  // but no clean up or catch would happen in current module.
458
  // So we do not set EH to false.
459
42.2k
  Args.AddLastArg(CmdArgs, options::OPT_fignore_exceptions);
460
42.2k
461
42.2k
  if (EH)
462
31.7k
    CmdArgs.push_back("-fexceptions");
463
42.2k
}
464
465
static bool ShouldEnableAutolink(const ArgList &Args, const ToolChain &TC,
466
42.7k
                                 const JobAction &JA) {
467
42.7k
  bool Default = true;
468
42.7k
  if (TC.getTriple().isOSDarwin()) {
469
    // The native darwin assembler doesn't support the linker_option directives,
470
    // so we disable them if we think the .s file will be passed to it.
471
18.0k
    Default = TC.useIntegratedAs();
472
18.0k
  }
473
  // The linker_option directives are intended for host compilation.
474
42.7k
  if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
475
42.4k
      JA.isDeviceOffloading(Action::OFK_HIP))
476
440
    Default = false;
477
42.7k
  return Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
478
42.7k
                      Default);
479
42.7k
}
480
481
static bool ShouldDisableDwarfDirectory(const ArgList &Args,
482
42.7k
                                        const ToolChain &TC) {
483
42.7k
  bool UseDwarfDirectory =
484
42.7k
      Args.hasFlag(options::OPT_fdwarf_directory_asm,
485
42.7k
                   options::OPT_fno_dwarf_directory_asm, TC.useIntegratedAs());
486
42.7k
  return !UseDwarfDirectory;
487
42.7k
}
488
489
// Convert an arg of the form "-gN" or "-ggdbN" or one of their aliases
490
// to the corresponding DebugInfoKind.
491
1.66k
static codegenoptions::DebugInfoKind DebugLevelToInfoKind(const Arg &A) {
492
1.66k
  assert(A.getOption().matches(options::OPT_gN_Group) &&
493
1.66k
         "Not a -g option that specifies a debug-info level");
494
1.66k
  if (A.getOption().matches(options::OPT_g0) ||
495
1.63k
      A.getOption().matches(options::OPT_ggdb0))
496
40
    return codegenoptions::NoDebugInfo;
497
1.62k
  if (A.getOption().matches(options::OPT_gline_tables_only) ||
498
1.60k
      A.getOption().matches(options::OPT_ggdb1))
499
28
    return codegenoptions::DebugLineTablesOnly;
500
1.59k
  if (A.getOption().matches(options::OPT_gline_directives_only))
501
11
    return codegenoptions::DebugDirectivesOnly;
502
1.58k
  return codegenoptions::LimitedDebugInfo;
503
1.58k
}
504
505
42.7k
static bool mustUseNonLeafFramePointerForTarget(const llvm::Triple &Triple) {
506
42.7k
  switch (Triple.getArch()){
507
41.1k
  default:
508
41.1k
    return false;
509
1.55k
  case llvm::Triple::arm:
510
1.55k
  case llvm::Triple::thumb:
511
    // ARM Darwin targets require a frame pointer to be always present to aid
512
    // offline debugging via backtraces.
513
1.55k
    return Triple.isOSDarwin();
514
42.7k
  }
515
42.7k
}
516
517
static bool useFramePointerForTargetByDefault(const ArgList &Args,
518
42.5k
                                              const llvm::Triple &Triple) {
519
42.5k
  if (Args.hasArg(options::OPT_pg) && 
!Args.hasArg(options::OPT_mfentry)48
)
520
44
    return true;
521
42.5k
522
42.5k
  switch (Triple.getArch()) {
523
129
  case llvm::Triple::xcore:
524
129
  case llvm::Triple::wasm32:
525
129
  case llvm::Triple::wasm64:
526
129
  case llvm::Triple::msp430:
527
    // XCore never wants frame pointers, regardless of OS.
528
    // WebAssembly never wants frame pointers.
529
129
    return false;
530
1.11k
  case llvm::Triple::ppc:
531
1.11k
  case llvm::Triple::ppc64:
532
1.11k
  case llvm::Triple::ppc64le:
533
1.11k
  case llvm::Triple::riscv32:
534
1.11k
  case llvm::Triple::riscv64:
535
1.11k
  case llvm::Triple::amdgcn:
536
1.11k
  case llvm::Triple::r600:
537
1.11k
    return !areOptimizationsEnabled(Args);
538
41.2k
  default:
539
41.2k
    break;
540
41.2k
  }
541
41.2k
542
41.2k
  if (Triple.isOSNetBSD()) {
543
179
    return !areOptimizationsEnabled(Args);
544
179
  }
545
41.1k
546
41.1k
  if (Triple.isOSLinux() || 
Triple.getOS() == llvm::Triple::CloudABI37.3k
||
547
37.2k
      Triple.isOSHurd()) {
548
3.82k
    switch (Triple.getArch()) {
549
    // Don't use a frame pointer on linux if optimizing for certain targets.
550
575
    case llvm::Triple::arm:
551
575
    case llvm::Triple::armeb:
552
575
    case llvm::Triple::thumb:
553
575
    case llvm::Triple::thumbeb:
554
575
      if (Triple.isAndroid())
555
94
        return true;
556
481
      LLVM_FALLTHROUGH;
557
3.43k
    case llvm::Triple::mips64:
558
3.43k
    case llvm::Triple::mips64el:
559
3.43k
    case llvm::Triple::mips:
560
3.43k
    case llvm::Triple::mipsel:
561
3.43k
    case llvm::Triple::systemz:
562
3.43k
    case llvm::Triple::x86:
563
3.43k
    case llvm::Triple::x86_64:
564
3.43k
      return !areOptimizationsEnabled(Args);
565
301
    default:
566
301
      return true;
567
37.2k
    }
568
37.2k
  }
569
37.2k
570
37.2k
  if (Triple.isOSWindows()) {
571
7.72k
    switch (Triple.getArch()) {
572
159
    case llvm::Triple::x86:
573
159
      return !areOptimizationsEnabled(Args);
574
7.51k
    case llvm::Triple::x86_64:
575
7.51k
      return Triple.isOSBinFormatMachO();
576
41
    case llvm::Triple::arm:
577
41
    case llvm::Triple::thumb:
578
      // Windows on ARM builds with FPO disabled to aid fast stack walking
579
41
      return true;
580
8
    default:
581
      // All other supported Windows ISAs use xdata unwind information, so frame
582
      // pointers are not generally useful.
583
8
      return false;
584
29.5k
    }
585
29.5k
  }
586
29.5k
587
29.5k
  return true;
588
29.5k
}
589
590
static CodeGenOptions::FramePointerKind
591
42.7k
getFramePointerKind(const ArgList &Args, const llvm::Triple &Triple) {
592
  // We have 4 states:
593
  //
594
  //  00) leaf retained, non-leaf retained
595
  //  01) leaf retained, non-leaf omitted (this is invalid)
596
  //  10) leaf omitted, non-leaf retained
597
  //      (what -momit-leaf-frame-pointer was designed for)
598
  //  11) leaf omitted, non-leaf omitted
599
  //
600
  //  "omit" options taking precedence over "no-omit" options is the only way
601
  //  to make 3 valid states representable
602
42.7k
  Arg *A = Args.getLastArg(options::OPT_fomit_frame_pointer,
603
42.7k
                           options::OPT_fno_omit_frame_pointer);
604
42.7k
  bool OmitFP = A && 
A->getOption().matches(options::OPT_fomit_frame_pointer)87
;
605
42.7k
  bool NoOmitFP =
606
42.7k
      A && 
A->getOption().matches(options::OPT_fno_omit_frame_pointer)87
;
607
42.7k
  bool KeepLeaf = Args.hasFlag(options::OPT_momit_leaf_frame_pointer,
608
42.7k
                               options::OPT_mno_omit_leaf_frame_pointer,
609
42.7k
                               Triple.isAArch64() || 
Triple.isPS4CPU()41.6k
);
610
42.7k
  if (NoOmitFP || 
mustUseNonLeafFramePointerForTarget(Triple)42.7k
||
611
42.6k
      (!OmitFP && 
useFramePointerForTargetByDefault(Args, Triple)42.5k
)) {
612
34.8k
    if (KeepLeaf)
613
1.25k
      return CodeGenOptions::FramePointerKind::NonLeaf;
614
33.6k
    return CodeGenOptions::FramePointerKind::All;
615
33.6k
  }
616
7.87k
  return CodeGenOptions::FramePointerKind::None;
617
7.87k
}
618
619
/// Add a CC1 option to specify the debug compilation directory.
620
static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs,
621
43.0k
                               const llvm::vfs::FileSystem &VFS) {
622
43.0k
  if (Arg *A = Args.getLastArg(options::OPT_fdebug_compilation_dir)) {
623
4
    CmdArgs.push_back("-fdebug-compilation-dir");
624
4
    CmdArgs.push_back(A->getValue());
625
43.0k
  } else if (llvm::ErrorOr<std::string> CWD =
626
43.0k
                 VFS.getCurrentWorkingDirectory()) {
627
43.0k
    CmdArgs.push_back("-fdebug-compilation-dir");
628
43.0k
    CmdArgs.push_back(Args.MakeArgString(*CWD));
629
43.0k
  }
630
43.0k
}
631
632
/// Add a CC1 and CC1AS option to specify the debug file path prefix map.
633
43.0k
static void addDebugPrefixMapArg(const Driver &D, const ArgList &Args, ArgStringList &CmdArgs) {
634
43.0k
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
635
19
                                    options::OPT_fdebug_prefix_map_EQ)) {
636
19
    StringRef Map = A->getValue();
637
19
    if (Map.find('=') == StringRef::npos)
638
2
      D.Diag(diag::err_drv_invalid_argument_to_option)
639
2
          << Map << A->getOption().getName();
640
17
    else
641
17
      CmdArgs.push_back(Args.MakeArgString("-fdebug-prefix-map=" + Map));
642
19
    A->claim();
643
19
  }
644
43.0k
}
645
646
/// Add a CC1 and CC1AS option to specify the macro file path prefix map.
647
static void addMacroPrefixMapArg(const Driver &D, const ArgList &Args,
648
42.4k
                                 ArgStringList &CmdArgs) {
649
42.4k
  for (const Arg *A : Args.filtered(options::OPT_ffile_prefix_map_EQ,
650
17
                                    options::OPT_fmacro_prefix_map_EQ)) {
651
17
    StringRef Map = A->getValue();
652
17
    if (Map.find('=') == StringRef::npos)
653
2
      D.Diag(diag::err_drv_invalid_argument_to_option)
654
2
          << Map << A->getOption().getName();
655
15
    else
656
15
      CmdArgs.push_back(Args.MakeArgString("-fmacro-prefix-map=" + Map));
657
17
    A->claim();
658
17
  }
659
42.4k
}
660
661
/// Vectorize at all optimization levels greater than 1 except for -Oz.
662
/// For -Oz the loop vectorizer is disabled, while the slp vectorizer is
663
/// enabled.
664
85.5k
static bool shouldEnableVectorizerAtOLevel(const ArgList &Args, bool isSlpVec) {
665
85.5k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
666
12.9k
    if (A->getOption().matches(options::OPT_O4) ||
667
12.9k
        A->getOption().matches(options::OPT_Ofast))
668
64
      return true;
669
12.8k
670
12.8k
    if (A->getOption().matches(options::OPT_O0))
671
11.6k
      return false;
672
1.25k
673
1.25k
    assert(A->getOption().matches(options::OPT_O) && "Must have a -O flag");
674
1.25k
675
    // Vectorize -Os.
676
1.25k
    StringRef S(A->getValue());
677
1.25k
    if (S == "s")
678
76
      return true;
679
1.18k
680
    // Don't vectorize -Oz, unless it's the slp vectorizer.
681
1.18k
    if (S == "z")
682
20
      return isSlpVec;
683
1.16k
684
1.16k
    unsigned OptLevel = 0;
685
1.16k
    if (S.getAsInteger(10, OptLevel))
686
12
      return false;
687
1.14k
688
1.14k
    return OptLevel > 1;
689
1.14k
  }
690
72.6k
691
72.6k
  return false;
692
72.6k
}
693
694
/// Add -x lang to \p CmdArgs for \p Input.
695
static void addDashXForInput(const ArgList &Args, const InputInfo &Input,
696
42.7k
                             ArgStringList &CmdArgs) {
697
  // When using -verify-pch, we don't want to provide the type
698
  // 'precompiled-header' if it was inferred from the file extension
699
42.7k
  if (Args.hasArg(options::OPT_verify_pch) && 
Input.getType() == types::TY_PCH2
)
700
1
    return;
701
42.7k
702
42.7k
  CmdArgs.push_back("-x");
703
42.7k
  if (Args.hasArg(options::OPT_rewrite_objc))
704
10
    CmdArgs.push_back(types::getTypeName(types::TY_PP_ObjCXX));
705
42.7k
  else {
706
    // Map the driver type to the frontend type. This is mostly an identity
707
    // mapping, except that the distinction between module interface units
708
    // and other source files does not exist at the frontend layer.
709
42.7k
    const char *ClangType;
710
42.7k
    switch (Input.getType()) {
711
6
    case types::TY_CXXModule:
712
6
      ClangType = "c++";
713
6
      break;
714
0
    case types::TY_PP_CXXModule:
715
0
      ClangType = "c++-cpp-output";
716
0
      break;
717
42.7k
    default:
718
42.7k
      ClangType = types::getTypeName(Input.getType());
719
42.7k
      break;
720
42.7k
    }
721
42.7k
    CmdArgs.push_back(ClangType);
722
42.7k
  }
723
42.7k
}
724
725
static void addPGOAndCoverageFlags(const ToolChain &TC, Compilation &C,
726
                                   const Driver &D, const InputInfo &Output,
727
                                   const ArgList &Args,
728
42.0k
                                   ArgStringList &CmdArgs) {
729
42.0k
730
42.0k
  auto *PGOGenerateArg = Args.getLastArg(options::OPT_fprofile_generate,
731
42.0k
                                         options::OPT_fprofile_generate_EQ,
732
42.0k
                                         options::OPT_fno_profile_generate);
733
42.0k
  if (PGOGenerateArg &&
734
25
      PGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
735
4
    PGOGenerateArg = nullptr;
736
42.0k
737
42.0k
  auto *CSPGOGenerateArg = Args.getLastArg(options::OPT_fcs_profile_generate,
738
42.0k
                                           options::OPT_fcs_profile_generate_EQ,
739
42.0k
                                           options::OPT_fno_profile_generate);
740
42.0k
  if (CSPGOGenerateArg &&
741
5
      CSPGOGenerateArg->getOption().matches(options::OPT_fno_profile_generate))
742
4
    CSPGOGenerateArg = nullptr;
743
42.0k
744
42.0k
  auto *ProfileGenerateArg = Args.getLastArg(
745
42.0k
      options::OPT_fprofile_instr_generate,
746
42.0k
      options::OPT_fprofile_instr_generate_EQ,
747
42.0k
      options::OPT_fno_profile_instr_generate);
748
42.0k
  if (ProfileGenerateArg &&
749
45
      ProfileGenerateArg->getOption().matches(
750
45
          options::OPT_fno_profile_instr_generate))
751
4
    ProfileGenerateArg = nullptr;
752
42.0k
753
42.0k
  if (PGOGenerateArg && 
ProfileGenerateArg21
)
754
2
    D.Diag(diag::err_drv_argument_not_allowed_with)
755
2
        << PGOGenerateArg->getSpelling() << ProfileGenerateArg->getSpelling();
756
42.0k
757
42.0k
  auto *ProfileUseArg = getLastProfileUseArg(Args);
758
42.0k
759
42.0k
  if (PGOGenerateArg && 
ProfileUseArg21
)
760
8
    D.Diag(diag::err_drv_argument_not_allowed_with)
761
8
        << ProfileUseArg->getSpelling() << PGOGenerateArg->getSpelling();
762
42.0k
763
42.0k
  if (ProfileGenerateArg && 
ProfileUseArg41
)
764
10
    D.Diag(diag::err_drv_argument_not_allowed_with)
765
10
        << ProfileGenerateArg->getSpelling() << ProfileUseArg->getSpelling();
766
42.0k
767
42.0k
  if (CSPGOGenerateArg && 
PGOGenerateArg1
)
768
0
    D.Diag(diag::err_drv_argument_not_allowed_with)
769
0
        << CSPGOGenerateArg->getSpelling() << PGOGenerateArg->getSpelling();
770
42.0k
771
42.0k
  if (ProfileGenerateArg) {
772
41
    if (ProfileGenerateArg->getOption().matches(
773
41
            options::OPT_fprofile_instr_generate_EQ))
774
7
      CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-instrument-path=") +
775
7
                                           ProfileGenerateArg->getValue()));
776
    // The default is to use Clang Instrumentation.
777
41
    CmdArgs.push_back("-fprofile-instrument=clang");
778
41
    if (TC.getTriple().isWindowsMSVCEnvironment()) {
779
      // Add dependent lib for clang_rt.profile
780
7
      CmdArgs.push_back(Args.MakeArgString(
781
7
          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
782
7
    }
783
41
  }
784
42.0k
785
42.0k
  Arg *PGOGenArg = nullptr;
786
42.0k
  if (PGOGenerateArg) {
787
21
    assert(!CSPGOGenerateArg);
788
21
    PGOGenArg = PGOGenerateArg;
789
21
    CmdArgs.push_back("-fprofile-instrument=llvm");
790
21
  }
791
42.0k
  if (CSPGOGenerateArg) {
792
1
    assert(!PGOGenerateArg);
793
1
    PGOGenArg = CSPGOGenerateArg;
794
1
    CmdArgs.push_back("-fprofile-instrument=csllvm");
795
1
  }
796
42.0k
  if (PGOGenArg) {
797
22
    if (TC.getTriple().isWindowsMSVCEnvironment()) {
798
      // Add dependent lib for clang_rt.profile
799
1
      CmdArgs.push_back(Args.MakeArgString(
800
1
          "--dependent-lib=" + TC.getCompilerRTBasename(Args, "profile")));
801
1
    }
802
22
    if (PGOGenArg->getOption().matches(
803
21
            PGOGenerateArg ? options::OPT_fprofile_generate_EQ
804
8
                           : 
options::OPT_fcs_profile_generate_EQ1
)) {
805
8
      SmallString<128> Path(PGOGenArg->getValue());
806
8
      llvm::sys::path::append(Path, "default_%m.profraw");
807
8
      CmdArgs.push_back(
808
8
          Args.MakeArgString(Twine("-fprofile-instrument-path=") + Path));
809
8
    }
810
22
  }
811
42.0k
812
42.0k
  if (ProfileUseArg) {
813
37
    if (ProfileUseArg->getOption().matches(options::OPT_fprofile_instr_use_EQ))
814
9
      CmdArgs.push_back(Args.MakeArgString(
815
9
          Twine("-fprofile-instrument-use-path=") + ProfileUseArg->getValue()));
816
28
    else if ((ProfileUseArg->getOption().matches(
817
28
                  options::OPT_fprofile_use_EQ) ||
818
12
              ProfileUseArg->getOption().matches(
819
28
                  options::OPT_fprofile_instr_use))) {
820
28
      SmallString<128> Path(
821
16
          ProfileUseArg->getNumValues() == 0 ? 
""12
: ProfileUseArg->getValue());
822
28
      if (Path.empty() || 
llvm::sys::fs::is_directory(Path)16
)
823
17
        llvm::sys::path::append(Path, "default.profdata");
824
28
      CmdArgs.push_back(
825
28
          Args.MakeArgString(Twine("-fprofile-instrument-use-path=") + Path));
826
28
    }
827
37
  }
828
42.0k
829
42.0k
  bool EmitCovNotes = Args.hasFlag(options::OPT_ftest_coverage,
830
42.0k
                                   options::OPT_fno_test_coverage, false) ||
831
42.0k
                      Args.hasArg(options::OPT_coverage);
832
42.0k
  bool EmitCovData = TC.needsGCovInstrumentation(Args);
833
42.0k
  if (EmitCovNotes)
834
22
    CmdArgs.push_back("-femit-coverage-notes");
835
42.0k
  if (EmitCovData)
836
26
    CmdArgs.push_back("-femit-coverage-data");
837
42.0k
838
42.0k
  if (Args.hasFlag(options::OPT_fcoverage_mapping,
839
4
                   options::OPT_fno_coverage_mapping, false)) {
840
4
    if (!ProfileGenerateArg)
841
1
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
842
1
          << "-fcoverage-mapping"
843
1
          << "-fprofile-instr-generate";
844
4
845
4
    CmdArgs.push_back("-fcoverage-mapping");
846
4
  }
847
42.0k
848
42.0k
  if (Args.hasArg(options::OPT_fprofile_exclude_files_EQ)) {
849
5
    auto *Arg = Args.getLastArg(options::OPT_fprofile_exclude_files_EQ);
850
5
    if (!Args.hasArg(options::OPT_coverage))
851
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
852
0
          << "-fprofile-exclude-files="
853
0
          << "--coverage";
854
5
855
5
    StringRef v = Arg->getValue();
856
5
    CmdArgs.push_back(
857
5
        Args.MakeArgString(Twine("-fprofile-exclude-files=" + v)));
858
5
  }
859
42.0k
860
42.0k
  if (Args.hasArg(options::OPT_fprofile_filter_files_EQ)) {
861
4
    auto *Arg = Args.getLastArg(options::OPT_fprofile_filter_files_EQ);
862
4
    if (!Args.hasArg(options::OPT_coverage))
863
0
      D.Diag(clang::diag::err_drv_argument_only_allowed_with)
864
0
          << "-fprofile-filter-files="
865
0
          << "--coverage";
866
4
867
4
    StringRef v = Arg->getValue();
868
4
    CmdArgs.push_back(Args.MakeArgString(Twine("-fprofile-filter-files=" + v)));
869
4
  }
870
42.0k
871
  // Leave -fprofile-dir= an unused argument unless .gcda emission is
872
  // enabled. To be polite, with '-fprofile-arcs -fno-profile-arcs' consider
873
  // the flag used. There is no -fno-profile-dir, so the user has no
874
  // targeted way to suppress the warning.
875
42.0k
  Arg *FProfileDir = nullptr;
876
42.0k
  if (Args.hasArg(options::OPT_fprofile_arcs) ||
877
42.0k
      Args.hasArg(options::OPT_coverage))
878
28
    FProfileDir = Args.getLastArg(options::OPT_fprofile_dir);
879
42.0k
880
  // Put the .gcno and .gcda files (if needed) next to the object file or
881
  // bitcode file in the case of LTO.
882
  // FIXME: There should be a simpler way to find the object file for this
883
  // input, and this code probably does the wrong thing for commands that
884
  // compile and link all at once.
885
42.0k
  if ((Args.hasArg(options::OPT_c) || 
Args.hasArg(options::OPT_S)35.5k
) &&
886
7.66k
      (EmitCovNotes || 
EmitCovData7.65k
) &&
Output.isFilename()19
) {
887
19
    SmallString<128> OutputFilename;
888
19
    if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT__SLASH_Fo))
889
1
      OutputFilename = FinalOutput->getValue();
890
18
    else if (Arg *FinalOutput = C.getArgs().getLastArg(options::OPT_o))
891
10
      OutputFilename = FinalOutput->getValue();
892
8
    else
893
8
      OutputFilename = llvm::sys::path::filename(Output.getBaseInput());
894
19
    SmallString<128> CoverageFilename = OutputFilename;
895
19
    if (llvm::sys::path::is_relative(CoverageFilename))
896
9
      (void)D.getVFS().makeAbsolute(CoverageFilename);
897
19
    llvm::sys::path::replace_extension(CoverageFilename, "gcno");
898
19
899
19
    CmdArgs.push_back("-coverage-notes-file");
900
19
    CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
901
19
902
19
    if (EmitCovData) {
903
16
      if (FProfileDir) {
904
2
        CoverageFilename = FProfileDir->getValue();
905
2
        llvm::sys::path::append(CoverageFilename, OutputFilename);
906
2
      }
907
16
      llvm::sys::path::replace_extension(CoverageFilename, "gcda");
908
16
      CmdArgs.push_back("-coverage-data-file");
909
16
      CmdArgs.push_back(Args.MakeArgString(CoverageFilename));
910
16
    }
911
19
  }
912
42.0k
}
913
914
/// Check whether the given input tree contains any compilation actions.
915
26.9k
static bool ContainsCompileAction(const Action *A) {
916
26.9k
  if (isa<CompileJobAction>(A) || isa<BackendJobAction>(A))
917
9.25k
    return true;
918
17.7k
919
17.7k
  for (const auto &AI : A->inputs())
920
17.4k
    if (ContainsCompileAction(AI))
921
16.9k
      return true;
922
17.7k
923
732
  return false;
924
17.7k
}
925
926
/// Check if -relax-all should be passed to the internal assembler.
927
/// This is done by default when compiling non-assembler source with -O0.
928
9.74k
static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
929
9.74k
  bool RelaxDefault = true;
930
9.74k
931
9.74k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group))
932
3.21k
    RelaxDefault = A->getOption().matches(options::OPT_O0);
933
9.74k
934
9.74k
  if (RelaxDefault) {
935
9.49k
    RelaxDefault = false;
936
9.52k
    for (const auto &Act : C.getActions()) {
937
9.52k
      if (ContainsCompileAction(Act)) {
938
9.25k
        RelaxDefault = true;
939
9.25k
        break;
940
9.25k
      }
941
9.52k
    }
942
9.49k
  }
943
9.74k
944
9.74k
  return Args.hasFlag(options::OPT_mrelax_all, options::OPT_mno_relax_all,
945
9.74k
                      RelaxDefault);
946
9.74k
}
947
948
// Extract the integer N from a string spelled "-dwarf-N", returning 0
949
// on mismatch. The StringRef input (rather than an Arg) allows
950
// for use by the "-Xassembler" option parser.
951
55
static unsigned DwarfVersionNum(StringRef ArgValue) {
952
55
  return llvm::StringSwitch<unsigned>(ArgValue)
953
55
      .Case("-gdwarf-2", 2)
954
55
      .Case("-gdwarf-3", 3)
955
55
      .Case("-gdwarf-4", 4)
956
55
      .Case("-gdwarf-5", 5)
957
55
      .Default(0);
958
55
}
959
960
static void RenderDebugEnablingArgs(const ArgList &Args, ArgStringList &CmdArgs,
961
                                    codegenoptions::DebugInfoKind DebugInfoKind,
962
                                    unsigned DwarfVersion,
963
43.1k
                                    llvm::DebuggerKind DebuggerTuning) {
964
43.1k
  switch (DebugInfoKind) {
965
17
  case codegenoptions::DebugDirectivesOnly:
966
17
    CmdArgs.push_back("-debug-info-kind=line-directives-only");
967
17
    break;
968
62
  case codegenoptions::DebugLineTablesOnly:
969
62
    CmdArgs.push_back("-debug-info-kind=line-tables-only");
970
62
    break;
971
0
  case codegenoptions::DebugInfoConstructor:
972
0
    CmdArgs.push_back("-debug-info-kind=constructor");
973
0
    break;
974
243
  case codegenoptions::LimitedDebugInfo:
975
243
    CmdArgs.push_back("-debug-info-kind=limited");
976
243
    break;
977
6.12k
  case codegenoptions::FullDebugInfo:
978
6.12k
    CmdArgs.push_back("-debug-info-kind=standalone");
979
6.12k
    break;
980
1
  case codegenoptions::UnusedTypeInfo:
981
1
    CmdArgs.push_back("-debug-info-kind=unused-types");
982
1
    break;
983
36.6k
  default:
984
36.6k
    break;
985
43.1k
  }
986
43.1k
  if (DwarfVersion > 0)
987
6.72k
    CmdArgs.push_back(
988
6.72k
        Args.MakeArgString("-dwarf-version=" + Twine(DwarfVersion)));
989
43.1k
  switch (DebuggerTuning) {
990
17.0k
  case llvm::DebuggerKind::GDB:
991
17.0k
    CmdArgs.push_back("-debugger-tuning=gdb");
992
17.0k
    break;
993
17.9k
  case llvm::DebuggerKind::LLDB:
994
17.9k
    CmdArgs.push_back("-debugger-tuning=lldb");
995
17.9k
    break;
996
130
  case llvm::DebuggerKind::SCE:
997
130
    CmdArgs.push_back("-debugger-tuning=sce");
998
130
    break;
999
7.94k
  default:
1000
7.94k
    break;
1001
43.1k
  }
1002
43.1k
}
1003
1004
static bool checkDebugInfoOption(const Arg *A, const ArgList &Args,
1005
14.1k
                                 const Driver &D, const ToolChain &TC) {
1006
14.1k
  assert(A && "Expected non-nullptr argument.");
1007
14.1k
  if (TC.supportsDebugInfoOption(A))
1008
14.1k
    return true;
1009
4
  D.Diag(diag::warn_drv_unsupported_debug_info_opt_for_target)
1010
4
      << A->getAsString(Args) << TC.getTripleString();
1011
4
  return false;
1012
4
}
1013
1014
static void RenderDebugInfoCompressionArgs(const ArgList &Args,
1015
                                           ArgStringList &CmdArgs,
1016
                                           const Driver &D,
1017
43.1k
                                           const ToolChain &TC) {
1018
43.1k
  const Arg *A = Args.getLastArg(options::OPT_gz, options::OPT_gz_EQ);
1019
43.1k
  if (!A)
1020
43.0k
    return;
1021
31
  if (checkDebugInfoOption(A, Args, D, TC)) {
1022
28
    if (A->getOption().getID() == options::OPT_gz) {
1023
6
      if (llvm::zlib::isAvailable())
1024
6
        CmdArgs.push_back("--compress-debug-sections");
1025
0
      else
1026
0
        D.Diag(diag::warn_debug_compression_unavailable);
1027
6
      return;
1028
6
    }
1029
22
1030
22
    StringRef Value = A->getValue();
1031
22
    if (Value == "none") {
1032
5
      CmdArgs.push_back("--compress-debug-sections=none");
1033
17
    } else if (Value == "zlib" || 
Value == "zlib-gnu"8
) {
1034
14
      if (llvm::zlib::isAvailable()) {
1035
14
        CmdArgs.push_back(
1036
14
            Args.MakeArgString("--compress-debug-sections=" + Twine(Value)));
1037
0
      } else {
1038
0
        D.Diag(diag::warn_debug_compression_unavailable);
1039
0
      }
1040
3
    } else {
1041
3
      D.Diag(diag::err_drv_unsupported_option_argument)
1042
3
          << A->getOption().getName() << Value;
1043
3
    }
1044
22
  }
1045
31
}
1046
1047
43.1k
static const char *RelocationModelName(llvm::Reloc::Model Model) {
1048
43.1k
  switch (Model) {
1049
16.1k
  case llvm::Reloc::Static:
1050
16.1k
    return "static";
1051
26.9k
  case llvm::Reloc::PIC_:
1052
26.9k
    return "pic";
1053
8
  case llvm::Reloc::DynamicNoPIC:
1054
8
    return "dynamic-no-pic";
1055
11
  case llvm::Reloc::ROPI:
1056
11
    return "ropi";
1057
6
  case llvm::Reloc::RWPI:
1058
6
    return "rwpi";
1059
6
  case llvm::Reloc::ROPI_RWPI:
1060
6
    return "ropi-rwpi";
1061
0
  }
1062
0
  llvm_unreachable("Unknown Reloc::Model kind");
1063
0
}
1064
1065
void Clang::AddPreprocessingOptions(Compilation &C, const JobAction &JA,
1066
                                    const Driver &D, const ArgList &Args,
1067
                                    ArgStringList &CmdArgs,
1068
                                    const InputInfo &Output,
1069
42.4k
                                    const InputInfoList &Inputs) const {
1070
42.4k
  const bool IsIAMCU = getToolChain().getTriple().isOSIAMCU();
1071
42.4k
1072
42.4k
  CheckPreprocessingOptions(D, Args);
1073
42.4k
1074
42.4k
  Args.AddLastArg(CmdArgs, options::OPT_C);
1075
42.4k
  Args.AddLastArg(CmdArgs, options::OPT_CC);
1076
42.4k
1077
  // Handle dependency file generation.
1078
42.4k
  Arg *ArgM = Args.getLastArg(options::OPT_MM);
1079
42.4k
  if (!ArgM)
1080
42.4k
    ArgM = Args.getLastArg(options::OPT_M);
1081
42.4k
  Arg *ArgMD = Args.getLastArg(options::OPT_MMD);
1082
42.4k
  if (!ArgMD)
1083
42.4k
    ArgMD = Args.getLastArg(options::OPT_MD);
1084
42.4k
1085
  // -M and -MM imply -w.
1086
42.4k
  if (ArgM)
1087
2.92k
    CmdArgs.push_back("-w");
1088
39.4k
  else
1089
39.4k
    ArgM = ArgMD;
1090
42.4k
1091
42.4k
  if (ArgM) {
1092
    // Determine the output location.
1093
2.96k
    const char *DepFile;
1094
2.96k
    if (Arg *MF = Args.getLastArg(options::OPT_MF)) {
1095
2.89k
      DepFile = MF->getValue();
1096
2.89k
      C.addFailureResultFile(DepFile, &JA);
1097
68
    } else if (Output.getType() == types::TY_Dependencies) {
1098
62
      DepFile = Output.getFilename();
1099
6
    } else if (!ArgMD) {
1100
0
      DepFile = "-";
1101
6
    } else {
1102
6
      DepFile = getDependencyFileName(Args, Inputs);
1103
6
      C.addFailureResultFile(DepFile, &JA);
1104
6
    }
1105
2.96k
    CmdArgs.push_back("-dependency-file");
1106
2.96k
    CmdArgs.push_back(DepFile);
1107
2.96k
1108
2.96k
    bool HasTarget = false;
1109
5.77k
    for (const Arg *A : Args.filtered(options::OPT_MT, options::OPT_MQ)) {
1110
5.77k
      HasTarget = true;
1111
5.77k
      A->claim();
1112
5.77k
      if (A->getOption().matches(options::OPT_MT)) {
1113
5.77k
        A->render(Args, CmdArgs);
1114
5
      } else {
1115
5
        CmdArgs.push_back("-MT");
1116
5
        SmallString<128> Quoted;
1117
5
        QuoteTarget(A->getValue(), Quoted);
1118
5
        CmdArgs.push_back(Args.MakeArgString(Quoted));
1119
5
      }
1120
5.77k
    }
1121
2.96k
1122
    // Add a default target if one wasn't specified.
1123
2.96k
    if (!HasTarget) {
1124
37
      const char *DepTarget;
1125
37
1126
      // If user provided -o, that is the dependency target, except
1127
      // when we are only generating a dependency file.
1128
37
      Arg *OutputOpt = Args.getLastArg(options::OPT_o);
1129
37
      if (OutputOpt && 
Output.getType() != types::TY_Dependencies8
) {
1130
6
        DepTarget = OutputOpt->getValue();
1131
31
      } else {
1132
        // Otherwise derive from the base input.
1133
        //
1134
        // FIXME: This should use the computed output file location.
1135
31
        SmallString<128> P(Inputs[0].getBaseInput());
1136
31
        llvm::sys::path::replace_extension(P, "o");
1137
31
        DepTarget = Args.MakeArgString(llvm::sys::path::filename(P));
1138
31
      }
1139
37
1140
37
      CmdArgs.push_back("-MT");
1141
37
      SmallString<128> Quoted;
1142
37
      QuoteTarget(DepTarget, Quoted);
1143
37
      CmdArgs.push_back(Args.MakeArgString(Quoted));
1144
37
    }
1145
2.96k
1146
2.96k
    if (ArgM->getOption().matches(options::OPT_M) ||
1147
36
        ArgM->getOption().matches(options::OPT_MD))
1148
2.94k
      CmdArgs.push_back("-sys-header-deps");
1149
2.96k
    if ((isa<PrecompileJobAction>(JA) &&
1150
2
         !Args.hasArg(options::OPT_fno_module_file_deps)) ||
1151
2.95k
        Args.hasArg(options::OPT_fmodule_file_deps))
1152
2
      CmdArgs.push_back("-module-file-deps");
1153
2.96k
  }
1154
42.4k
1155
42.4k
  if (Args.hasArg(options::OPT_MG)) {
1156
4
    if (!ArgM || ArgM->getOption().matches(options::OPT_MD) ||
1157
4
        ArgM->getOption().matches(options::OPT_MMD))
1158
0
      D.Diag(diag::err_drv_mg_requires_m_or_mm);
1159
4
    CmdArgs.push_back("-MG");
1160
4
  }
1161
42.4k
1162
42.4k
  Args.AddLastArg(CmdArgs, options::OPT_MP);
1163
42.4k
  Args.AddLastArg(CmdArgs, options::OPT_MV);
1164
42.4k
1165
  // Add offload include arguments specific for CUDA/HIP.  This must happen
1166
  // before we -I or -include anything else, because we must pick up the
1167
  // CUDA/HIP headers from the particular CUDA/ROCm installation, rather than
1168
  // from e.g. /usr/local/include.
1169
42.4k
  if (JA.isOffloading(Action::OFK_Cuda))
1170
475
    getToolChain().AddCudaIncludeArgs(Args, CmdArgs);
1171
42.4k
  if (JA.isOffloading(Action::OFK_HIP))
1172
238
    getToolChain().AddHIPIncludeArgs(Args, CmdArgs);
1173
42.4k
1174
  // If we are offloading to a target via OpenMP we need to include the
1175
  // openmp_wrappers folder which contains alternative system headers.
1176
42.4k
  if (JA.isDeviceOffloading(Action::OFK_OpenMP) &&
1177
69
      getToolChain().getTriple().isNVPTX()){
1178
43
    if (!Args.hasArg(options::OPT_nobuiltininc)) {
1179
      // Add openmp_wrappers/* to our system include path.  This lets us wrap
1180
      // standard library headers.
1181
43
      SmallString<128> P(D.ResourceDir);
1182
43
      llvm::sys::path::append(P, "include");
1183
43
      llvm::sys::path::append(P, "openmp_wrappers");
1184
43
      CmdArgs.push_back("-internal-isystem");
1185
43
      CmdArgs.push_back(Args.MakeArgString(P));
1186
43
    }
1187
43
1188
43
    CmdArgs.push_back("-include");
1189
43
    CmdArgs.push_back("__clang_openmp_device_functions.h");
1190
43
  }
1191
42.4k
1192
  // Add -i* options, and automatically translate to
1193
  // -include-pch/-include-pth for transparent PCH support. It's
1194
  // wonky, but we include looking for .gch so we can support seamless
1195
  // replacement into a build system already set up to be generating
1196
  // .gch files.
1197
42.4k
1198
42.4k
  if (getToolChain().getDriver().IsCLMode()) {
1199
536
    const Arg *YcArg = Args.getLastArg(options::OPT__SLASH_Yc);
1200
536
    const Arg *YuArg = Args.getLastArg(options::OPT__SLASH_Yu);
1201
536
    if (YcArg && 
JA.getKind() >= Action::PrecompileJobClass34
&&
1202
34
        JA.getKind() <= Action::AssembleJobClass) {
1203
34
      CmdArgs.push_back(Args.MakeArgString("-building-pch-with-obj"));
1204
34
      CmdArgs.push_back(Args.MakeArgString("-fpch-instantiate-templates"));
1205
34
    }
1206
536
    if (YcArg || 
YuArg502
) {
1207
34
      StringRef ThroughHeader = YcArg ? YcArg->getValue() : 
YuArg->getValue()14
;
1208
48
      if (!isa<PrecompileJobAction>(JA)) {
1209
31
        CmdArgs.push_back("-include-pch");
1210
31
        CmdArgs.push_back(Args.MakeArgString(D.GetClPchPath(
1211
31
            C, !ThroughHeader.empty()
1212
28
                   ? ThroughHeader
1213
3
                   : llvm::sys::path::filename(Inputs[0].getBaseInput()))));
1214
31
      }
1215
48
1216
48
      if (ThroughHeader.empty()) {
1217
5
        CmdArgs.push_back(Args.MakeArgString(
1218
4
            Twine("-pch-through-hdrstop-") + (YcArg ? "create" : 
"use"1
)));
1219
43
      } else {
1220
43
        CmdArgs.push_back(
1221
43
            Args.MakeArgString(Twine("-pch-through-header=") + ThroughHeader));
1222
43
      }
1223
48
    }
1224
536
  }
1225
42.4k
1226
42.4k
  bool RenderedImplicitInclude = false;
1227
15.1k
  for (const Arg *A : Args.filtered(options::OPT_clang_i_Group)) {
1228
15.1k
    if (A->getOption().matches(options::OPT_include)) {
1229
      // Handling of gcc-style gch precompiled headers.
1230
5.95k
      bool IsFirstImplicitInclude = !RenderedImplicitInclude;
1231
5.95k
      RenderedImplicitInclude = true;
1232
5.95k
1233
5.95k
      bool FoundPCH = false;
1234
5.95k
      SmallString<128> P(A->getValue());
1235
      // We want the files to have a name like foo.h.pch. Add a dummy extension
1236
      // so that replace_extension does the right thing.
1237
5.95k
      P += ".dummy";
1238
5.95k
      llvm::sys::path::replace_extension(P, "pch");
1239
5.95k
      if (llvm::sys::fs::exists(P))
1240
69
        FoundPCH = true;
1241
5.95k
1242
5.95k
      if (!FoundPCH) {
1243
5.88k
        llvm::sys::path::replace_extension(P, "gch");
1244
5.88k
        if (llvm::sys::fs::exists(P)) {
1245
8
          FoundPCH = true;
1246
8
        }
1247
5.88k
      }
1248
5.95k
1249
5.95k
      if (FoundPCH) {
1250
77
        if (IsFirstImplicitInclude) {
1251
77
          A->claim();
1252
77
          CmdArgs.push_back("-include-pch");
1253
77
          CmdArgs.push_back(Args.MakeArgString(P));
1254
77
          continue;
1255
0
        } else {
1256
          // Ignore the PCH if not first on command line and emit warning.
1257
0
          D.Diag(diag::warn_drv_pch_not_first_include) << P
1258
0
                                                       << A->getAsString(Args);
1259
0
        }
1260
77
      }
1261
9.23k
    } else if (A->getOption().matches(options::OPT_isystem_after)) {
1262
      // Handling of paths which must come late.  These entries are handled by
1263
      // the toolchain itself after the resource dir is inserted in the right
1264
      // search order.
1265
      // Do not claim the argument so that the use of the argument does not
1266
      // silently go unnoticed on toolchains which do not honour the option.
1267
4
      continue;
1268
9.23k
    } else if (A->getOption().matches(options::OPT_stdlibxx_isystem)) {
1269
      // Translated to -internal-isystem by the driver, no need to pass to cc1.
1270
14
      continue;
1271
14
    }
1272
15.0k
1273
    // Not translated, render as usual.
1274
15.0k
    A->claim();
1275
15.0k
    A->render(Args, CmdArgs);
1276
15.0k
  }
1277
42.4k
1278
42.4k
  Args.AddAllArgs(CmdArgs,
1279
42.4k
                  {options::OPT_D, options::OPT_U, options::OPT_I_Group,
1280
42.4k
                   options::OPT_F, options::OPT_index_header_map});
1281
42.4k
1282
  // Add -Wp, and -Xpreprocessor if using the preprocessor.
1283
42.4k
1284
  // FIXME: There is a very unfortunate problem here, some troubled
1285
  // souls abuse -Wp, to pass preprocessor options in gcc syntax. To
1286
  // really support that we would have to parse and then translate
1287
  // those options. :(
1288
42.4k
  Args.AddAllArgValues(CmdArgs, options::OPT_Wp_COMMA,
1289
42.4k
                       options::OPT_Xpreprocessor);
1290
42.4k
1291
  // -I- is a deprecated GCC feature, reject it.
1292
42.4k
  if (Arg *A = Args.getLastArg(options::OPT_I_))
1293
0
    D.Diag(diag::err_drv_I_dash_not_supported) << A->getAsString(Args);
1294
42.4k
1295
  // If we have a --sysroot, and don't have an explicit -isysroot flag, add an
1296
  // -isysroot to the CC1 invocation.
1297
42.4k
  StringRef sysroot = C.getSysRoot();
1298
42.4k
  if (sysroot != "") {
1299
733
    if (!Args.hasArg(options::OPT_isysroot)) {
1300
728
      CmdArgs.push_back("-isysroot");
1301
728
      CmdArgs.push_back(C.getArgs().MakeArgString(sysroot));
1302
728
    }
1303
733
  }
1304
42.4k
1305
  // Parse additional include paths from environment variables.
1306
  // FIXME: We should probably sink the logic for handling these from the
1307
  // frontend into the driver. It will allow deleting 4 otherwise unused flags.
1308
  // CPATH - included following the user specified includes (but prior to
1309
  // builtin and standard includes).
1310
42.4k
  addDirectoryList(Args, CmdArgs, "-I", "CPATH");
1311
  // C_INCLUDE_PATH - system includes enabled when compiling C.
1312
42.4k
  addDirectoryList(Args, CmdArgs, "-c-isystem", "C_INCLUDE_PATH");
1313
  // CPLUS_INCLUDE_PATH - system includes enabled when compiling C++.
1314
42.4k
  addDirectoryList(Args, CmdArgs, "-cxx-isystem", "CPLUS_INCLUDE_PATH");
1315
  // OBJC_INCLUDE_PATH - system includes enabled when compiling ObjC.
1316
42.4k
  addDirectoryList(Args, CmdArgs, "-objc-isystem", "OBJC_INCLUDE_PATH");
1317
  // OBJCPLUS_INCLUDE_PATH - system includes enabled when compiling ObjC++.
1318
42.4k
  addDirectoryList(Args, CmdArgs, "-objcxx-isystem", "OBJCPLUS_INCLUDE_PATH");
1319
42.4k
1320
  // While adding the include arguments, we also attempt to retrieve the
1321
  // arguments of related offloading toolchains or arguments that are specific
1322
  // of an offloading programming model.
1323
42.4k
1324
  // Add C++ include arguments, if needed.
1325
42.4k
  if (types::isCXX(Inputs[0].getType())) {
1326
28.3k
    bool HasStdlibxxIsystem = Args.hasArg(options::OPT_stdlibxx_isystem);
1327
28.3k
    forAllAssociatedToolChains(
1328
28.3k
        C, JA, getToolChain(),
1329
29.1k
        [&Args, &CmdArgs, HasStdlibxxIsystem](const ToolChain &TC) {
1330
8
          HasStdlibxxIsystem ? TC.AddClangCXXStdlibIsystemArgs(Args, CmdArgs)
1331
29.1k
                             : TC.AddClangCXXStdlibIncludeArgs(Args, CmdArgs);
1332
29.1k
        });
1333
28.3k
  }
1334
42.4k
1335
  // Add system include arguments for all targets but IAMCU.
1336
42.4k
  if (!IsIAMCU)
1337
42.4k
    forAllAssociatedToolChains(C, JA, getToolChain(),
1338
43.3k
                               [&Args, &CmdArgs](const ToolChain &TC) {
1339
43.3k
                                 TC.AddClangSystemIncludeArgs(Args, CmdArgs);
1340
43.3k
                               });
1341
6
  else {
1342
    // For IAMCU add special include arguments.
1343
6
    getToolChain().AddIAMCUIncludeArgs(Args, CmdArgs);
1344
6
  }
1345
42.4k
1346
42.4k
  addMacroPrefixMapArg(D, Args, CmdArgs);
1347
42.4k
}
1348
1349
// FIXME: Move to target hook.
1350
42.7k
static bool isSignedCharDefault(const llvm::Triple &Triple) {
1351
42.7k
  switch (Triple.getArch()) {
1352
39.0k
  default:
1353
39.0k
    return true;
1354
0
1355
2.83k
  case llvm::Triple::aarch64:
1356
2.83k
  case llvm::Triple::aarch64_32:
1357
2.83k
  case llvm::Triple::aarch64_be:
1358
2.83k
  case llvm::Triple::arm:
1359
2.83k
  case llvm::Triple::armeb:
1360
2.83k
  case llvm::Triple::thumb:
1361
2.83k
  case llvm::Triple::thumbeb:
1362
2.83k
    if (Triple.isOSDarwin() || 
Triple.isOSWindows()2.65k
)
1363
251
      return true;
1364
2.58k
    return false;
1365
2.58k
1366
239
  case llvm::Triple::ppc:
1367
239
  case llvm::Triple::ppc64:
1368
239
    if (Triple.isOSDarwin())
1369
0
      return true;
1370
239
    return false;
1371
239
1372
642
  case llvm::Triple::hexagon:
1373
642
  case llvm::Triple::ppc64le:
1374
642
  case llvm::Triple::riscv32:
1375
642
  case llvm::Triple::riscv64:
1376
642
  case llvm::Triple::systemz:
1377
642
  case llvm::Triple::xcore:
1378
642
    return false;
1379
42.7k
  }
1380
42.7k
}
1381
1382
static bool hasMultipleInvocations(const llvm::Triple &Triple,
1383
34
                                   const ArgList &Args) {
1384
  // Supported only on Darwin where we invoke the compiler multiple times
1385
  // followed by an invocation to lipo.
1386
34
  if (!Triple.isOSDarwin())
1387
3
    return false;
1388
  // If more than one "-arch <arch>" is specified, we're targeting multiple
1389
  // architectures resulting in a fat binary.
1390
31
  return Args.getAllArgValues(options::OPT_arch).size() > 1;
1391
31
}
1392
1393
static bool checkRemarksOptions(const Driver &D, const ArgList &Args,
1394
34
                                const llvm::Triple &Triple) {
1395
  // When enabling remarks, we need to error if:
1396
  // * The remark file is specified but we're targeting multiple architectures,
1397
  // which means more than one remark file is being generated.
1398
34
  bool hasMultipleInvocations = ::hasMultipleInvocations(Triple, Args);
1399
34
  bool hasExplicitOutputFile =
1400
34
      Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1401
34
  if (hasMultipleInvocations && 
hasExplicitOutputFile4
) {
1402
2
    D.Diag(diag::err_drv_invalid_output_with_multiple_archs)
1403
2
        << "-foptimization-record-file";
1404
2
    return false;
1405
2
  }
1406
32
  return true;
1407
32
}
1408
1409
static void renderRemarksOptions(const ArgList &Args, ArgStringList &CmdArgs,
1410
                                 const llvm::Triple &Triple,
1411
                                 const InputInfo &Input,
1412
32
                                 const InputInfo &Output, const JobAction &JA) {
1413
32
  StringRef Format = "yaml";
1414
32
  if (const Arg *A = Args.getLastArg(options::OPT_fsave_optimization_record_EQ))
1415
3
    Format = A->getValue();
1416
32
1417
32
  CmdArgs.push_back("-opt-record-file");
1418
32
1419
32
  const Arg *A = Args.getLastArg(options::OPT_foptimization_record_file_EQ);
1420
32
  if (A) {
1421
2
    CmdArgs.push_back(A->getValue());
1422
30
  } else {
1423
30
    bool hasMultipleArchs =
1424
30
        Triple.isOSDarwin() && // Only supported on Darwin platforms.
1425
27
        Args.getAllArgValues(options::OPT_arch).size() > 1;
1426
30
1427
30
    SmallString<128> F;
1428
30
1429
30
    if (Args.hasArg(options::OPT_c) || 
Args.hasArg(options::OPT_S)16
) {
1430
24
      if (Arg *FinalOutput = Args.getLastArg(options::OPT_o))
1431
16
        F = FinalOutput->getValue();
1432
6
    } else {
1433
6
      if (Format != "yaml" && // For YAML, keep the original behavior.
1434
1
          Triple.isOSDarwin() && // Enable this only on darwin, since it's the only platform supporting .dSYM bundles.
1435
1
          Output.isFilename())
1436
1
        F = Output.getFilename();
1437
6
    }
1438
30
1439
30
    if (F.empty()) {
1440
      // Use the input filename.
1441
13
      F = llvm::sys::path::stem(Input.getBaseInput());
1442
13
1443
      // If we're compiling for an offload architecture (i.e. a CUDA device),
1444
      // we need to make the file name for the device compilation different
1445
      // from the host compilation.
1446
13
      if (!JA.isDeviceOffloading(Action::OFK_None) &&
1447
2
          !JA.isDeviceOffloading(Action::OFK_Host)) {
1448
2
        llvm::sys::path::replace_extension(F, "");
1449
2
        F += Action::GetOffloadingFileNamePrefix(JA.getOffloadingDeviceKind(),
1450
2
                                                 Triple.normalize());
1451
2
        F += "-";
1452
2
        F += JA.getOffloadingArch();
1453
2
      }
1454
13
    }
1455
30
1456
    // If we're having more than one "-arch", we should name the files
1457
    // differently so that every cc1 invocation writes to a different file.
1458
    // We're doing that by appending "-<arch>" with "<arch>" being the arch
1459
    // name from the triple.
1460
30
    if (hasMultipleArchs) {
1461
      // First, remember the extension.
1462
2
      SmallString<64> OldExtension = llvm::sys::path::extension(F);
1463
      // then, remove it.
1464
2
      llvm::sys::path::replace_extension(F, "");
1465
      // attach -<arch> to it.
1466
2
      F += "-";
1467
2
      F += Triple.getArchName();
1468
      // put back the extension.
1469
2
      llvm::sys::path::replace_extension(F, OldExtension);
1470
2
    }
1471
30
1472
30
    SmallString<32> Extension;
1473
30
    Extension += "opt.";
1474
30
    Extension += Format;
1475
30
1476
30
    llvm::sys::path::replace_extension(F, Extension);
1477
30
    CmdArgs.push_back(Args.MakeArgString(F));
1478
30
  }
1479
32
1480
32
  if (const Arg *A =
1481
2
          Args.getLastArg(options::OPT_foptimization_record_passes_EQ)) {
1482
2
    CmdArgs.push_back("-opt-record-passes");
1483
2
    CmdArgs.push_back(A->getValue());
1484
2
  }
1485
32
1486
32
  if (!Format.empty()) {
1487
32
    CmdArgs.push_back("-opt-record-format");
1488
32
    CmdArgs.push_back(Format.data());
1489
32
  }
1490
32
}
1491
1492
namespace {
1493
void RenderARMABI(const llvm::Triple &Triple, const ArgList &Args,
1494
1.70k
                  ArgStringList &CmdArgs) {
1495
  // Select the ABI to use.
1496
  // FIXME: Support -meabi.
1497
  // FIXME: Parts of this are duplicated in the backend, unify this somehow.
1498
1.70k
  const char *ABIName = nullptr;
1499
1.70k
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
1500
3
    ABIName = A->getValue();
1501
1.70k
  } else {
1502
1.70k
    std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
1503
1.70k
    ABIName = llvm::ARM::computeDefaultTargetABI(Triple, CPU).data();
1504
1.70k
  }
1505
1.70k
1506
1.70k
  CmdArgs.push_back("-target-abi");
1507
1.70k
  CmdArgs.push_back(ABIName);
1508
1.70k
}
1509
}
1510
1511
void Clang::AddARMTargetArgs(const llvm::Triple &Triple, const ArgList &Args,
1512
1.70k
                             ArgStringList &CmdArgs, bool KernelOrKext) const {
1513
1.70k
  RenderARMABI(Triple, Args, CmdArgs);
1514
1.70k
1515
  // Determine floating point ABI from the options & target defaults.
1516
1.70k
  arm::FloatABI ABI = arm::getARMFloatABI(getToolChain(), Args);
1517
1.70k
  if (ABI == arm::FloatABI::Soft) {
1518
    // Floating point operations and argument passing are soft.
1519
    // FIXME: This changes CPP defines, we need -target-soft-float.
1520
738
    CmdArgs.push_back("-msoft-float");
1521
738
    CmdArgs.push_back("-mfloat-abi");
1522
738
    CmdArgs.push_back("soft");
1523
968
  } else if (ABI == arm::FloatABI::SoftFP) {
1524
    // Floating point operations are hard, but argument passing is soft.
1525
784
    CmdArgs.push_back("-mfloat-abi");
1526
784
    CmdArgs.push_back("soft");
1527
184
  } else {
1528
    // Floating point operations and argument passing are hard.
1529
184
    assert(ABI == arm::FloatABI::Hard && "Invalid float abi!");
1530
184
    CmdArgs.push_back("-mfloat-abi");
1531
184
    CmdArgs.push_back("hard");
1532
184
  }
1533
1.70k
1534
  // Forward the -mglobal-merge option for explicit control over the pass.
1535
1.70k
  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1536
2
                               options::OPT_mno_global_merge)) {
1537
2
    CmdArgs.push_back("-mllvm");
1538
2
    if (A->getOption().matches(options::OPT_mno_global_merge))
1539
1
      CmdArgs.push_back("-arm-global-merge=false");
1540
1
    else
1541
1
      CmdArgs.push_back("-arm-global-merge=true");
1542
2
  }
1543
1.70k
1544
1.70k
  if (!Args.hasFlag(options::OPT_mimplicit_float,
1545
1.70k
                    options::OPT_mno_implicit_float, true))
1546
1
    CmdArgs.push_back("-no-implicit-float");
1547
1.70k
1548
1.70k
  if (Args.getLastArg(options::OPT_mcmse))
1549
15
    CmdArgs.push_back("-mcmse");
1550
1.70k
}
1551
1552
void Clang::RenderTargetOptions(const llvm::Triple &EffectiveTriple,
1553
                                const ArgList &Args, bool KernelOrKext,
1554
42.7k
                                ArgStringList &CmdArgs) const {
1555
42.7k
  const ToolChain &TC = getToolChain();
1556
42.7k
1557
  // Add the target features
1558
42.7k
  getTargetFeatures(TC.getDriver(), EffectiveTriple, Args, CmdArgs, false);
1559
42.7k
1560
  // Add target specific flags.
1561
42.7k
  switch (TC.getArch()) {
1562
873
  default:
1563
873
    break;
1564
0
1565
1.70k
  case llvm::Triple::arm:
1566
1.70k
  case llvm::Triple::armeb:
1567
1.70k
  case llvm::Triple::thumb:
1568
1.70k
  case llvm::Triple::thumbeb:
1569
    // Use the effective triple, which takes into account the deployment target.
1570
1.70k
    AddARMTargetArgs(EffectiveTriple, Args, CmdArgs, KernelOrKext);
1571
1.70k
    CmdArgs.push_back("-fallow-half-arguments-and-returns");
1572
1.70k
    break;
1573
1.70k
1574
1.12k
  case llvm::Triple::aarch64:
1575
1.12k
  case llvm::Triple::aarch64_32:
1576
1.12k
  case llvm::Triple::aarch64_be:
1577
1.12k
    AddAArch64TargetArgs(Args, CmdArgs);
1578
1.12k
    CmdArgs.push_back("-fallow-half-arguments-and-returns");
1579
1.12k
    break;
1580
1.12k
1581
584
  case llvm::Triple::mips:
1582
584
  case llvm::Triple::mipsel:
1583
584
  case llvm::Triple::mips64:
1584
584
  case llvm::Triple::mips64el:
1585
584
    AddMIPSTargetArgs(Args, CmdArgs);
1586
584
    break;
1587
584
1588
394
  case llvm::Triple::ppc:
1589
394
  case llvm::Triple::ppc64:
1590
394
  case llvm::Triple::ppc64le:
1591
394
    AddPPCTargetArgs(Args, CmdArgs);
1592
394
    break;
1593
394
1594
309
  case llvm::Triple::riscv32:
1595
309
  case llvm::Triple::riscv64:
1596
309
    AddRISCVTargetArgs(Args, CmdArgs);
1597
309
    break;
1598
309
1599
168
  case llvm::Triple::sparc:
1600
168
  case llvm::Triple::sparcel:
1601
168
  case llvm::Triple::sparcv9:
1602
168
    AddSparcTargetArgs(Args, CmdArgs);
1603
168
    break;
1604
168
1605
58
  case llvm::Triple::systemz:
1606
58
    AddSystemZTargetArgs(Args, CmdArgs);
1607
58
    break;
1608
168
1609
37.3k
  case llvm::Triple::x86:
1610
37.3k
  case llvm::Triple::x86_64:
1611
37.3k
    AddX86TargetArgs(Args, CmdArgs);
1612
37.3k
    break;
1613
37.3k
1614
2
  case llvm::Triple::lanai:
1615
2
    AddLanaiTargetArgs(Args, CmdArgs);
1616
2
    break;
1617
37.3k
1618
96
  case llvm::Triple::hexagon:
1619
96
    AddHexagonTargetArgs(Args, CmdArgs);
1620
96
    break;
1621
37.3k
1622
73
  case llvm::Triple::wasm32:
1623
73
  case llvm::Triple::wasm64:
1624
73
    AddWebAssemblyTargetArgs(Args, CmdArgs);
1625
73
    break;
1626
73
1627
0
  case llvm::Triple::ve:
1628
0
    AddVETargetArgs(Args, CmdArgs);
1629
0
    break;
1630
42.7k
  }
1631
42.7k
}
1632
1633
namespace {
1634
void RenderAArch64ABI(const llvm::Triple &Triple, const ArgList &Args,
1635
1.12k
                      ArgStringList &CmdArgs) {
1636
1.12k
  const char *ABIName = nullptr;
1637
1.12k
  if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
1638
0
    ABIName = A->getValue();
1639
1.12k
  else if (Triple.isOSDarwin())
1640
78
    ABIName = "darwinpcs";
1641
1.05k
  else
1642
1.05k
    ABIName = "aapcs";
1643
1.12k
1644
1.12k
  CmdArgs.push_back("-target-abi");
1645
1.12k
  CmdArgs.push_back(ABIName);
1646
1.12k
}
1647
}
1648
1649
void Clang::AddAArch64TargetArgs(const ArgList &Args,
1650
1.12k
                                 ArgStringList &CmdArgs) const {
1651
1.12k
  const llvm::Triple &Triple = getToolChain().getEffectiveTriple();
1652
1.12k
1653
1.12k
  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
1654
1.12k
      Args.hasArg(options::OPT_mkernel) ||
1655
1.12k
      Args.hasArg(options::OPT_fapple_kext))
1656
2
    CmdArgs.push_back("-disable-red-zone");
1657
1.12k
1658
1.12k
  if (!Args.hasFlag(options::OPT_mimplicit_float,
1659
1.12k
                    options::OPT_mno_implicit_float, true))
1660
0
    CmdArgs.push_back("-no-implicit-float");
1661
1.12k
1662
1.12k
  RenderAArch64ABI(Triple, Args, CmdArgs);
1663
1.12k
1664
1.12k
  if (Arg *A = Args.getLastArg(options::OPT_mfix_cortex_a53_835769,
1665
6
                               options::OPT_mno_fix_cortex_a53_835769)) {
1666
6
    CmdArgs.push_back("-mllvm");
1667
6
    if (A->getOption().matches(options::OPT_mfix_cortex_a53_835769))
1668
3
      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1669
3
    else
1670
3
      CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=0");
1671
1.12k
  } else if (Triple.isAndroid()) {
1672
    // Enabled A53 errata (835769) workaround by default on android
1673
51
    CmdArgs.push_back("-mllvm");
1674
51
    CmdArgs.push_back("-aarch64-fix-cortex-a53-835769=1");
1675
51
  }
1676
1.12k
1677
  // Forward the -mglobal-merge option for explicit control over the pass.
1678
1.12k
  if (Arg *A = Args.getLastArg(options::OPT_mglobal_merge,
1679
2
                               options::OPT_mno_global_merge)) {
1680
2
    CmdArgs.push_back("-mllvm");
1681
2
    if (A->getOption().matches(options::OPT_mno_global_merge))
1682
1
      CmdArgs.push_back("-aarch64-enable-global-merge=false");
1683
1
    else
1684
1
      CmdArgs.push_back("-aarch64-enable-global-merge=true");
1685
2
  }
1686
1.12k
1687
  // Enable/disable return address signing and indirect branch targets.
1688
1.12k
  if (Arg *A = Args.getLastArg(options::OPT_msign_return_address_EQ,
1689
45
                               options::OPT_mbranch_protection_EQ)) {
1690
45
1691
45
    const Driver &D = getToolChain().getDriver();
1692
45
1693
45
    StringRef Scope, Key;
1694
45
    bool IndirectBranches;
1695
45
1696
45
    if (A->getOption().matches(options::OPT_msign_return_address_EQ)) {
1697
16
      Scope = A->getValue();
1698
16
      if (!Scope.equals("none") && 
!Scope.equals("non-leaf")12
&&
1699
8
          !Scope.equals("all"))
1700
1
        D.Diag(diag::err_invalid_branch_protection)
1701
1
            << Scope << A->getAsString(Args);
1702
16
      Key = "a_key";
1703
16
      IndirectBranches = false;
1704
29
    } else {
1705
29
      StringRef Err;
1706
29
      llvm::AArch64::ParsedBranchProtection PBP;
1707
29
      if (!llvm::AArch64::parseBranchProtection(A->getValue(), PBP, Err))
1708
1
        D.Diag(diag::err_invalid_branch_protection)
1709
1
            << Err << A->getAsString(Args);
1710
29
      Scope = PBP.Scope;
1711
29
      Key = PBP.Key;
1712
29
      IndirectBranches = PBP.BranchTargetEnforcement;
1713
29
    }
1714
45
1715
45
    CmdArgs.push_back(
1716
45
        Args.MakeArgString(Twine("-msign-return-address=") + Scope));
1717
45
    CmdArgs.push_back(
1718
45
        Args.MakeArgString(Twine("-msign-return-address-key=") + Key));
1719
45
    if (IndirectBranches)
1720
10
      CmdArgs.push_back("-mbranch-target-enforce");
1721
45
  }
1722
1.12k
1723
  // Handle -msve_vector_bits=<bits>
1724
1.12k
  if (Arg *A = Args.getLastArg(options::OPT_msve_vector_bits_EQ)) {
1725
21
    StringRef Val = A->getValue();
1726
21
    const Driver &D = getToolChain().getDriver();
1727
21
    if (Val.equals("128") || 
Val.equals("256")17
||
Val.equals("512")14
||
1728
11
        Val.equals("1024") || 
Val.equals("2048")8
)
1729
17
      CmdArgs.push_back(
1730
17
          Args.MakeArgString(llvm::Twine("-msve-vector-bits=") + Val));
1731
    // Silently drop requests for vector-length agnostic code as it's implied.
1732
4
    else if (!Val.equals("scalable"))
1733
      // Handle the unsupported values passed to msve-vector-bits.
1734
2
      D.Diag(diag::err_drv_unsupported_option_argument)
1735
2
          << A->getOption().getName() << Val;
1736
21
  }
1737
1.12k
}
1738
1739
void Clang::AddMIPSTargetArgs(const ArgList &Args,
1740
584
                              ArgStringList &CmdArgs) const {
1741
584
  const Driver &D = getToolChain().getDriver();
1742
584
  StringRef CPUName;
1743
584
  StringRef ABIName;
1744
584
  const llvm::Triple &Triple = getToolChain().getTriple();
1745
584
  mips::getMipsCPUAndABI(Args, Triple, CPUName, ABIName);
1746
584
1747
584
  CmdArgs.push_back("-target-abi");
1748
584
  CmdArgs.push_back(ABIName.data());
1749
584
1750
584
  mips::FloatABI ABI = mips::getMipsFloatABI(D, Args, Triple);
1751
584
  if (ABI == mips::FloatABI::Soft) {
1752
    // Floating point operations and argument passing are soft.
1753
96
    CmdArgs.push_back("-msoft-float");
1754
96
    CmdArgs.push_back("-mfloat-abi");
1755
96
    CmdArgs.push_back("soft");
1756
488
  } else {
1757
    // Floating point operations and argument passing are hard.
1758
488
    assert(ABI == mips::FloatABI::Hard && "Invalid float abi!");
1759
488
    CmdArgs.push_back("-mfloat-abi");
1760
488
    CmdArgs.push_back("hard");
1761
488
  }
1762
584
1763
584
  if (Arg *A = Args.getLastArg(options::OPT_mldc1_sdc1,
1764
2
                               options::OPT_mno_ldc1_sdc1)) {
1765
2
    if (A->getOption().matches(options::OPT_mno_ldc1_sdc1)) {
1766
1
      CmdArgs.push_back("-mllvm");
1767
1
      CmdArgs.push_back("-mno-ldc1-sdc1");
1768
1
    }
1769
2
  }
1770
584
1771
584
  if (Arg *A = Args.getLastArg(options::OPT_mcheck_zero_division,
1772
2
                               options::OPT_mno_check_zero_division)) {
1773
2
    if (A->getOption().matches(options::OPT_mno_check_zero_division)) {
1774
1
      CmdArgs.push_back("-mllvm");
1775
1
      CmdArgs.push_back("-mno-check-zero-division");
1776
1
    }
1777
2
  }
1778
584
1779
584
  if (Arg *A = Args.getLastArg(options::OPT_G)) {
1780
3
    StringRef v = A->getValue();
1781
3
    CmdArgs.push_back("-mllvm");
1782
3
    CmdArgs.push_back(Args.MakeArgString("-mips-ssection-threshold=" + v));
1783
3
    A->claim();
1784
3
  }
1785
584
1786
584
  Arg *GPOpt = Args.getLastArg(options::OPT_mgpopt, options::OPT_mno_gpopt);
1787
584
  Arg *ABICalls =
1788
584
      Args.getLastArg(options::OPT_mabicalls, options::OPT_mno_abicalls);
1789
584
1790
  // -mabicalls is the default for many MIPS environments, even with -fno-pic.
1791
  // -mgpopt is the default for static, -fno-pic environments but these two
1792
  // options conflict. We want to be certain that -mno-abicalls -mgpopt is
1793
  // the only case where -mllvm -mgpopt is passed.
1794
  // NOTE: We need a warning here or in the backend to warn when -mgpopt is
1795
  //       passed explicitly when compiling something with -mabicalls
1796
  //       (implictly) in affect. Currently the warning is in the backend.
1797
  //
1798
  // When the ABI in use is  N64, we also need to determine the PIC mode that
1799
  // is in use, as -fno-pic for N64 implies -mno-abicalls.
1800
584
  bool NoABICalls =
1801
584
      ABICalls && 
ABICalls->getOption().matches(options::OPT_mno_abicalls)36
;
1802
584
1803
584
  llvm::Reloc::Model RelocationModel;
1804
584
  unsigned PICLevel;
1805
584
  bool IsPIE;
1806
584
  std::tie(RelocationModel, PICLevel, IsPIE) =
1807
584
      ParsePICArgs(getToolChain(), Args);
1808
584
1809
584
  NoABICalls = NoABICalls ||
1810
556
               (RelocationModel == llvm::Reloc::Static && 
ABIName == "n64"322
);
1811
584
1812
584
  bool WantGPOpt = GPOpt && 
GPOpt->getOption().matches(options::OPT_mgpopt)17
;
1813
  // We quietly ignore -mno-gpopt as the backend defaults to -mno-gpopt.
1814
584
  if (NoABICalls && 
(28
!GPOpt28
||
WantGPOpt12
)) {
1815
26
    CmdArgs.push_back("-mllvm");
1816
26
    CmdArgs.push_back("-mgpopt");
1817
26
1818
26
    Arg *LocalSData = Args.getLastArg(options::OPT_mlocal_sdata,
1819
26
                                      options::OPT_mno_local_sdata);
1820
26
    Arg *ExternSData = Args.getLastArg(options::OPT_mextern_sdata,
1821
26
                                       options::OPT_mno_extern_sdata);
1822
26
    Arg *EmbeddedData = Args.getLastArg(options::OPT_membedded_data,
1823
26
                                        options::OPT_mno_embedded_data);
1824
26
    if (LocalSData) {
1825
2
      CmdArgs.push_back("-mllvm");
1826
2
      if (LocalSData->getOption().matches(options::OPT_mlocal_sdata)) {
1827
1
        CmdArgs.push_back("-mlocal-sdata=1");
1828
1
      } else {
1829
1
        CmdArgs.push_back("-mlocal-sdata=0");
1830
1
      }
1831
2
      LocalSData->claim();
1832
2
    }
1833
26
1834
26
    if (ExternSData) {
1835
2
      CmdArgs.push_back("-mllvm");
1836
2
      if (ExternSData->getOption().matches(options::OPT_mextern_sdata)) {
1837
1
        CmdArgs.push_back("-mextern-sdata=1");
1838
1
      } else {
1839
1
        CmdArgs.push_back("-mextern-sdata=0");
1840
1
      }
1841
2
      ExternSData->claim();
1842
2
    }
1843
26
1844
26
    if (EmbeddedData) {
1845
2
      CmdArgs.push_back("-mllvm");
1846
2
      if (EmbeddedData->getOption().matches(options::OPT_membedded_data)) {
1847
1
        CmdArgs.push_back("-membedded-data=1");
1848
1
      } else {
1849
1
        CmdArgs.push_back("-membedded-data=0");
1850
1
      }
1851
2
      EmbeddedData->claim();
1852
2
    }
1853
26
1854
558
  } else if ((!ABICalls || 
(10
!NoABICalls10
&&
ABICalls8
)) &&
WantGPOpt556
)
1855
5
    D.Diag(diag::warn_drv_unsupported_gpopt) << (ABICalls ? 
02
:
13
);
1856
584
1857
584
  if (GPOpt)
1858
17
    GPOpt->claim();
1859
584
1860
584
  if (Arg *A = Args.getLastArg(options::OPT_mcompact_branches_EQ)) {
1861
3
    StringRef Val = StringRef(A->getValue());
1862
3
    if (mips::hasCompactBranches(CPUName)) {
1863
3
      if (Val == "never" || 
Val == "always"2
||
Val == "optimal"1
) {
1864
3
        CmdArgs.push_back("-mllvm");
1865
3
        CmdArgs.push_back(Args.MakeArgString("-mips-compact-branches=" + Val));
1866
3
      } else
1867
0
        D.Diag(diag::err_drv_unsupported_option_argument)
1868
0
            << A->getOption().getName() << Val;
1869
3
    } else
1870
0
      D.Diag(diag::warn_target_unsupported_compact_branches) << CPUName;
1871
3
  }
1872
584
1873
584
  if (Arg *A = Args.getLastArg(options::OPT_mrelax_pic_calls,
1874
2
                               options::OPT_mno_relax_pic_calls)) {
1875
2
    if (A->getOption().matches(options::OPT_mno_relax_pic_calls)) {
1876
1
      CmdArgs.push_back("-mllvm");
1877
1
      CmdArgs.push_back("-mips-jalr-reloc=0");
1878
1
    }
1879
2
  }
1880
584
}
1881
1882
void Clang::AddPPCTargetArgs(const ArgList &Args,
1883
394
                             ArgStringList &CmdArgs) const {
1884
  // Select the ABI to use.
1885
394
  const char *ABIName = nullptr;
1886
394
  const llvm::Triple &T = getToolChain().getTriple();
1887
394
  if (T.isOSBinFormatELF()) {
1888
341
    switch (getToolChain().getArch()) {
1889
140
    case llvm::Triple::ppc64: {
1890
140
      if ((T.isOSFreeBSD() && 
T.getOSMajorVersion() >= 1310
) ||
1891
137
          T.isOSOpenBSD() || 
T.isMusl()136
)
1892
6
        ABIName = "elfv2";
1893
134
      else
1894
134
        ABIName = "elfv1";
1895
140
      break;
1896
0
    }
1897
156
    case llvm::Triple::ppc64le:
1898
156
      ABIName = "elfv2";
1899
156
      break;
1900
45
    default:
1901
45
      break;
1902
394
    }
1903
394
  }
1904
394
1905
394
  bool IEEELongDouble = false;
1906
24
  for (const Arg *A : Args.filtered(options::OPT_mabi_EQ)) {
1907
24
    StringRef V = A->getValue();
1908
24
    if (V == "ieeelongdouble")
1909
3
      IEEELongDouble = true;
1910
21
    else if (V == "ibmlongdouble")
1911
2
      IEEELongDouble = false;
1912
19
    else if (V != "altivec")
1913
      // The ppc64 linux abis are all "altivec" abis by default. Accept and ignore
1914
      // the option if given as we don't have backend support for any targets
1915
      // that don't use the altivec abi.
1916
17
      ABIName = A->getValue();
1917
24
  }
1918
394
  if (IEEELongDouble)
1919
3
    CmdArgs.push_back("-mabi=ieeelongdouble");
1920
394
1921
394
  ppc::FloatABI FloatABI =
1922
394
      ppc::getPPCFloatABI(getToolChain().getDriver(), Args);
1923
394
1924
394
  if (FloatABI == ppc::FloatABI::Soft) {
1925
    // Floating point operations and argument passing are soft.
1926
9
    CmdArgs.push_back("-msoft-float");
1927
9
    CmdArgs.push_back("-mfloat-abi");
1928
9
    CmdArgs.push_back("soft");
1929
385
  } else {
1930
    // Floating point operations and argument passing are hard.
1931
385
    assert(FloatABI == ppc::FloatABI::Hard && "Invalid float abi!");
1932
385
    CmdArgs.push_back("-mfloat-abi");
1933
385
    CmdArgs.push_back("hard");
1934
385
  }
1935
394
1936
394
  if (ABIName) {
1937
296
    CmdArgs.push_back("-target-abi");
1938
296
    CmdArgs.push_back(ABIName);
1939
296
  }
1940
394
}
1941
1942
static void SetRISCVSmallDataLimit(const ToolChain &TC, const ArgList &Args,
1943
309
                                   ArgStringList &CmdArgs) {
1944
309
  const Driver &D = TC.getDriver();
1945
309
  const llvm::Triple &Triple = TC.getTriple();
1946
  // Default small data limitation is eight.
1947
309
  const char *SmallDataLimit = "8";
1948
  // Get small data limitation.
1949
309
  if (Args.getLastArg(options::OPT_shared, options::OPT_fpic,
1950
3
                      options::OPT_fPIC)) {
1951
    // Not support linker relaxation for PIC.
1952
3
    SmallDataLimit = "0";
1953
3
    if (Args.hasArg(options::OPT_G)) {
1954
1
      D.Diag(diag::warn_drv_unsupported_sdata);
1955
1
    }
1956
306
  } else if (Args.getLastArgValue(options::OPT_mcmodel_EQ)
1957
306
                 .equals_lower("large") &&
1958
2
             (Triple.getArch() == llvm::Triple::riscv64)) {
1959
    // Not support linker relaxation for RV64 with large code model.
1960
2
    SmallDataLimit = "0";
1961
2
    if (Args.hasArg(options::OPT_G)) {
1962
1
      D.Diag(diag::warn_drv_unsupported_sdata);
1963
1
    }
1964
304
  } else if (Arg *A = Args.getLastArg(options::OPT_G)) {
1965
8
    SmallDataLimit = A->getValue();
1966
8
  }
1967
  // Forward the -msmall-data-limit= option.
1968
309
  CmdArgs.push_back("-msmall-data-limit");
1969
309
  CmdArgs.push_back(SmallDataLimit);
1970
309
}
1971
1972
void Clang::AddRISCVTargetArgs(const ArgList &Args,
1973
309
                               ArgStringList &CmdArgs) const {
1974
309
  const llvm::Triple &Triple = getToolChain().getTriple();
1975
309
  StringRef ABIName = riscv::getRISCVABI(Args, Triple);
1976
309
1977
309
  CmdArgs.push_back("-target-abi");
1978
309
  CmdArgs.push_back(ABIName.data());
1979
309
1980
309
  SetRISCVSmallDataLimit(getToolChain(), Args, CmdArgs);
1981
309
}
1982
1983
void Clang::AddSparcTargetArgs(const ArgList &Args,
1984
168
                               ArgStringList &CmdArgs) const {
1985
168
  sparc::FloatABI FloatABI =
1986
168
      sparc::getSparcFloatABI(getToolChain().getDriver(), Args);
1987
168
1988
168
  if (FloatABI == sparc::FloatABI::Soft) {
1989
    // Floating point operations and argument passing are soft.
1990
4
    CmdArgs.push_back("-msoft-float");
1991
4
    CmdArgs.push_back("-mfloat-abi");
1992
4
    CmdArgs.push_back("soft");
1993
164
  } else {
1994
    // Floating point operations and argument passing are hard.
1995
164
    assert(FloatABI == sparc::FloatABI::Hard && "Invalid float abi!");
1996
164
    CmdArgs.push_back("-mfloat-abi");
1997
164
    CmdArgs.push_back("hard");
1998
164
  }
1999
168
}
2000
2001
void Clang::AddSystemZTargetArgs(const ArgList &Args,
2002
58
                                 ArgStringList &CmdArgs) const {
2003
58
  bool HasBackchain = Args.hasFlag(options::OPT_mbackchain,
2004
58
                                   options::OPT_mno_backchain, false);
2005
58
  bool HasPackedStack = Args.hasFlag(options::OPT_mpacked_stack,
2006
58
                                     options::OPT_mno_packed_stack, false);
2007
58
  systemz::FloatABI FloatABI =
2008
58
      systemz::getSystemZFloatABI(getToolChain().getDriver(), Args);
2009
58
  bool HasSoftFloat = (FloatABI == systemz::FloatABI::Soft);
2010
58
  if (HasBackchain && 
HasPackedStack3
&&
!HasSoftFloat2
) {
2011
1
    const Driver &D = getToolChain().getDriver();
2012
1
    D.Diag(diag::err_drv_unsupported_opt)
2013
1
      << "-mpacked-stack -mbackchain -mhard-float";
2014
1
  }
2015
58
  if (HasBackchain)
2016
3
    CmdArgs.push_back("-mbackchain");
2017
58
  if (HasPackedStack)
2018
2
    CmdArgs.push_back("-mpacked-stack");
2019
58
  if (HasSoftFloat) {
2020
    // Floating point operations and argument passing are soft.
2021
3
    CmdArgs.push_back("-msoft-float");
2022
3
    CmdArgs.push_back("-mfloat-abi");
2023
3
    CmdArgs.push_back("soft");
2024
3
  }
2025
58
}
2026
2027
void Clang::AddX86TargetArgs(const ArgList &Args,
2028
37.3k
                             ArgStringList &CmdArgs) const {
2029
37.3k
  const Driver &D = getToolChain().getDriver();
2030
37.3k
  addX86AlignBranchArgs(D, Args, CmdArgs, /*IsLTO=*/false);
2031
37.3k
2032
37.3k
  if (!Args.hasFlag(options::OPT_mred_zone, options::OPT_mno_red_zone, true) ||
2033
37.3k
      Args.hasArg(options::OPT_mkernel) ||
2034
37.3k
      Args.hasArg(options::OPT_fapple_kext))
2035
14
    CmdArgs.push_back("-disable-red-zone");
2036
37.3k
2037
37.3k
  if (!Args.hasFlag(options::OPT_mtls_direct_seg_refs,
2038
37.3k
                    options::OPT_mno_tls_direct_seg_refs, true))
2039
1
    CmdArgs.push_back("-mno-tls-direct-seg-refs");
2040
37.3k
2041
  // Default to avoid implicit floating-point for kernel/kext code, but allow
2042
  // that to be overridden with -mno-soft-float.
2043
37.3k
  bool NoImplicitFloat = (Args.hasArg(options::OPT_mkernel) ||
2044
37.3k
                          Args.hasArg(options::OPT_fapple_kext));
2045
37.3k
  if (Arg *A = Args.getLastArg(
2046
6
          options::OPT_msoft_float, options::OPT_mno_soft_float,
2047
6
          options::OPT_mimplicit_float, options::OPT_mno_implicit_float)) {
2048
6
    const Option &O = A->getOption();
2049
6
    NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
2050
5
                       O.matches(options::OPT_msoft_float));
2051
6
  }
2052
37.3k
  if (NoImplicitFloat)
2053
15
    CmdArgs.push_back("-no-implicit-float");
2054
37.3k
2055
37.3k
  if (Arg *A = Args.getLastArg(options::OPT_masm_EQ)) {
2056
3
    StringRef Value = A->getValue();
2057
3
    if (Value == "intel" || 
Value == "att"2
) {
2058
2
      CmdArgs.push_back("-mllvm");
2059
2
      CmdArgs.push_back(Args.MakeArgString("-x86-asm-syntax=" + Value));
2060
1
    } else {
2061
1
      D.Diag(diag::err_drv_unsupported_option_argument)
2062
1
          << A->getOption().getName() << Value;
2063
1
    }
2064
37.3k
  } else if (D.IsCLMode()) {
2065
532
    CmdArgs.push_back("-mllvm");
2066
532
    CmdArgs.push_back("-x86-asm-syntax=intel");
2067
532
  }
2068
37.3k
2069
  // Set flags to support MCU ABI.
2070
37.3k
  if (Args.hasFlag(options::OPT_miamcu, options::OPT_mno_iamcu, false)) {
2071
8
    CmdArgs.push_back("-mfloat-abi");
2072
8
    CmdArgs.push_back("soft");
2073
8
    CmdArgs.push_back("-mstack-alignment=4");
2074
8
  }
2075
37.3k
2076
  // Handle -mtune.
2077
37.3k
2078
  // Default to "generic" unless -march is present or targetting the PS4.
2079
37.3k
  std::string TuneCPU;
2080
37.3k
  if (!Args.hasArg(clang::driver::options::OPT_march_EQ) &&
2081
36.9k
      !getToolChain().getTriple().isPS4CPU())
2082
36.8k
    TuneCPU = "generic";
2083
37.3k
2084
  // Override based on -mtune.
2085
37.3k
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mtune_EQ)) {
2086
7
    StringRef Name = A->getValue();
2087
7
2088
7
    if (Name == "native") {
2089
0
      Name = llvm::sys::getHostCPUName();
2090
0
      if (!Name.empty())
2091
0
        TuneCPU = std::string(Name);
2092
0
    } else
2093
7
      TuneCPU = std::string(Name);
2094
7
  }
2095
37.3k
2096
37.3k
  if (!TuneCPU.empty()) {
2097
36.8k
    CmdArgs.push_back("-tune-cpu");
2098
36.8k
    CmdArgs.push_back(Args.MakeArgString(TuneCPU));
2099
36.8k
  }
2100
37.3k
}
2101
2102
void Clang::AddHexagonTargetArgs(const ArgList &Args,
2103
96
                                 ArgStringList &CmdArgs) const {
2104
96
  CmdArgs.push_back("-mqdsp6-compat");
2105
96
  CmdArgs.push_back("-Wreturn-type");
2106
96
2107
96
  if (auto G = toolchains::HexagonToolChain::getSmallDataThreshold(Args)) {
2108
9
    CmdArgs.push_back("-mllvm");
2109
9
    CmdArgs.push_back(Args.MakeArgString("-hexagon-small-data-threshold=" +
2110
9
                                         Twine(G.getValue())));
2111
9
  }
2112
96
2113
96
  if (!Args.hasArg(options::OPT_fno_short_enums))
2114
96
    CmdArgs.push_back("-fshort-enums");
2115
96
  if (Args.getLastArg(options::OPT_mieee_rnd_near)) {
2116
0
    CmdArgs.push_back("-mllvm");
2117
0
    CmdArgs.push_back("-enable-hexagon-ieee-rnd-near");
2118
0
  }
2119
96
  CmdArgs.push_back("-mllvm");
2120
96
  CmdArgs.push_back("-machine-sink-split=0");
2121
96
}
2122
2123
void Clang::AddLanaiTargetArgs(const ArgList &Args,
2124
2
                               ArgStringList &CmdArgs) const {
2125
2
  if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
2126
0
    StringRef CPUName = A->getValue();
2127
0
2128
0
    CmdArgs.push_back("-target-cpu");
2129
0
    CmdArgs.push_back(Args.MakeArgString(CPUName));
2130
0
  }
2131
2
  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
2132
0
    StringRef Value = A->getValue();
2133
    // Only support mregparm=4 to support old usage. Report error for all other
2134
    // cases.
2135
0
    int Mregparm;
2136
0
    if (Value.getAsInteger(10, Mregparm)) {
2137
0
      if (Mregparm != 4) {
2138
0
        getToolChain().getDriver().Diag(
2139
0
            diag::err_drv_unsupported_option_argument)
2140
0
            << A->getOption().getName() << Value;
2141
0
      }
2142
0
    }
2143
0
  }
2144
2
}
2145
2146
void Clang::AddWebAssemblyTargetArgs(const ArgList &Args,
2147
73
                                     ArgStringList &CmdArgs) const {
2148
  // Default to "hidden" visibility.
2149
73
  if (!Args.hasArg(options::OPT_fvisibility_EQ,
2150
71
                   options::OPT_fvisibility_ms_compat)) {
2151
71
    CmdArgs.push_back("-fvisibility");
2152
71
    CmdArgs.push_back("hidden");
2153
71
  }
2154
73
}
2155
2156
0
void Clang::AddVETargetArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
2157
  // Floating point operations and argument passing are hard.
2158
0
  CmdArgs.push_back("-mfloat-abi");
2159
0
  CmdArgs.push_back("hard");
2160
0
}
2161
2162
void Clang::DumpCompilationDatabase(Compilation &C, StringRef Filename,
2163
                                    StringRef Target, const InputInfo &Output,
2164
7
                                    const InputInfo &Input, const ArgList &Args) const {
2165
  // If this is a dry run, do not create the compilation database file.
2166
7
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2167
0
    return;
2168
7
2169
7
  using llvm::yaml::escape;
2170
7
  const Driver &D = getToolChain().getDriver();
2171
7
2172
7
  if (!CompilationDatabase) {
2173
3
    std::error_code EC;
2174
3
    auto File = std::make_unique<llvm::raw_fd_ostream>(Filename, EC,
2175
3
                                                        llvm::sys::fs::OF_Text);
2176
3
    if (EC) {
2177
1
      D.Diag(clang::diag::err_drv_compilationdatabase) << Filename
2178
1
                                                       << EC.message();
2179
1
      return;
2180
1
    }
2181
2
    CompilationDatabase = std::move(File);
2182
2
  }
2183
6
  auto &CDB = *CompilationDatabase;
2184
6
  auto CWD = D.getVFS().getCurrentWorkingDirectory();
2185
6
  if (!CWD)
2186
0
    CWD = ".";
2187
6
  CDB << "{ \"directory\": \"" << escape(*CWD) << "\"";
2188
6
  CDB << ", \"file\": \"" << escape(Input.getFilename()) << "\"";
2189
6
  CDB << ", \"output\": \"" << escape(Output.getFilename()) << "\"";
2190
6
  CDB << ", \"arguments\": [\"" << escape(D.ClangExecutable) << "\"";
2191
6
  SmallString<128> Buf;
2192
6
  Buf = "-x";
2193
6
  Buf += types::getTypeName(Input.getType());
2194
6
  CDB << ", \"" << escape(Buf) << "\"";
2195
6
  if (!D.SysRoot.empty() && 
!Args.hasArg(options::OPT__sysroot_EQ)2
) {
2196
0
    Buf = "--sysroot=";
2197
0
    Buf += D.SysRoot;
2198
0
    CDB << ", \"" << escape(Buf) << "\"";
2199
0
  }
2200
6
  CDB << ", \"" << escape(Input.getFilename()) << "\"";
2201
64
  for (auto &A: Args) {
2202
64
    auto &O = A->getOption();
2203
    // Skip language selection, which is positional.
2204
64
    if (O.getID() == options::OPT_x)
2205
4
      continue;
2206
    // Skip writing dependency output and the compilation database itself.
2207
60
    if (O.getGroup().isValid() && 
O.getGroup().getID() == options::OPT_M_Group27
)
2208
7
      continue;
2209
53
    if (O.getID() == options::OPT_gen_cdb_fragment_path)
2210
4
      continue;
2211
    // Skip inputs.
2212
49
    if (O.getKind() == Option::InputClass)
2213
8
      continue;
2214
    // All other arguments are quoted and appended.
2215
41
    ArgStringList ASL;
2216
41
    A->render(Args, ASL);
2217
41
    for (auto &it: ASL)
2218
46
      CDB << ", \"" << escape(it) << "\"";
2219
41
  }
2220
6
  Buf = "--target=";
2221
6
  Buf += Target;
2222
6
  CDB << ", \"" << escape(Buf) << "\"]},\n";
2223
6
}
2224
2225
void Clang::DumpCompilationDatabaseFragmentToDir(
2226
    StringRef Dir, Compilation &C, StringRef Target, const InputInfo &Output,
2227
4
    const InputInfo &Input, const llvm::opt::ArgList &Args) const {
2228
  // If this is a dry run, do not create the compilation database file.
2229
4
  if (C.getArgs().hasArg(options::OPT__HASH_HASH_HASH))
2230
1
    return;
2231
3
2232
3
  if (CompilationDatabase)
2233
0
    DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2234
3
2235
3
  SmallString<256> Path = Dir;
2236
3
  const auto &Driver = C.getDriver();
2237
3
  Driver.getVFS().makeAbsolute(Path);
2238
3
  auto Err = llvm::sys::fs::create_directory(Path, /*IgnoreExisting=*/true);
2239
3
  if (Err) {
2240
0
    Driver.Diag(diag::err_drv_compilationdatabase) << Dir << Err.message();
2241
0
    return;
2242
0
  }
2243
3
2244
3
  llvm::sys::path::append(
2245
3
      Path,
2246
3
      Twine(llvm::sys::path::filename(Input.getFilename())) + ".%%%%.json");
2247
3
  int FD;
2248
3
  SmallString<256> TempPath;
2249
3
  Err = llvm::sys::fs::createUniqueFile(Path, FD, TempPath);
2250
3
  if (Err) {
2251
0
    Driver.Diag(diag::err_drv_compilationdatabase) << Path << Err.message();
2252
0
    return;
2253
0
  }
2254
3
  CompilationDatabase =
2255
3
      std::make_unique<llvm::raw_fd_ostream>(FD, /*shouldClose=*/true);
2256
3
  DumpCompilationDatabase(C, "", Target, Output, Input, Args);
2257
3
}
2258
2259
static void CollectArgsForIntegratedAssembler(Compilation &C,
2260
                                              const ArgList &Args,
2261
                                              ArgStringList &CmdArgs,
2262
9.74k
                                              const Driver &D) {
2263
9.74k
  if (UseRelaxAll(C, Args))
2264
9.25k
    CmdArgs.push_back("-mrelax-all");
2265
9.74k
2266
  // Only default to -mincremental-linker-compatible if we think we are
2267
  // targeting the MSVC linker.
2268
9.74k
  bool DefaultIncrementalLinkerCompatible =
2269
9.74k
      C.getDefaultToolChain().getTriple().isWindowsMSVCEnvironment();
2270
9.74k
  if (Args.hasFlag(options::OPT_mincremental_linker_compatible,
2271
9.74k
                   options::OPT_mno_incremental_linker_compatible,
2272
9.74k
                   DefaultIncrementalLinkerCompatible))
2273
563
    CmdArgs.push_back("-mincremental-linker-compatible");
2274
9.74k
2275
9.74k
  switch (C.getDefaultToolChain().getArch()) {
2276
1.22k
  case llvm::Triple::arm:
2277
1.22k
  case llvm::Triple::armeb:
2278
1.22k
  case llvm::Triple::thumb:
2279
1.22k
  case llvm::Triple::thumbeb:
2280
1.22k
    if (Arg *A = Args.getLastArg(options::OPT_mimplicit_it_EQ)) {
2281
5
      StringRef Value = A->getValue();
2282
5
      if (Value == "always" || 
Value == "never"4
||
Value == "arm"3
||
2283
4
          
Value == "thumb"2
) {
2284
4
        CmdArgs.push_back("-mllvm");
2285
4
        CmdArgs.push_back(Args.MakeArgString("-arm-implicit-it=" + Value));
2286
1
      } else {
2287
1
        D.Diag(diag::err_drv_unsupported_option_argument)
2288
1
            << A->getOption().getName() << Value;
2289
1
      }
2290
5
    }
2291
1.22k
    break;
2292
8.51k
  default:
2293
8.51k
    break;
2294
9.74k
  }
2295
9.74k
2296
  // If you add more args here, also add them to the block below that
2297
  // starts with "// If CollectArgsForIntegratedAssembler() isn't called below".
2298
9.74k
2299
  // When passing -I arguments to the assembler we sometimes need to
2300
  // unconditionally take the next argument.  For example, when parsing
2301
  // '-Wa,-I -Wa,foo' we need to accept the -Wa,foo arg after seeing the
2302
  // -Wa,-I arg and when parsing '-Wa,-I,foo' we need to accept the 'foo'
2303
  // arg after parsing the '-I' arg.
2304
9.74k
  bool TakeNextArg = false;
2305
9.74k
2306
9.74k
  bool UseRelaxRelocations = C.getDefaultToolChain().useRelaxRelocations();
2307
9.74k
  bool UseNoExecStack = C.getDefaultToolChain().isNoExecStackDefault();
2308
9.74k
  const char *MipsTargetFeature = nullptr;
2309
9.74k
  for (const Arg *A :
2310
83
       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
2311
83
    A->claim();
2312
83
2313
94
    for (StringRef Value : A->getValues()) {
2314
94
      if (TakeNextArg) {
2315
7
        CmdArgs.push_back(Value.data());
2316
7
        TakeNextArg = false;
2317
7
        continue;
2318
7
      }
2319
87
2320
87
      if (C.getDefaultToolChain().getTriple().isOSBinFormatCOFF() &&
2321
2
          Value == "-mbig-obj")
2322
2
        continue; // LLVM handles bigobj automatically
2323
85
2324
85
      switch (C.getDefaultToolChain().getArch()) {
2325
38
      default:
2326
38
        break;
2327
15
      case llvm::Triple::thumb:
2328
15
      case llvm::Triple::thumbeb:
2329
15
      case llvm::Triple::arm:
2330
15
      case llvm::Triple::armeb:
2331
15
        if (Value == "-mthumb")
2332
          // -mthumb has already been processed in ComputeLLVMTriple()
2333
          // recognize but skip over here.
2334
3
          continue;
2335
12
        break;
2336
32
      case llvm::Triple::mips:
2337
32
      case llvm::Triple::mipsel:
2338
32
      case llvm::Triple::mips64:
2339
32
      case llvm::Triple::mips64el:
2340
32
        if (Value == "--trap") {
2341
3
          CmdArgs.push_back("-target-feature");
2342
3
          CmdArgs.push_back("+use-tcc-in-div");
2343
3
          continue;
2344
3
        }
2345
29
        if (Value == "--break") {
2346
3
          CmdArgs.push_back("-target-feature");
2347
3
          CmdArgs.push_back("-use-tcc-in-div");
2348
3
          continue;
2349
3
        }
2350
26
        if (Value.startswith("-msoft-float")) {
2351
3
          CmdArgs.push_back("-target-feature");
2352
3
          CmdArgs.push_back("+soft-float");
2353
3
          continue;
2354
3
        }
2355
23
        if (Value.startswith("-mhard-float")) {
2356
3
          CmdArgs.push_back("-target-feature");
2357
3
          CmdArgs.push_back("-soft-float");
2358
3
          continue;
2359
3
        }
2360
20
2361
20
        MipsTargetFeature = llvm::StringSwitch<const char *>(Value)
2362
20
                                .Case("-mips1", "+mips1")
2363
20
                                .Case("-mips2", "+mips2")
2364
20
                                .Case("-mips3", "+mips3")
2365
20
                                .Case("-mips4", "+mips4")
2366
20
                                .Case("-mips5", "+mips5")
2367
20
                                .Case("-mips32", "+mips32")
2368
20
                                .Case("-mips32r2", "+mips32r2")
2369
20
                                .Case("-mips32r3", "+mips32r3")
2370
20
                                .Case("-mips32r5", "+mips32r5")
2371
20
                                .Case("-mips32r6", "+mips32r6")
2372
20
                                .Case("-mips64", "+mips64")
2373
20
                                .Case("-mips64r2", "+mips64r2")
2374
20
                                .Case("-mips64r3", "+mips64r3")
2375
20
                                .Case("-mips64r5", "+mips64r5")
2376
20
                                .Case("-mips64r6", "+mips64r6")
2377
20
                                .Default(nullptr);
2378
20
        if (MipsTargetFeature)
2379
20
          continue;
2380
50
      }
2381
50
2382
50
      if (Value == "-force_cpusubtype_ALL") {
2383
        // Do nothing, this is the default and we don't support anything else.
2384
50
      } else if (Value == "-L") {
2385
1
        CmdArgs.push_back("-msave-temp-labels");
2386
49
      } else if (Value == "--fatal-warnings") {
2387
2
        CmdArgs.push_back("-massembler-fatal-warnings");
2388
47
      } else if (Value == "--no-warn" || Value == "-W") {
2389
0
        CmdArgs.push_back("-massembler-no-warn");
2390
47
      } else if (Value == "--noexecstack") {
2391
1
        UseNoExecStack = true;
2392
46
      } else if (Value.startswith("-compress-debug-sections") ||
2393
44
                 Value.startswith("--compress-debug-sections") ||
2394
40
                 Value == "-nocompress-debug-sections" ||
2395
40
                 Value == "--nocompress-debug-sections") {
2396
7
        CmdArgs.push_back(Value.data());
2397
39
      } else if (Value == "-mrelax-relocations=yes" ||
2398
37
                 Value == "--mrelax-relocations=yes") {
2399
4
        UseRelaxRelocations = true;
2400
35
      } else if (Value == "-mrelax-relocations=no" ||
2401
33
                 Value == "--mrelax-relocations=no") {
2402
2
        UseRelaxRelocations = false;
2403
33
      } else if (Value.startswith("-I")) {
2404
5
        CmdArgs.push_back(Value.data());
2405
        // We need to consume the next argument if the current arg is a plain
2406
        // -I. The next arg will be the include directory.
2407
5
        if (Value == "-I")
2408
3
          TakeNextArg = true;
2409
28
      } else if (Value.startswith("-gdwarf-")) {
2410
        // "-gdwarf-N" options are not cc1as options.
2411
3
        unsigned DwarfVersion = DwarfVersionNum(Value);
2412
3
        if (DwarfVersion == 0) { // Send it onward, and let cc1as complain.
2413
1
          CmdArgs.push_back(Value.data());
2414
2
        } else {
2415
2
          RenderDebugEnablingArgs(Args, CmdArgs,
2416
2
                                  codegenoptions::LimitedDebugInfo,
2417
2
                                  DwarfVersion, llvm::DebuggerKind::Default);
2418
2
        }
2419
25
      } else if (Value.startswith("-mcpu") || 
Value.startswith("-mfpu")22
||
2420
19
                 Value.startswith("-mhwdiv") || 
Value.startswith("-march")15
) {
2421
        // Do nothing, we'll validate it later.
2422
13
      } else if (Value == "-defsym") {
2423
7
          if (A->getNumValues() != 2) {
2424
2
            D.Diag(diag::err_drv_defsym_invalid_format) << Value;
2425
2
            break;
2426
2
          }
2427
5
          const char *S = A->getValue(1);
2428
5
          auto Pair = StringRef(S).split('=');
2429
5
          auto Sym = Pair.first;
2430
5
          auto SVal = Pair.second;
2431
5
2432
5
          if (Sym.empty() || 
SVal.empty()4
) {
2433
2
            D.Diag(diag::err_drv_defsym_invalid_format) << S;
2434
2
            break;
2435
2
          }
2436
3
          int64_t IVal;
2437
3
          if (SVal.getAsInteger(0, IVal)) {
2438
1
            D.Diag(diag::err_drv_defsym_invalid_symval) << SVal;
2439
1
            break;
2440
1
          }
2441
2
          CmdArgs.push_back(Value.data());
2442
2
          TakeNextArg = true;
2443
6
      } else if (Value == "-fdebug-compilation-dir") {
2444
2
        CmdArgs.push_back("-fdebug-compilation-dir");
2445
2
        TakeNextArg = true;
2446
4
      } else if (Value.consume_front("-fdebug-compilation-dir=")) {
2447
        // The flag is a -Wa / -Xassembler argument and Options doesn't
2448
        // parse the argument, so this isn't automatically aliased to
2449
        // -fdebug-compilation-dir (without '=') here.
2450
2
        CmdArgs.push_back("-fdebug-compilation-dir");
2451
2
        CmdArgs.push_back(Value.data());
2452
2
      } else {
2453
2
        D.Diag(diag::err_drv_unsupported_option_argument)
2454
2
            << A->getOption().getName() << Value;
2455
2
      }
2456
50
    }
2457
83
  }
2458
9.74k
  if (UseRelaxRelocations)
2459
9.74k
    CmdArgs.push_back("--mrelax-relocations");
2460
9.74k
  if (UseNoExecStack)
2461
195
    CmdArgs.push_back("-mnoexecstack");
2462
9.74k
  if (MipsTargetFeature != nullptr) {
2463
17
    CmdArgs.push_back("-target-feature");
2464
17
    CmdArgs.push_back(MipsTargetFeature);
2465
17
  }
2466
9.74k
2467
  // forward -fembed-bitcode to assmebler
2468
9.74k
  if (C.getDriver().embedBitcodeEnabled() ||
2469
9.72k
      C.getDriver().embedBitcodeMarkerOnly())
2470
17
    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
2471
9.74k
}
2472
2473
static void RenderFloatingPointOptions(const ToolChain &TC, const Driver &D,
2474
                                       bool OFastEnabled, const ArgList &Args,
2475
                                       ArgStringList &CmdArgs,
2476
42.7k
                                       const JobAction &JA) {
2477
  // Handle various floating point optimization flags, mapping them to the
2478
  // appropriate LLVM code generation flags. This is complicated by several
2479
  // "umbrella" flags, so we do this by stepping through the flags incrementally
2480
  // adjusting what we think is enabled/disabled, then at the end setting the
2481
  // LLVM flags based on the final state.
2482
42.7k
  bool HonorINFs = true;
2483
42.7k
  bool HonorNaNs = true;
2484
  // -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
2485
42.7k
  bool MathErrno = TC.IsMathErrnoDefault();
2486
42.7k
  bool AssociativeMath = false;
2487
42.7k
  bool ReciprocalMath = false;
2488
42.7k
  bool SignedZeros = true;
2489
42.7k
  bool TrappingMath = false; // Implemented via -ffp-exception-behavior
2490
42.7k
  bool TrappingMathPresent = false; // Is trapping-math in args, and not
2491
                                    // overriden by ffp-exception-behavior?
2492
42.7k
  bool RoundingFPMath = false;
2493
42.7k
  bool RoundingMathPresent = false; // Is rounding-math in args?
2494
  // -ffp-model values: strict, fast, precise
2495
42.7k
  StringRef FPModel = "";
2496
  // -ffp-exception-behavior options: strict, maytrap, ignore
2497
42.7k
  StringRef FPExceptionBehavior = "";
2498
42.7k
  const llvm::DenormalMode DefaultDenormalFPMath =
2499
42.7k
      TC.getDefaultDenormalModeForType(Args, JA);
2500
42.7k
  const llvm::DenormalMode DefaultDenormalFP32Math =
2501
42.7k
      TC.getDefaultDenormalModeForType(Args, JA, &llvm::APFloat::IEEEsingle());
2502
42.7k
2503
42.7k
  llvm::DenormalMode DenormalFPMath = DefaultDenormalFPMath;
2504
42.7k
  llvm::DenormalMode DenormalFP32Math = DefaultDenormalFP32Math;
2505
42.7k
  StringRef FPContract = "";
2506
42.7k
  bool StrictFPModel = false;
2507
42.7k
2508
42.7k
2509
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_flimited_precision_EQ)) {
2510
0
    CmdArgs.push_back("-mlimit-float-precision");
2511
0
    CmdArgs.push_back(A->getValue());
2512
0
  }
2513
42.7k
2514
784k
  for (const Arg *A : Args) {
2515
784k
    auto optID = A->getOption().getID();
2516
784k
    bool PreciseFPModel = false;
2517
784k
    switch (optID) {
2518
784k
    default:
2519
784k
      break;
2520
23
    case options::OPT_ffp_model_EQ: {
2521
      // If -ffp-model= is seen, reset to fno-fast-math
2522
23
      HonorINFs = true;
2523
23
      HonorNaNs = true;
2524
      // Turning *off* -ffast-math restores the toolchain default.
2525
23
      MathErrno = TC.IsMathErrnoDefault();
2526
23
      AssociativeMath = false;
2527
23
      ReciprocalMath = false;
2528
23
      SignedZeros = true;
2529
      // -fno_fast_math restores default denormal and fpcontract handling
2530
23
      FPContract = "";
2531
23
      DenormalFPMath = llvm::DenormalMode::getIEEE();
2532
23
2533
      // FIXME: The target may have picked a non-IEEE default mode here based on
2534
      // -cl-denorms-are-zero. Should the target consider -fp-model interaction?
2535
23
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
2536
23
2537
23
      StringRef Val = A->getValue();
2538
23
      if (OFastEnabled && 
!Val.equals("fast")1
) {
2539
          // Only -ffp-model=fast is compatible with OFast, ignore.
2540
1
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2541
1
          << Args.MakeArgString("-ffp-model=" + Val)
2542
1
          << "-Ofast";
2543
1
        break;
2544
1
      }
2545
22
      StrictFPModel = false;
2546
22
      PreciseFPModel = true;
2547
      // ffp-model= is a Driver option, it is entirely rewritten into more
2548
      // granular options before being passed into cc1.
2549
      // Use the gcc option in the switch below.
2550
22
      if (!FPModel.empty() && 
!FPModel.equals(Val)0
) {
2551
0
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2552
0
          << Args.MakeArgString("-ffp-model=" + FPModel)
2553
0
          << Args.MakeArgString("-ffp-model=" + Val);
2554
0
        FPContract = "";
2555
0
      }
2556
22
      if (Val.equals("fast")) {
2557
4
        optID = options::OPT_ffast_math;
2558
4
        FPModel = Val;
2559
4
        FPContract = "fast";
2560
18
      } else if (Val.equals("precise")) {
2561
2
        optID = options::OPT_ffp_contract;
2562
2
        FPModel = Val;
2563
2
        FPContract = "fast";
2564
2
        PreciseFPModel = true;
2565
16
      } else if (Val.equals("strict")) {
2566
15
        StrictFPModel = true;
2567
15
        optID = options::OPT_frounding_math;
2568
15
        FPExceptionBehavior = "strict";
2569
15
        FPModel = Val;
2570
15
        FPContract = "off";
2571
15
        TrappingMath = true;
2572
15
      } else
2573
1
        D.Diag(diag::err_drv_unsupported_option_argument)
2574
1
            << A->getOption().getName() << Val;
2575
22
      break;
2576
22
      }
2577
784k
    }
2578
784k
2579
784k
    switch (optID) {
2580
    // If this isn't an FP option skip the claim below
2581
783k
    default: continue;
2582
0
2583
    // Options controlling individual features
2584
3
    case options::OPT_fhonor_infinities:    HonorINFs = true;         break;
2585
7
    case options::OPT_fno_honor_infinities: HonorINFs = false;        break;
2586
3
    case options::OPT_fhonor_nans:          HonorNaNs = true;         break;
2587
8
    case options::OPT_fno_honor_nans:       HonorNaNs = false;        break;
2588
8
    case options::OPT_fmath_errno:          MathErrno = true;         break;
2589
14
    case options::OPT_fno_math_errno:       MathErrno = false;        break;
2590
11
    case options::OPT_fassociative_math:    AssociativeMath = true;   break;
2591
4
    case options::OPT_fno_associative_math: AssociativeMath = false;  break;
2592
14
    case options::OPT_freciprocal_math:     ReciprocalMath = true;    break;
2593
3
    case options::OPT_fno_reciprocal_math:  ReciprocalMath = false;   break;
2594
3
    case options::OPT_fsigned_zeros:        SignedZeros = true;       break;
2595
14
    case options::OPT_fno_signed_zeros:     SignedZeros = false;      break;
2596
8
    case options::OPT_ftrapping_math:
2597
8
      if (!TrappingMathPresent && 
!FPExceptionBehavior.empty()7
&&
2598
0
          !FPExceptionBehavior.equals("strict"))
2599
        // Warn that previous value of option is overridden.
2600
0
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2601
0
          << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2602
0
          << "-ftrapping-math";
2603
8
      TrappingMath = true;
2604
8
      TrappingMathPresent = true;
2605
8
      FPExceptionBehavior = "strict";
2606
8
      break;
2607
13
    case options::OPT_fno_trapping_math:
2608
13
      if (!TrappingMathPresent && 
!FPExceptionBehavior.empty()11
&&
2609
1
          !FPExceptionBehavior.equals("ignore"))
2610
        // Warn that previous value of option is overridden.
2611
1
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2612
1
          << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2613
1
          << "-fno-trapping-math";
2614
13
      TrappingMath = false;
2615
13
      TrappingMathPresent = true;
2616
13
      FPExceptionBehavior = "ignore";
2617
13
      break;
2618
0
2619
18
    case options::OPT_frounding_math:
2620
18
      RoundingFPMath = true;
2621
18
      RoundingMathPresent = true;
2622
18
      break;
2623
0
2624
4
    case options::OPT_fno_rounding_math:
2625
4
      RoundingFPMath = false;
2626
4
      RoundingMathPresent = false;
2627
4
      break;
2628
0
2629
10
    case options::OPT_fdenormal_fp_math_EQ:
2630
10
      DenormalFPMath = llvm::parseDenormalFPAttribute(A->getValue());
2631
10
      if (!DenormalFPMath.isValid()) {
2632
4
        D.Diag(diag::err_drv_invalid_value)
2633
4
            << A->getAsString(Args) << A->getValue();
2634
4
      }
2635
10
      break;
2636
0
2637
0
    case options::OPT_fdenormal_fp_math_f32_EQ:
2638
0
      DenormalFP32Math = llvm::parseDenormalFPAttribute(A->getValue());
2639
0
      if (!DenormalFP32Math.isValid()) {
2640
0
        D.Diag(diag::err_drv_invalid_value)
2641
0
            << A->getAsString(Args) << A->getValue();
2642
0
      }
2643
0
      break;
2644
0
2645
    // Validate and pass through -ffp-contract option.
2646
11
    case options::OPT_ffp_contract: {
2647
11
      StringRef Val = A->getValue();
2648
11
      if (PreciseFPModel) {
2649
        // -ffp-model=precise enables ffp-contract=fast as a side effect
2650
        // the FPContract value has already been set to a string literal
2651
        // and the Val string isn't a pertinent value.
2652
2
        ;
2653
9
      } else if (Val.equals("fast") || 
Val.equals("on")5
||
Val.equals("off")3
)
2654
9
        FPContract = Val;
2655
0
      else
2656
0
        D.Diag(diag::err_drv_unsupported_option_argument)
2657
0
           << A->getOption().getName() << Val;
2658
11
      break;
2659
0
    }
2660
0
2661
    // Validate and pass through -ffp-model option.
2662
2
    case options::OPT_ffp_model_EQ:
2663
      // This should only occur in the error case
2664
      // since the optID has been replaced by a more granular
2665
      // floating point option.
2666
2
      break;
2667
0
2668
    // Validate and pass through -ffp-exception-behavior option.
2669
8
    case options::OPT_ffp_exception_behavior_EQ: {
2670
8
      StringRef Val = A->getValue();
2671
8
      if (!TrappingMathPresent && 
!FPExceptionBehavior.empty()7
&&
2672
0
          !FPExceptionBehavior.equals(Val))
2673
        // Warn that previous value of option is overridden.
2674
0
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2675
0
          << Args.MakeArgString("-ffp-exception-behavior=" + FPExceptionBehavior)
2676
0
          << Args.MakeArgString("-ffp-exception-behavior=" + Val);
2677
8
      TrappingMath = TrappingMathPresent = false;
2678
8
      if (Val.equals("ignore") || 
Val.equals("maytrap")5
)
2679
5
        FPExceptionBehavior = Val;
2680
3
      else if (Val.equals("strict")) {
2681
2
        FPExceptionBehavior = Val;
2682
2
        TrappingMath = TrappingMathPresent = true;
2683
2
      } else
2684
1
        D.Diag(diag::err_drv_unsupported_option_argument)
2685
1
            << A->getOption().getName() << Val;
2686
8
      break;
2687
0
    }
2688
0
2689
8
    case options::OPT_ffinite_math_only:
2690
8
      HonorINFs = false;
2691
8
      HonorNaNs = false;
2692
8
      break;
2693
6
    case options::OPT_fno_finite_math_only:
2694
6
      HonorINFs = true;
2695
6
      HonorNaNs = true;
2696
6
      break;
2697
0
2698
9
    case options::OPT_funsafe_math_optimizations:
2699
9
      AssociativeMath = true;
2700
9
      ReciprocalMath = true;
2701
9
      SignedZeros = false;
2702
9
      TrappingMath = false;
2703
9
      FPExceptionBehavior = "";
2704
9
      break;
2705
6
    case options::OPT_fno_unsafe_math_optimizations:
2706
6
      AssociativeMath = false;
2707
6
      ReciprocalMath = false;
2708
6
      SignedZeros = true;
2709
6
      TrappingMath = true;
2710
6
      FPExceptionBehavior = "strict";
2711
6
2712
      // The target may have opted to flush by default, so force IEEE.
2713
6
      DenormalFPMath = llvm::DenormalMode::getIEEE();
2714
6
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
2715
6
      break;
2716
0
2717
27
    case options::OPT_Ofast:
2718
      // If -Ofast is the optimization level, then -ffast-math should be enabled
2719
27
      if (!OFastEnabled)
2720
2
        continue;
2721
25
      LLVM_FALLTHROUGH;
2722
68
    case options::OPT_ffast_math:
2723
68
      HonorINFs = false;
2724
68
      HonorNaNs = false;
2725
68
      MathErrno = false;
2726
68
      AssociativeMath = true;
2727
68
      ReciprocalMath = true;
2728
68
      SignedZeros = false;
2729
68
      TrappingMath = false;
2730
68
      RoundingFPMath = false;
2731
      // If fast-math is set then set the fp-contract mode to fast.
2732
68
      FPContract = "fast";
2733
68
      break;
2734
31
    case options::OPT_fno_fast_math:
2735
31
      HonorINFs = true;
2736
31
      HonorNaNs = true;
2737
      // Turning on -ffast-math (with either flag) removes the need for
2738
      // MathErrno. However, turning *off* -ffast-math merely restores the
2739
      // toolchain default (which may be false).
2740
31
      MathErrno = TC.IsMathErrnoDefault();
2741
31
      AssociativeMath = false;
2742
31
      ReciprocalMath = false;
2743
31
      SignedZeros = true;
2744
31
      TrappingMath = false;
2745
31
      RoundingFPMath = false;
2746
      // -fno_fast_math restores default denormal and fpcontract handling
2747
31
      DenormalFPMath = DefaultDenormalFPMath;
2748
31
      DenormalFP32Math = llvm::DenormalMode::getIEEE();
2749
31
      FPContract = "";
2750
31
      break;
2751
294
    }
2752
294
    if (StrictFPModel) {
2753
      // If -ffp-model=strict has been specified on command line but
2754
      // subsequent options conflict then emit warning diagnostic.
2755
28
      if (HonorINFs && 
HonorNaNs25
&&
2756
24
        !AssociativeMath && 
!ReciprocalMath22
&&
2757
21
        SignedZeros && 
TrappingMath20
&&
RoundingFPMath19
&&
2758
18
        (FPContract.equals("off") || 
FPContract.empty()2
) &&
2759
16
        DenormalFPMath == llvm::DenormalMode::getIEEE() &&
2760
15
        DenormalFP32Math == llvm::DenormalMode::getIEEE())
2761
        // OK: Current Arg doesn't conflict with -ffp-model=strict
2762
15
        ;
2763
13
      else {
2764
13
        StrictFPModel = false;
2765
13
        FPModel = "";
2766
13
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2767
13
            << "-ffp-model=strict" <<
2768
10
            ((A->getNumValues() == 0) ?  A->getSpelling()
2769
3
            : Args.MakeArgString(A->getSpelling() + A->getValue()));
2770
13
      }
2771
28
    }
2772
294
2773
    // If we handled this option claim it
2774
294
    A->claim();
2775
294
  }
2776
42.7k
2777
42.7k
  if (!HonorINFs)
2778
68
    CmdArgs.push_back("-menable-no-infs");
2779
42.7k
2780
42.7k
  if (!HonorNaNs)
2781
69
    CmdArgs.push_back("-menable-no-nans");
2782
42.7k
2783
42.7k
  if (MathErrno)
2784
23.1k
    CmdArgs.push_back("-fmath-errno");
2785
42.7k
2786
42.7k
  if (!MathErrno && 
AssociativeMath19.5k
&&
ReciprocalMath70
&&
!SignedZeros66
&&
2787
63
      !TrappingMath)
2788
59
    CmdArgs.push_back("-menable-unsafe-fp-math");
2789
42.7k
2790
42.7k
  if (!SignedZeros)
2791
77
    CmdArgs.push_back("-fno-signed-zeros");
2792
42.7k
2793
42.7k
  if (AssociativeMath && 
!SignedZeros73
&&
!TrappingMath69
)
2794
65
    CmdArgs.push_back("-mreassociate");
2795
42.7k
2796
42.7k
  if (ReciprocalMath)
2797
76
    CmdArgs.push_back("-freciprocal-math");
2798
42.7k
2799
42.7k
  if (TrappingMath) {
2800
    // FP Exception Behavior is also set to strict
2801
24
    assert(FPExceptionBehavior.equals("strict"));
2802
24
    CmdArgs.push_back("-ftrapping-math");
2803
42.7k
  } else if (TrappingMathPresent)
2804
12
    CmdArgs.push_back("-fno-trapping-math");
2805
42.7k
2806
  // The default is IEEE.
2807
42.7k
  if (DenormalFPMath != llvm::DenormalMode::getIEEE()) {
2808
143
    llvm::SmallString<64> DenormFlag;
2809
143
    llvm::raw_svector_ostream ArgStr(DenormFlag);
2810
143
    ArgStr << "-fdenormal-fp-math=" << DenormalFPMath;
2811
143
    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2812
143
  }
2813
42.7k
2814
  // Add f32 specific denormal mode flag if it's different.
2815
42.7k
  if (DenormalFP32Math != DenormalFPMath) {
2816
109
    llvm::SmallString<64> DenormFlag;
2817
109
    llvm::raw_svector_ostream ArgStr(DenormFlag);
2818
109
    ArgStr << "-fdenormal-fp-math-f32=" << DenormalFP32Math;
2819
109
    CmdArgs.push_back(Args.MakeArgString(ArgStr.str()));
2820
109
  }
2821
42.7k
2822
42.7k
  if (!FPContract.empty())
2823
83
    CmdArgs.push_back(Args.MakeArgString("-ffp-contract=" + FPContract));
2824
42.7k
2825
42.7k
  if (!RoundingFPMath)
2826
42.7k
    CmdArgs.push_back(Args.MakeArgString("-fno-rounding-math"));
2827
42.7k
2828
42.7k
  if (RoundingFPMath && 
RoundingMathPresent15
)
2829
15
    CmdArgs.push_back(Args.MakeArgString("-frounding-math"));
2830
42.7k
2831
42.7k
  if (!FPExceptionBehavior.empty())
2832
43
    CmdArgs.push_back(Args.MakeArgString("-ffp-exception-behavior=" +
2833
43
                      FPExceptionBehavior));
2834
42.7k
2835
42.7k
  ParseMRecip(D, Args, CmdArgs);
2836
42.7k
2837
  // -ffast-math enables the __FAST_MATH__ preprocessor macro, but check for the
2838
  // individual features enabled by -ffast-math instead of the option itself as
2839
  // that's consistent with gcc's behaviour.
2840
42.7k
  if (!HonorINFs && 
!HonorNaNs68
&&
!MathErrno62
&&
AssociativeMath60
&&
2841
52
      ReciprocalMath && 
!SignedZeros51
&&
!TrappingMath50
&&
!RoundingFPMath48
) {
2842
48
    CmdArgs.push_back("-ffast-math");
2843
48
    if (FPModel.equals("fast")) {
2844
4
      if (FPContract.equals("fast"))
2845
        // All set, do nothing.
2846
2
        ;
2847
2
      else if (FPContract.empty())
2848
        // Enable -ffp-contract=fast
2849
0
        CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
2850
2
      else
2851
2
        D.Diag(clang::diag::warn_drv_overriding_flag_option)
2852
2
          << "-ffp-model=fast"
2853
2
          << Args.MakeArgString("-ffp-contract=" + FPContract);
2854
4
    }
2855
48
  }
2856
42.7k
2857
  // Handle __FINITE_MATH_ONLY__ similarly.
2858
42.7k
  if (!HonorINFs && 
!HonorNaNs68
)
2859
62
    CmdArgs.push_back("-ffinite-math-only");
2860
42.7k
2861
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_mfpmath_EQ)) {
2862
0
    CmdArgs.push_back("-mfpmath");
2863
0
    CmdArgs.push_back(A->getValue());
2864
0
  }
2865
42.7k
2866
  // Disable a codegen optimization for floating-point casts.
2867
42.7k
  if (Args.hasFlag(options::OPT_fno_strict_float_cast_overflow,
2868
42.7k
                   options::OPT_fstrict_float_cast_overflow, false))
2869
1
    CmdArgs.push_back("-fno-strict-float-cast-overflow");
2870
42.7k
}
2871
2872
static void RenderAnalyzerOptions(const ArgList &Args, ArgStringList &CmdArgs,
2873
                                  const llvm::Triple &Triple,
2874
41
                                  const InputInfo &Input) {
2875
  // Enable region store model by default.
2876
41
  CmdArgs.push_back("-analyzer-store=region");
2877
41
2878
  // Treat blocks as analysis entry points.
2879
41
  CmdArgs.push_back("-analyzer-opt-analyze-nested-blocks");
2880
41
2881
  // Add default argument set.
2882
41
  if (!Args.hasArg(options::OPT__analyzer_no_default_checks)) {
2883
41
    CmdArgs.push_back("-analyzer-checker=core");
2884
41
    CmdArgs.push_back("-analyzer-checker=apiModeling");
2885
41
2886
41
    if (!Triple.isWindowsMSVCEnvironment()) {
2887
40
      CmdArgs.push_back("-analyzer-checker=unix");
2888
1
    } else {
2889
      // Enable "unix" checkers that also work on Windows.
2890
1
      CmdArgs.push_back("-analyzer-checker=unix.API");
2891
1
      CmdArgs.push_back("-analyzer-checker=unix.Malloc");
2892
1
      CmdArgs.push_back("-analyzer-checker=unix.MallocSizeof");
2893
1
      CmdArgs.push_back("-analyzer-checker=unix.MismatchedDeallocator");
2894
1
      CmdArgs.push_back("-analyzer-checker=unix.cstring.BadSizeArg");
2895
1
      CmdArgs.push_back("-analyzer-checker=unix.cstring.NullArg");
2896
1
    }
2897
41
2898
    // Disable some unix checkers for PS4.
2899
41
    if (Triple.isPS4CPU()) {
2900
3
      CmdArgs.push_back("-analyzer-disable-checker=unix.API");
2901
3
      CmdArgs.push_back("-analyzer-disable-checker=unix.Vfork");
2902
3
    }
2903
41
2904
41
    if (Triple.isOSDarwin()) {
2905
34
      CmdArgs.push_back("-analyzer-checker=osx");
2906
34
      CmdArgs.push_back(
2907
34
          "-analyzer-checker=security.insecureAPI.decodeValueOfObjCType");
2908
34
    }
2909
7
    else if (Triple.isOSFuchsia())
2910
0
      CmdArgs.push_back("-analyzer-checker=fuchsia");
2911
41
2912
41
    CmdArgs.push_back("-analyzer-checker=deadcode");
2913
41
2914
41
    if (types::isCXX(Input.getType()))
2915
15
      CmdArgs.push_back("-analyzer-checker=cplusplus");
2916
41
2917
41
    if (!Triple.isPS4CPU()) {
2918
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
2919
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
2920
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.gets");
2921
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mktemp");
2922
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.mkstemp");
2923
38
      CmdArgs.push_back("-analyzer-checker=security.insecureAPI.vfork");
2924
38
    }
2925
41
2926
    // Default nullability checks.
2927
41
    CmdArgs.push_back("-analyzer-checker=nullability.NullPassedToNonnull");
2928
41
    CmdArgs.push_back("-analyzer-checker=nullability.NullReturnedFromNonnull");
2929
41
  }
2930
41
2931
  // Set the output format. The default is plist, for (lame) historical reasons.
2932
41
  CmdArgs.push_back("-analyzer-output");
2933
41
  if (Arg *A = Args.getLastArg(options::OPT__analyzer_output))
2934
0
    CmdArgs.push_back(A->getValue());
2935
41
  else
2936
41
    CmdArgs.push_back("plist");
2937
41
2938
  // Disable the presentation of standard compiler warnings when using
2939
  // --analyze.  We only want to show static analyzer diagnostics or frontend
2940
  // errors.
2941
41
  CmdArgs.push_back("-w");
2942
41
2943
  // Add -Xanalyzer arguments when running as analyzer.
2944
41
  Args.AddAllArgValues(CmdArgs, options::OPT_Xanalyzer);
2945
41
}
2946
2947
static void RenderSSPOptions(const ToolChain &TC, const ArgList &Args,
2948
42.7k
                             ArgStringList &CmdArgs, bool KernelOrKext) {
2949
42.7k
  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2950
42.7k
2951
  // NVPTX doesn't support stack protectors; from the compiler's perspective, it
2952
  // doesn't even have a stack!
2953
42.7k
  if (EffectiveTriple.isNVPTX())
2954
333
    return;
2955
42.4k
2956
  // -stack-protector=0 is default.
2957
42.4k
  unsigned StackProtectorLevel = 0;
2958
42.4k
  unsigned DefaultStackProtectorLevel =
2959
42.4k
      TC.GetDefaultStackProtectorLevel(KernelOrKext);
2960
42.4k
2961
42.4k
  if (Arg *A = Args.getLastArg(options::OPT_fno_stack_protector,
2962
15
                               options::OPT_fstack_protector_all,
2963
15
                               options::OPT_fstack_protector_strong,
2964
15
                               options::OPT_fstack_protector)) {
2965
15
    if (A->getOption().matches(options::OPT_fstack_protector))
2966
9
      StackProtectorLevel =
2967
9
          std::max<unsigned>(LangOptions::SSPOn, DefaultStackProtectorLevel);
2968
6
    else if (A->getOption().matches(options::OPT_fstack_protector_strong))
2969
2
      StackProtectorLevel = LangOptions::SSPStrong;
2970
4
    else if (A->getOption().matches(options::OPT_fstack_protector_all))
2971
3
      StackProtectorLevel = LangOptions::SSPReq;
2972
42.4k
  } else {
2973
42.4k
    StackProtectorLevel = DefaultStackProtectorLevel;
2974
42.4k
  }
2975
42.4k
2976
42.4k
  if (StackProtectorLevel) {
2977
18.2k
    CmdArgs.push_back("-stack-protector");
2978
18.2k
    CmdArgs.push_back(Args.MakeArgString(Twine(StackProtectorLevel)));
2979
18.2k
  }
2980
42.4k
2981
  // --param ssp-buffer-size=
2982
5
  for (const Arg *A : Args.filtered(options::OPT__param)) {
2983
5
    StringRef Str(A->getValue());
2984
5
    if (Str.startswith("ssp-buffer-size=")) {
2985
2
      if (StackProtectorLevel) {
2986
2
        CmdArgs.push_back("-stack-protector-buffer-size");
2987
        // FIXME: Verify the argument is a valid integer.
2988
2
        CmdArgs.push_back(Args.MakeArgString(Str.drop_front(16)));
2989
2
      }
2990
2
      A->claim();
2991
2
    }
2992
5
  }
2993
42.4k
}
2994
2995
static void RenderSCPOptions(const ToolChain &TC, const ArgList &Args,
2996
42.7k
                             ArgStringList &CmdArgs) {
2997
42.7k
  const llvm::Triple &EffectiveTriple = TC.getEffectiveTriple();
2998
42.7k
2999
42.7k
  if (!EffectiveTriple.isOSLinux())
3000
38.6k
    return;
3001
4.16k
3002
4.16k
  if (!EffectiveTriple.isX86() && 
!EffectiveTriple.isSystemZ()1.76k
&&
3003
1.72k
      !EffectiveTriple.isPPC64())
3004
1.47k
    return;
3005
2.68k
3006
2.68k
  if (Args.hasFlag(options::OPT_fstack_clash_protection,
3007
2.68k
                   options::OPT_fno_stack_clash_protection, false))
3008
7
    CmdArgs.push_back("-fstack-clash-protection");
3009
2.68k
}
3010
3011
static void RenderTrivialAutoVarInitOptions(const Driver &D,
3012
                                            const ToolChain &TC,
3013
                                            const ArgList &Args,
3014
42.7k
                                            ArgStringList &CmdArgs) {
3015
42.7k
  auto DefaultTrivialAutoVarInit = TC.GetDefaultTrivialAutoVarInit();
3016
42.7k
  StringRef TrivialAutoVarInit = "";
3017
42.7k
3018
784k
  for (const Arg *A : Args) {
3019
784k
    switch (A->getOption().getID()) {
3020
784k
    default:
3021
784k
      continue;
3022
8
    case options::OPT_ftrivial_auto_var_init: {
3023
8
      A->claim();
3024
8
      StringRef Val = A->getValue();
3025
8
      if (Val == "uninitialized" || 
Val == "zero"7
||
Val == "pattern"3
)
3026
8
        TrivialAutoVarInit = Val;
3027
0
      else
3028
0
        D.Diag(diag::err_drv_unsupported_option_argument)
3029
0
            << A->getOption().getName() << Val;
3030
8
      break;
3031
0
    }
3032
784k
    }
3033
784k
  }
3034
42.7k
3035
42.7k
  if (TrivialAutoVarInit.empty())
3036
42.7k
    switch (DefaultTrivialAutoVarInit) {
3037
42.7k
    case LangOptions::TrivialAutoVarInitKind::Uninitialized:
3038
42.7k
      break;
3039
0
    case LangOptions::TrivialAutoVarInitKind::Pattern:
3040
0
      TrivialAutoVarInit = "pattern";
3041
0
      break;
3042
0
    case LangOptions::TrivialAutoVarInitKind::Zero:
3043
0
      TrivialAutoVarInit = "zero";
3044
0
      break;
3045
42.7k
    }
3046
42.7k
3047
42.7k
  if (!TrivialAutoVarInit.empty()) {
3048
8
    if (TrivialAutoVarInit == "zero" && 
!Args.hasArg(options::OPT_enable_trivial_var_init_zero)4
)
3049
1
      D.Diag(diag::err_drv_trivial_auto_var_init_zero_disabled);
3050
8
    CmdArgs.push_back(
3051
8
        Args.MakeArgString("-ftrivial-auto-var-init=" + TrivialAutoVarInit));
3052
8
  }
3053
42.7k
3054
42.7k
  if (Arg *A =
3055
5
          Args.getLastArg(options::OPT_ftrivial_auto_var_init_stop_after)) {
3056
5
    if (!Args.hasArg(options::OPT_ftrivial_auto_var_init) ||
3057
4
        StringRef(
3058
4
            Args.getLastArg(options::OPT_ftrivial_auto_var_init)->getValue()) ==
3059
4
            "uninitialized")
3060
1
      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_missing_dependency);
3061
5
    A->claim();
3062
5
    StringRef Val = A->getValue();
3063
5
    if (std::stoi(Val.str()) <= 0)
3064
3
      D.Diag(diag::err_drv_trivial_auto_var_init_stop_after_invalid_value);
3065
5
    CmdArgs.push_back(
3066
5
        Args.MakeArgString("-ftrivial-auto-var-init-stop-after=" + Val));
3067
5
  }
3068
42.7k
}
3069
3070
42.7k
static void RenderOpenCLOptions(const ArgList &Args, ArgStringList &CmdArgs) {
3071
  // cl-denorms-are-zero is not forwarded. It is translated into a generic flag
3072
  // for denormal flushing handling based on the target.
3073
42.7k
  const unsigned ForwardedArguments[] = {
3074
42.7k
      options::OPT_cl_opt_disable,
3075
42.7k
      options::OPT_cl_strict_aliasing,
3076
42.7k
      options::OPT_cl_single_precision_constant,
3077
42.7k
      options::OPT_cl_finite_math_only,
3078
42.7k
      options::OPT_cl_kernel_arg_info,
3079
42.7k
      options::OPT_cl_unsafe_math_optimizations,
3080
42.7k
      options::OPT_cl_fast_relaxed_math,
3081
42.7k
      options::OPT_cl_mad_enable,
3082
42.7k
      options::OPT_cl_no_signed_zeros,
3083
42.7k
      options::OPT_cl_fp32_correctly_rounded_divide_sqrt,
3084
42.7k
      options::OPT_cl_uniform_work_group_size
3085
42.7k
  };
3086
42.7k
3087
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_cl_std_EQ)) {
3088
13
    std::string CLStdStr = std::string("-cl-std=") + A->getValue();
3089
13
    CmdArgs.push_back(Args.MakeArgString(CLStdStr));
3090
13
  }
3091
42.7k
3092
42.7k
  for (const auto &Arg : ForwardedArguments)
3093
470k
    if (const auto *A = Args.getLastArg(Arg))
3094
16
      CmdArgs.push_back(Args.MakeArgString(A->getOption().getPrefixedName()));
3095
42.7k
}
3096
3097
static void RenderARCMigrateToolOptions(const Driver &D, const ArgList &Args,
3098
42.7k
                                        ArgStringList &CmdArgs) {
3099
42.7k
  bool ARCMTEnabled = false;
3100
42.7k
  if (!Args.hasArg(options::OPT_fno_objc_arc, options::OPT_fobjc_arc)) {
3101
41.4k
    if (const Arg *A = Args.getLastArg(options::OPT_ccc_arcmt_check,
3102
1
                                       options::OPT_ccc_arcmt_modify,
3103
1
                                       options::OPT_ccc_arcmt_migrate)) {
3104
1
      ARCMTEnabled = true;
3105
1
      switch (A->getOption().getID()) {
3106
0
      default: llvm_unreachable("missed a case");
3107
0
      case options::OPT_ccc_arcmt_check:
3108
0
        CmdArgs.push_back("-arcmt-check");
3109
0
        break;
3110
0
      case options::OPT_ccc_arcmt_modify:
3111
0
        CmdArgs.push_back("-arcmt-modify");
3112
0
        break;
3113
1
      case options::OPT_ccc_arcmt_migrate:
3114
1
        CmdArgs.push_back("-arcmt-migrate");
3115
1
        CmdArgs.push_back("-mt-migrate-directory");
3116
1
        CmdArgs.push_back(A->getValue());
3117
1
3118
1
        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_report_output);
3119
1
        Args.AddLastArg(CmdArgs, options::OPT_arcmt_migrate_emit_arc_errors);
3120
1
        break;
3121
1.27k
      }
3122
1.27k
    }
3123
1.27k
  } else {
3124
1.27k
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_check);
3125
1.27k
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_modify);
3126
1.27k
    Args.ClaimAllArgs(options::OPT_ccc_arcmt_migrate);
3127
1.27k
  }
3128
42.7k
3129
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_ccc_objcmt_migrate)) {
3130
0
    if (ARCMTEnabled)
3131
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
3132
0
          << A->getAsString(Args) << "-ccc-arcmt-migrate";
3133
0
3134
0
    CmdArgs.push_back("-mt-migrate-directory");
3135
0
    CmdArgs.push_back(A->getValue());
3136
0
3137
0
    if (!Args.hasArg(options::OPT_objcmt_migrate_literals,
3138
0
                     options::OPT_objcmt_migrate_subscripting,
3139
0
                     options::OPT_objcmt_migrate_property)) {
3140
      // None specified, means enable them all.
3141
0
      CmdArgs.push_back("-objcmt-migrate-literals");
3142
0
      CmdArgs.push_back("-objcmt-migrate-subscripting");
3143
0
      CmdArgs.push_back("-objcmt-migrate-property");
3144
0
    } else {
3145
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3146
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3147
0
      Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3148
0
    }
3149
42.7k
  } else {
3150
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_literals);
3151
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_subscripting);
3152
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property);
3153
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_all);
3154
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readonly_property);
3155
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_readwrite_property);
3156
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_property_dot_syntax);
3157
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_annotation);
3158
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_instancetype);
3159
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_nsmacros);
3160
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_protocol_conformance);
3161
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_atomic_property);
3162
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_returns_innerpointer_property);
3163
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_ns_nonatomic_iosonly);
3164
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_migrate_designated_init);
3165
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_objcmt_whitelist_dir_path);
3166
42.7k
  }
3167
42.7k
}
3168
3169
static void RenderBuiltinOptions(const ToolChain &TC, const llvm::Triple &T,
3170
42.7k
                                 const ArgList &Args, ArgStringList &CmdArgs) {
3171
  // -fbuiltin is default unless -mkernel is used.
3172
42.7k
  bool UseBuiltins =
3173
42.7k
      Args.hasFlag(options::OPT_fbuiltin, options::OPT_fno_builtin,
3174
42.7k
                   !Args.hasArg(options::OPT_mkernel));
3175
42.7k
  if (!UseBuiltins)
3176
5.78k
    CmdArgs.push_back("-fno-builtin");
3177
42.7k
3178
  // -ffreestanding implies -fno-builtin.
3179
42.7k
  if (Args.hasArg(options::OPT_ffreestanding))
3180
51
    UseBuiltins = false;
3181
42.7k
3182
  // Process the -fno-builtin-* options.
3183
784k
  for (const auto &Arg : Args) {
3184
784k
    const Option &O = Arg->getOption();
3185
784k
    if (!O.matches(options::OPT_fno_builtin_))
3186
784k
      continue;
3187
5
3188
5
    Arg->claim();
3189
5
3190
    // If -fno-builtin is specified, then there's no need to pass the option to
3191
    // the frontend.
3192
5
    if (!UseBuiltins)
3193
3
      continue;
3194
2
3195
2
    StringRef FuncName = Arg->getValue();
3196
2
    CmdArgs.push_back(Args.MakeArgString("-fno-builtin-" + FuncName));
3197
2
  }
3198
42.7k
3199
  // le32-specific flags:
3200
  //  -fno-math-builtin: clang should not convert math builtins to intrinsics
3201
  //                     by default.
3202
42.7k
  if (TC.getArch() == llvm::Triple::le32)
3203
5
    CmdArgs.push_back("-fno-math-builtin");
3204
42.7k
}
3205
3206
3.07k
bool Driver::getDefaultModuleCachePath(SmallVectorImpl<char> &Result) {
3207
3.07k
  if (llvm::sys::path::cache_directory(Result)) {
3208
3.07k
    llvm::sys::path::append(Result, "clang");
3209
3.07k
    llvm::sys::path::append(Result, "ModuleCache");
3210
3.07k
    return true;
3211
3.07k
  }
3212
0
  return false;
3213
0
}
3214
3215
static void RenderModulesOptions(Compilation &C, const Driver &D,
3216
                                 const ArgList &Args, const InputInfo &Input,
3217
                                 const InputInfo &Output,
3218
42.7k
                                 ArgStringList &CmdArgs, bool &HaveModules) {
3219
  // -fmodules enables the use of precompiled modules (off by default).
3220
  // Users can pass -fno-cxx-modules to turn off modules support for
3221
  // C++/Objective-C++ programs.
3222
42.7k
  bool HaveClangModules = false;
3223
42.7k
  if (Args.hasFlag(options::OPT_fmodules, options::OPT_fno_modules, false)) {
3224
2.95k
    bool AllowedInCXX = Args.hasFlag(options::OPT_fcxx_modules,
3225
2.95k
                                     options::OPT_fno_cxx_modules, true);
3226
2.95k
    if (AllowedInCXX || 
!types::isCXX(Input.getType())1
) {
3227
2.95k
      CmdArgs.push_back("-fmodules");
3228
2.95k
      HaveClangModules = true;
3229
2.95k
    }
3230
2.95k
  }
3231
42.7k
3232
42.7k
  HaveModules |= HaveClangModules;
3233
42.7k
  if (Args.hasArg(options::OPT_fmodules_ts)) {
3234
8
    CmdArgs.push_back("-fmodules-ts");
3235
8
    HaveModules = true;
3236
8
  }
3237
42.7k
3238
  // -fmodule-maps enables implicit reading of module map files. By default,
3239
  // this is enabled if we are using Clang's flavor of precompiled modules.
3240
42.7k
  if (Args.hasFlag(options::OPT_fimplicit_module_maps,
3241
42.7k
                   options::OPT_fno_implicit_module_maps, HaveClangModules))
3242
2.95k
    CmdArgs.push_back("-fimplicit-module-maps");
3243
42.7k
3244
  // -fmodules-decluse checks that modules used are declared so (off by default)
3245
42.7k
  if (Args.hasFlag(options::OPT_fmodules_decluse,
3246
42.7k
                   options::OPT_fno_modules_decluse, false))
3247
1
    CmdArgs.push_back("-fmodules-decluse");
3248
42.7k
3249
  // -fmodules-strict-decluse is like -fmodule-decluse, but also checks that
3250
  // all #included headers are part of modules.
3251
42.7k
  if (Args.hasFlag(options::OPT_fmodules_strict_decluse,
3252
42.7k
                   options::OPT_fno_modules_strict_decluse, false))
3253
0
    CmdArgs.push_back("-fmodules-strict-decluse");
3254
42.7k
3255
  // -fno-implicit-modules turns off implicitly compiling modules on demand.
3256
42.7k
  bool ImplicitModules = false;
3257
42.7k
  if (!Args.hasFlag(options::OPT_fimplicit_modules,
3258
39.8k
                    options::OPT_fno_implicit_modules, HaveClangModules)) {
3259
39.8k
    if (HaveModules)
3260
2.66k
      CmdArgs.push_back("-fno-implicit-modules");
3261
2.95k
  } else if (HaveModules) {
3262
2.95k
    ImplicitModules = true;
3263
    // -fmodule-cache-path specifies where our implicitly-built module files
3264
    // should be written.
3265
2.95k
    SmallString<128> Path;
3266
2.95k
    if (Arg *A = Args.getLastArg(options::OPT_fmodules_cache_path))
3267
2.93k
      Path = A->getValue();
3268
2.95k
3269
2.95k
    bool HasPath = true;
3270
2.95k
    if (C.isForDiagnostics()) {
3271
      // When generating crash reports, we want to emit the modules along with
3272
      // the reproduction sources, so we ignore any provided module path.
3273
14
      Path = Output.getFilename();
3274
14
      llvm::sys::path::replace_extension(Path, ".cache");
3275
14
      llvm::sys::path::append(Path, "modules");
3276
2.93k
    } else if (Path.empty()) {
3277
      // No module path was provided: use the default.
3278
29
      HasPath = Driver::getDefaultModuleCachePath(Path);
3279
29
    }
3280
2.95k
3281
    // `HasPath` will only be false if getDefaultModuleCachePath() fails.
3282
    // That being said, that failure is unlikely and not caching is harmless.
3283
2.95k
    if (
HasPath2.95k
) {
3284
2.95k
      const char Arg[] = "-fmodules-cache-path=";
3285
2.95k
      Path.insert(Path.begin(), Arg, Arg + strlen(Arg));
3286
2.95k
      CmdArgs.push_back(Args.MakeArgString(Path));
3287
2.95k
    }
3288
2.95k
  }
3289
42.7k
3290
42.7k
  if (HaveModules) {
3291
    // -fprebuilt-module-path specifies where to load the prebuilt module files.
3292
2
    for (const Arg *A : Args.filtered(options::OPT_fprebuilt_module_path)) {
3293
2
      CmdArgs.push_back(Args.MakeArgString(
3294
2
          std::string("-fprebuilt-module-path=") + A->getValue()));
3295
2
      A->claim();
3296
2
    }
3297
5.61k
    if (Args.hasFlag(options::OPT_fmodules_validate_input_files_content,
3298
5.61k
                     options::OPT_fno_modules_validate_input_files_content,
3299
5.61k
                     false))
3300
1
      CmdArgs.push_back("-fvalidate-ast-input-files-content");
3301
5.61k
  }
3302
42.7k
3303
  // -fmodule-name specifies the module that is currently being built (or
3304
  // used for header checking by -fmodule-maps).
3305
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fmodule_name_EQ);
3306
42.7k
3307
  // -fmodule-map-file can be used to specify files containing module
3308
  // definitions.
3309
42.7k
  Args.AddAllArgs(CmdArgs, options::OPT_fmodule_map_file);
3310
42.7k
3311
  // -fbuiltin-module-map can be used to load the clang
3312
  // builtin headers modulemap file.
3313
42.7k
  if (Args.hasArg(options::OPT_fbuiltin_module_map)) {
3314
1
    SmallString<128> BuiltinModuleMap(D.ResourceDir);
3315
1
    llvm::sys::path::append(BuiltinModuleMap, "include");
3316
1
    llvm::sys::path::append(BuiltinModuleMap, "module.modulemap");
3317
1
    if (llvm::sys::fs::exists(BuiltinModuleMap))
3318
1
      CmdArgs.push_back(
3319
1
          Args.MakeArgString("-fmodule-map-file=" + BuiltinModuleMap));
3320
1
  }
3321
42.7k
3322
  // The -fmodule-file=<name>=<file> form specifies the mapping of module
3323
  // names to precompiled module files (the module is loaded only if used).
3324
  // The -fmodule-file=<file> form can be used to unconditionally load
3325
  // precompiled module files (whether used or not).
3326
42.7k
  if (HaveModules)
3327
5.61k
    Args.AddAllArgs(CmdArgs, options::OPT_fmodule_file);
3328
37.1k
  else
3329
37.1k
    Args.ClaimAllArgs(options::OPT_fmodule_file);
3330
42.7k
3331
  // When building modules and generating crashdumps, we need to dump a module
3332
  // dependency VFS alongside the output.
3333
42.7k
  if (HaveClangModules && 
C.isForDiagnostics()2.95k
) {
3334
14
    SmallString<128> VFSDir(Output.getFilename());
3335
14
    llvm::sys::path::replace_extension(VFSDir, ".cache");
3336
    // Add the cache directory as a temp so the crash diagnostics pick it up.
3337
14
    C.addTempFile(Args.MakeArgString(VFSDir));
3338
14
3339
14
    llvm::sys::path::append(VFSDir, "vfs");
3340
14
    CmdArgs.push_back("-module-dependency-dir");
3341
14
    CmdArgs.push_back(Args.MakeArgString(VFSDir));
3342
14
  }
3343
42.7k
3344
42.7k
  if (HaveClangModules)
3345
2.95k
    Args.AddLastArg(CmdArgs, options::OPT_fmodules_user_build_path);
3346
42.7k
3347
  // Pass through all -fmodules-ignore-macro arguments.
3348
42.7k
  Args.AddAllArgs(CmdArgs, options::OPT_fmodules_ignore_macro);
3349
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
3350
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
3351
42.7k
3352
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fbuild_session_timestamp);
3353
42.7k
3354
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_fbuild_session_file)) {
3355
4
    if (Args.hasArg(options::OPT_fbuild_session_timestamp))
3356
1
      D.Diag(diag::err_drv_argument_not_allowed_with)
3357
1
          << A->getAsString(Args) << "-fbuild-session-timestamp";
3358
4
3359
4
    llvm::sys::fs::file_status Status;
3360
4
    if (llvm::sys::fs::status(A->getValue(), Status))
3361
1
      D.Diag(diag::err_drv_no_such_file) << A->getValue();
3362
4
    CmdArgs.push_back(
3363
4
        Args.MakeArgString("-fbuild-session-timestamp=" +
3364
4
                           Twine((uint64_t)Status.getLastModificationTime()
3365
4
                                     .time_since_epoch()
3366
4
                                     .count())));
3367
4
  }
3368
42.7k
3369
42.7k
  if (Args.getLastArg(options::OPT_fmodules_validate_once_per_build_session)) {
3370
3
    if (!Args.getLastArg(options::OPT_fbuild_session_timestamp,
3371
3
                         options::OPT_fbuild_session_file))
3372
1
      D.Diag(diag::err_drv_modules_validate_once_requires_timestamp);
3373
3
3374
3
    Args.AddLastArg(CmdArgs,
3375
3
                    options::OPT_fmodules_validate_once_per_build_session);
3376
3
  }
3377
42.7k
3378
42.7k
  if (Args.hasFlag(options::OPT_fmodules_validate_system_headers,
3379
42.7k
                   options::OPT_fno_modules_validate_system_headers,
3380
42.7k
                   ImplicitModules))
3381
2.95k
    CmdArgs.push_back("-fmodules-validate-system-headers");
3382
42.7k
3383
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fmodules_disable_diagnostic_validation);
3384
42.7k
}
3385
3386
static void RenderCharacterOptions(const ArgList &Args, const llvm::Triple &T,
3387
42.7k
                                   ArgStringList &CmdArgs) {
3388
  // -fsigned-char is default.
3389
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_fsigned_char,
3390
18
                                     options::OPT_fno_signed_char,
3391
18
                                     options::OPT_funsigned_char,
3392
18
                                     options::OPT_fno_unsigned_char)) {
3393
18
    if (A->getOption().matches(options::OPT_funsigned_char) ||
3394
10
        A->getOption().matches(options::OPT_fno_signed_char)) {
3395
10
      CmdArgs.push_back("-fno-signed-char");
3396
10
    }
3397
42.7k
  } else if (!isSignedCharDefault(T)) {
3398
3.46k
    CmdArgs.push_back("-fno-signed-char");
3399
3.46k
  }
3400
42.7k
3401
  // The default depends on the language standard.
3402
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fchar8__t, options::OPT_fno_char8__t);
3403
42.7k
3404
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_fshort_wchar,
3405
26
                                     options::OPT_fno_short_wchar)) {
3406
26
    if (A->getOption().matches(options::OPT_fshort_wchar)) {
3407
4
      CmdArgs.push_back("-fwchar-type=short");
3408
4
      CmdArgs.push_back("-fno-signed-wchar");
3409
22
    } else {
3410
22
      bool IsARM = T.isARM() || 
T.isThumb()9
||
T.isAArch64()9
;
3411
22
      CmdArgs.push_back("-fwchar-type=int");
3412
22
      if (IsARM && 
!(20
T.isOSWindows()20
||
T.isOSNetBSD()18
||
3413
12
                     T.isOSOpenBSD()))
3414
6
        CmdArgs.push_back("-fno-signed-wchar");
3415
16
      else
3416
16
        CmdArgs.push_back("-fsigned-wchar");
3417
22
    }
3418
26
  }
3419
42.7k
}
3420
3421
static void RenderObjCOptions(const ToolChain &TC, const Driver &D,
3422
                              const llvm::Triple &T, const ArgList &Args,
3423
                              ObjCRuntime &Runtime, bool InferCovariantReturns,
3424
42.7k
                              const InputInfo &Input, ArgStringList &CmdArgs) {
3425
42.7k
  const llvm::Triple::ArchType Arch = TC.getArch();
3426
42.7k
3427
  // -fobjc-dispatch-method is only relevant with the nonfragile-abi, and legacy
3428
  // is the default. Except for deployment target of 10.5, next runtime is
3429
  // always legacy dispatch and -fno-objc-legacy-dispatch gets ignored silently.
3430
42.7k
  if (Runtime.isNonFragile()) {
3431
19.3k
    if (!Args.hasFlag(options::OPT_fobjc_legacy_dispatch,
3432
19.3k
                      options::OPT_fno_objc_legacy_dispatch,
3433
26
                      Runtime.isLegacyDispatchDefaultForArch(Arch))) {
3434
26
      if (TC.UseObjCMixedDispatch())
3435
2
        CmdArgs.push_back("-fobjc-dispatch-method=mixed");
3436
24
      else
3437
24
        CmdArgs.push_back("-fobjc-dispatch-method=non-legacy");
3438
26
    }
3439
19.3k
  }
3440
42.7k
3441
  // When ObjectiveC legacy runtime is in effect on MacOSX, turn on the option
3442
  // to do Array/Dictionary subscripting by default.
3443
42.7k
  if (Arch == llvm::Triple::x86 && 
T.isMacOSX()9.68k
&&
3444
108
      Runtime.getKind() == ObjCRuntime::FragileMacOSX && 
Runtime.isNeXTFamily()92
)
3445
92
    CmdArgs.push_back("-fobjc-subscripting-legacy-runtime");
3446
42.7k
3447
  // Allow -fno-objc-arr to trump -fobjc-arr/-fobjc-arc.
3448
  // NOTE: This logic is duplicated in ToolChains.cpp.
3449
42.7k
  if (isObjCAutoRefCount(Args)) {
3450
1.27k
    TC.CheckObjCARC();
3451
1.27k
3452
1.27k
    CmdArgs.push_back("-fobjc-arc");
3453
1.27k
3454
    // FIXME: It seems like this entire block, and several around it should be
3455
    // wrapped in isObjC, but for now we just use it here as this is where it
3456
    // was being used previously.
3457
1.27k
    if (types::isCXX(Input.getType()) && 
types::isObjC(Input.getType())1.24k
) {
3458
1.24k
      if (TC.GetCXXStdlibType(Args) == ToolChain::CST_Libcxx)
3459
1.23k
        CmdArgs.push_back("-fobjc-arc-cxxlib=libc++");
3460
8
      else
3461
8
        CmdArgs.push_back("-fobjc-arc-cxxlib=libstdc++");
3462
1.24k
    }
3463
1.27k
3464
    // Allow the user to enable full exceptions code emission.
3465
    // We default off for Objective-C, on for Objective-C++.
3466
1.27k
    if (Args.hasFlag(options::OPT_fobjc_arc_exceptions,
3467
1.27k
                     options::OPT_fno_objc_arc_exceptions,
3468
1.27k
                     /*Default=*/types::isCXX(Input.getType())))
3469
1.24k
      CmdArgs.push_back("-fobjc-arc-exceptions");
3470
1.27k
  }
3471
42.7k
3472
  // Silence warning for full exception code emission options when explicitly
3473
  // set to use no ARC.
3474
42.7k
  if (Args.hasArg(options::OPT_fno_objc_arc)) {
3475
5
    Args.ClaimAllArgs(options::OPT_fobjc_arc_exceptions);
3476
5
    Args.ClaimAllArgs(options::OPT_fno_objc_arc_exceptions);
3477
5
  }
3478
42.7k
3479
  // Allow the user to control whether messages can be converted to runtime
3480
  // functions.
3481
42.7k
  if (types::isObjC(Input.getType())) {
3482
3.52k
    auto *Arg = Args.getLastArg(
3483
3.52k
        options::OPT_fobjc_convert_messages_to_runtime_calls,
3484
3.52k
        options::OPT_fno_objc_convert_messages_to_runtime_calls);
3485
3.52k
    if (Arg &&
3486
2
        Arg->getOption().matches(
3487
2
            options::OPT_fno_objc_convert_messages_to_runtime_calls))
3488
1
      CmdArgs.push_back("-fno-objc-convert-messages-to-runtime-calls");
3489
3.52k
  }
3490
42.7k
3491
  // -fobjc-infer-related-result-type is the default, except in the Objective-C
3492
  // rewriter.
3493
42.7k
  if (InferCovariantReturns)
3494
8
    CmdArgs.push_back("-fno-objc-infer-related-result-type");
3495
42.7k
3496
  // Pass down -fobjc-weak or -fno-objc-weak if present.
3497
42.7k
  if (types::isObjC(Input.getType())) {
3498
3.52k
    auto WeakArg =
3499
3.52k
        Args.getLastArg(options::OPT_fobjc_weak, options::OPT_fno_objc_weak);
3500
3.52k
    if (!WeakArg) {
3501
      // nothing to do
3502
12
    } else if (!Runtime.allowsWeak()) {
3503
4
      if (WeakArg->getOption().matches(options::OPT_fobjc_weak))
3504
4
        D.Diag(diag::err_objc_weak_unsupported);
3505
8
    } else {
3506
8
      WeakArg->render(Args, CmdArgs);
3507
8
    }
3508
3.52k
  }
3509
42.7k
}
3510
3511
static void RenderDiagnosticsOptions(const Driver &D, const ArgList &Args,
3512
42.7k
                                     ArgStringList &CmdArgs) {
3513
42.7k
  bool CaretDefault = true;
3514
42.7k
  bool ColumnDefault = true;
3515
42.7k
3516
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_diagnostics_classic,
3517
5
                                     options::OPT__SLASH_diagnostics_column,
3518
5
                                     options::OPT__SLASH_diagnostics_caret)) {
3519
5
    switch (A->getOption().getID()) {
3520
2
    case options::OPT__SLASH_diagnostics_caret:
3521
2
      CaretDefault = true;
3522
2
      ColumnDefault = true;
3523
2
      break;
3524
1
    case options::OPT__SLASH_diagnostics_column:
3525
1
      CaretDefault = false;
3526
1
      ColumnDefault = true;
3527
1
      break;
3528
2
    case options::OPT__SLASH_diagnostics_classic:
3529
2
      CaretDefault = false;
3530
2
      ColumnDefault = false;
3531
2
      break;
3532
42.7k
    }
3533
42.7k
  }
3534
42.7k
3535
  // -fcaret-diagnostics is default.
3536
42.7k
  if (!Args.hasFlag(options::OPT_fcaret_diagnostics,
3537
42.7k
                    options::OPT_fno_caret_diagnostics, CaretDefault))
3538
3
    CmdArgs.push_back("-fno-caret-diagnostics");
3539
42.7k
3540
  // -fdiagnostics-fixit-info is default, only pass non-default.
3541
42.7k
  if (!Args.hasFlag(options::OPT_fdiagnostics_fixit_info,
3542
42.7k
                    options::OPT_fno_diagnostics_fixit_info))
3543
0
    CmdArgs.push_back("-fno-diagnostics-fixit-info");
3544
42.7k
3545
  // Enable -fdiagnostics-show-option by default.
3546
42.7k
  if (!Args.hasFlag(options::OPT_fdiagnostics_show_option,
3547
42.7k
                    options::OPT_fno_diagnostics_show_option, true))
3548
1
    CmdArgs.push_back("-fno-diagnostics-show-option");
3549
42.7k
3550
42.7k
  if (const Arg *A =
3551
0
          Args.getLastArg(options::OPT_fdiagnostics_show_category_EQ)) {
3552
0
    CmdArgs.push_back("-fdiagnostics-show-category");
3553
0
    CmdArgs.push_back(A->getValue());
3554
0
  }
3555
42.7k
3556
42.7k
  if (Args.hasFlag(options::OPT_fdiagnostics_show_hotness,
3557
42.7k
                   options::OPT_fno_diagnostics_show_hotness, false))
3558
4
    CmdArgs.push_back("-fdiagnostics-show-hotness");
3559
42.7k
3560
42.7k
  if (const Arg *A =
3561
0
          Args.getLastArg(options::OPT_fdiagnostics_hotness_threshold_EQ)) {
3562
0
    std::string Opt =
3563
0
        std::string("-fdiagnostics-hotness-threshold=") + A->getValue();
3564
0
    CmdArgs.push_back(Args.MakeArgString(Opt));
3565
0
  }
3566
42.7k
3567
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_fdiagnostics_format_EQ)) {
3568
20
    CmdArgs.push_back("-fdiagnostics-format");
3569
20
    CmdArgs.push_back(A->getValue());
3570
20
  }
3571
42.7k
3572
42.7k
  if (const Arg *A = Args.getLastArg(
3573
0
          options::OPT_fdiagnostics_show_note_include_stack,
3574
0
          options::OPT_fno_diagnostics_show_note_include_stack)) {
3575
0
    const Option &O = A->getOption();
3576
0
    if (O.matches(options::OPT_fdiagnostics_show_note_include_stack))
3577
0
      CmdArgs.push_back("-fdiagnostics-show-note-include-stack");
3578
0
    else
3579
0
      CmdArgs.push_back("-fno-diagnostics-show-note-include-stack");
3580
0
  }
3581
42.7k
3582
  // Color diagnostics are parsed by the driver directly from argv and later
3583
  // re-parsed to construct this job; claim any possible color diagnostic here
3584
  // to avoid warn_drv_unused_argument and diagnose bad
3585
  // OPT_fdiagnostics_color_EQ values.
3586
784k
  for (const Arg *A : Args) {
3587
784k
    const Option &O = A->getOption();
3588
784k
    if (!O.matches(options::OPT_fcolor_diagnostics) &&
3589
784k
        !O.matches(options::OPT_fdiagnostics_color) &&
3590
784k
        !O.matches(options::OPT_fno_color_diagnostics) &&
3591
784k
        !O.matches(options::OPT_fno_diagnostics_color) &&
3592
784k
        !O.matches(options::OPT_fdiagnostics_color_EQ))
3593
784k
      continue;
3594
36
3595
36
    if (O.matches(options::OPT_fdiagnostics_color_EQ)) {
3596
6
      StringRef Value(A->getValue());
3597
6
      if (Value != "always" && 
Value != "never"4
&&
Value != "auto"3
)
3598
1
        D.Diag(diag::err_drv_clang_unsupported)
3599
1
            << ("-fdiagnostics-color=" + Value).str();
3600
6
    }
3601
36
    A->claim();
3602
36
  }
3603
42.7k
3604
42.7k
  if (D.getDiags().getDiagnosticOptions().ShowColors)
3605
9
    CmdArgs.push_back("-fcolor-diagnostics");
3606
42.7k
3607
42.7k
  if (Args.hasArg(options::OPT_fansi_escape_codes))
3608
1
    CmdArgs.push_back("-fansi-escape-codes");
3609
42.7k
3610
42.7k
  if (!Args.hasFlag(options::OPT_fshow_source_location,
3611
42.7k
                    options::OPT_fno_show_source_location))
3612
1
    CmdArgs.push_back("-fno-show-source-location");
3613
42.7k
3614
42.7k
  if (Args.hasArg(options::OPT_fdiagnostics_absolute_paths))
3615
0
    CmdArgs.push_back("-fdiagnostics-absolute-paths");
3616
42.7k
3617
42.7k
  if (!Args.hasFlag(options::OPT_fshow_column, options::OPT_fno_show_column,
3618
42.7k
                    ColumnDefault))
3619
4
    CmdArgs.push_back("-fno-show-column");
3620
42.7k
3621
42.7k
  if (!Args.hasFlag(options::OPT_fspell_checking,
3622
42.7k
                    options::OPT_fno_spell_checking))
3623
993
    CmdArgs.push_back("-fno-spell-checking");
3624
42.7k
}
3625
3626
enum class DwarfFissionKind { None, Split, Single };
3627
3628
static DwarfFissionKind getDebugFissionKind(const Driver &D,
3629
43.1k
                                            const ArgList &Args, Arg *&Arg) {
3630
43.1k
  Arg =
3631
43.1k
      Args.getLastArg(options::OPT_gsplit_dwarf, options::OPT_gsplit_dwarf_EQ);
3632
43.1k
  if (!Arg)
3633
43.0k
    return DwarfFissionKind::None;
3634
36
3635
36
  if (Arg->getOption().matches(options::OPT_gsplit_dwarf))
3636
30
    return DwarfFissionKind::Split;
3637
6
3638
6
  StringRef Value = Arg->getValue();
3639
6
  if (Value == "split")
3640
4
    return DwarfFissionKind::Split;
3641
2
  if (Value == "single")
3642
3
    return DwarfFissionKind::Single;
3643
18.4E
3644
18.4E
  D.Diag(diag::err_drv_unsupported_option_argument)
3645
18.4E
      << Arg->getOption().getName() << Arg->getValue();
3646
18.4E
  return DwarfFissionKind::None;
3647
18.4E
}
3648
3649
static void RenderDebugOptions(const ToolChain &TC, const Driver &D,
3650
                               const llvm::Triple &T, const ArgList &Args,
3651
                               bool EmitCodeView, ArgStringList &CmdArgs,
3652
                               codegenoptions::DebugInfoKind &DebugInfoKind,
3653
42.7k
                               DwarfFissionKind &DwarfFission) {
3654
42.7k
  if (Args.hasFlag(options::OPT_fdebug_info_for_profiling,
3655
42.7k
                   options::OPT_fno_debug_info_for_profiling, false) &&
3656
1
      checkDebugInfoOption(
3657
1
          Args.getLastArg(options::OPT_fdebug_info_for_profiling), Args, D, TC))
3658
1
    CmdArgs.push_back("-fdebug-info-for-profiling");
3659
42.7k
3660
  // The 'g' groups options involve a somewhat intricate sequence of decisions
3661
  // about what to pass from the driver to the frontend, but by the time they
3662
  // reach cc1 they've been factored into three well-defined orthogonal choices:
3663
  //  * what level of debug info to generate
3664
  //  * what dwarf version to write
3665
  //  * what debugger tuning to use
3666
  // This avoids having to monkey around further in cc1 other than to disable
3667
  // codeview if not running in a Windows environment. Perhaps even that
3668
  // decision should be made in the driver as well though.
3669
42.7k
  llvm::DebuggerKind DebuggerTuning = TC.getDefaultDebuggerTuning();
3670
42.7k
3671
42.7k
  bool SplitDWARFInlining =
3672
42.7k
      Args.hasFlag(options::OPT_fsplit_dwarf_inlining,
3673
42.7k
                   options::OPT_fno_split_dwarf_inlining, false);
3674
42.7k
3675
42.7k
  Args.ClaimAllArgs(options::OPT_g_Group);
3676
42.7k
3677
42.7k
  Arg* SplitDWARFArg;
3678
42.7k
  DwarfFission = getDebugFissionKind(D, Args, SplitDWARFArg);
3679
42.7k
3680
42.7k
  if (DwarfFission != DwarfFissionKind::None &&
3681
32
      !checkDebugInfoOption(SplitDWARFArg, Args, D, TC)) {
3682
0
    DwarfFission = DwarfFissionKind::None;
3683
0
    SplitDWARFInlining = false;
3684
0
  }
3685
42.7k
3686
42.7k
  if (const Arg *A =
3687
6.42k
          Args.getLastArg(options::OPT_g_Group, options::OPT_gsplit_dwarf,
3688
6.42k
                          options::OPT_gsplit_dwarf_EQ)) {
3689
6.42k
    DebugInfoKind = codegenoptions::LimitedDebugInfo;
3690
6.42k
3691
    // If the last option explicitly specified a debug-info level, use it.
3692
6.42k
    if (checkDebugInfoOption(A, Args, D, TC) &&
3693
6.42k
        A->getOption().matches(options::OPT_gN_Group)) {
3694
1.66k
      DebugInfoKind = DebugLevelToInfoKind(*A);
3695
      // For -g0 or -gline-tables-only, drop -gsplit-dwarf. This gets a bit more
3696
      // complicated if you've disabled inline info in the skeleton CUs
3697
      // (SplitDWARFInlining) - then there's value in composing split-dwarf and
3698
      // line-tables-only, so let those compose naturally in that case.
3699
1.66k
      if (DebugInfoKind == codegenoptions::NoDebugInfo ||
3700
1.62k
          DebugInfoKind == codegenoptions::DebugDirectivesOnly ||
3701
1.61k
          (DebugInfoKind == codegenoptions::DebugLineTablesOnly &&
3702
28
           SplitDWARFInlining))
3703
52
        DwarfFission = DwarfFissionKind::None;
3704
1.66k
    }
3705
6.42k
  }
3706
42.7k
3707
  // If a debugger tuning argument appeared, remember it.
3708
42.7k
  if (const Arg *A =
3709
208
          Args.getLastArg(options::OPT_gTune_Group, options::OPT_ggdbN_Group)) {
3710
208
    if (checkDebugInfoOption(A, Args, D, TC)) {
3711
207
      if (A->getOption().matches(options::OPT_glldb))
3712
121
        DebuggerTuning = llvm::DebuggerKind::LLDB;
3713
86
      else if (A->getOption().matches(options::OPT_gsce))
3714
3
        DebuggerTuning = llvm::DebuggerKind::SCE;
3715
83
      else
3716
83
        DebuggerTuning = llvm::DebuggerKind::GDB;
3717
207
    }
3718
208
  }
3719
42.7k
3720
  // If a -gdwarf argument appeared, remember it.
3721
42.7k
  const Arg *GDwarfN = Args.getLastArg(
3722
42.7k
      options::OPT_gdwarf_2, options::OPT_gdwarf_3, options::OPT_gdwarf_4,
3723
42.7k
      options::OPT_gdwarf_5, options::OPT_gdwarf);
3724
42.7k
  bool EmitDwarf = false;
3725
42.7k
  if (GDwarfN) {
3726
32
    if (checkDebugInfoOption(GDwarfN, Args, D, TC))
3727
32
      EmitDwarf = true;
3728
0
    else
3729
0
      GDwarfN = nullptr;
3730
32
  }
3731
42.7k
3732
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_gcodeview)) {
3733
11
    if (checkDebugInfoOption(A, Args, D, TC))
3734
11
      EmitCodeView = true;
3735
11
  }
3736
42.7k
3737
  // If the user asked for debug info but did not explicitly specify -gcodeview
3738
  // or -gdwarf, ask the toolchain for the default format.
3739
42.7k
  if (!EmitCodeView && 
!EmitDwarf42.7k
&&
3740
42.7k
      DebugInfoKind != codegenoptions::NoDebugInfo) {
3741
6.34k
    switch (TC.getDefaultDebugFormat()) {
3742
3
    case codegenoptions::DIF_CodeView:
3743
3
      EmitCodeView = true;
3744
3
      break;
3745
6.34k
    case codegenoptions::DIF_DWARF:
3746
6.34k
      EmitDwarf = true;
3747
6.34k
      break;
3748
42.7k
    }
3749
42.7k
  }
3750
42.7k
3751
42.7k
  unsigned DWARFVersion = 0;
3752
42.7k
  unsigned DefaultDWARFVersion = ParseDebugDefaultVersion(TC, Args);
3753
42.7k
  if (EmitDwarf) {
3754
    // Start with the platform default DWARF version
3755
6.37k
    DWARFVersion = TC.GetDefaultDwarfVersion();
3756
6.37k
    assert(DWARFVersion && "toolchain default DWARF version must be nonzero");
3757
6.37k
3758
    // If the user specified a default DWARF version, that takes precedence
3759
    // over the platform default.
3760
6.37k
    if (DefaultDWARFVersion)
3761
8
      DWARFVersion = DefaultDWARFVersion;
3762
6.37k
3763
    // Override with a user-specified DWARF version
3764
6.37k
    if (GDwarfN)
3765
32
      if (auto ExplicitVersion = DwarfVersionNum(GDwarfN->getSpelling()))
3766
24
        DWARFVersion = ExplicitVersion;
3767
6.37k
  }
3768
42.7k
3769
  // -gline-directives-only supported only for the DWARF debug info.
3770
42.7k
  if (DWARFVersion == 0 && 
DebugInfoKind == codegenoptions::DebugDirectivesOnly36.3k
)
3771
0
    DebugInfoKind = codegenoptions::NoDebugInfo;
3772
42.7k
3773
  // We ignore flag -gstrict-dwarf for now.
3774
  // And we handle flag -grecord-gcc-switches later with DWARFDebugFlags.
3775
42.7k
  Args.ClaimAllArgs(options::OPT_g_flags_Group);
3776
42.7k
3777
  // Column info is included by default for everything except SCE and
3778
  // CodeView. Clang doesn't track end columns, just starting columns, which,
3779
  // in theory, is fine for CodeView (and PDB).  In practice, however, the
3780
  // Microsoft debuggers don't handle missing end columns well, so it's better
3781
  // not to include any column info.
3782
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_gcolumn_info))
3783
28
    (void)checkDebugInfoOption(A, Args, D, TC);
3784
42.7k
  if (!Args.hasFlag(options::OPT_gcolumn_info, options::OPT_gno_column_info,
3785
42.7k
                    !EmitCodeView && 
DebuggerTuning != llvm::DebuggerKind::SCE42.7k
))
3786
157
    CmdArgs.push_back("-gno-column-info");
3787
42.7k
3788
  // FIXME: Move backend command line options to the module.
3789
  // If -gline-tables-only or -gline-directives-only is the last option it wins.
3790
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_gmodules))
3791
1.59k
    if (checkDebugInfoOption(A, Args, D, TC)) {
3792
1.59k
      if (DebugInfoKind != codegenoptions::DebugLineTablesOnly &&
3793
1.59k
          DebugInfoKind != codegenoptions::DebugDirectivesOnly) {
3794
1.59k
        DebugInfoKind = codegenoptions::LimitedDebugInfo;
3795
1.59k
        CmdArgs.push_back("-dwarf-ext-refs");
3796
1.59k
        CmdArgs.push_back("-fmodule-format=obj");
3797
1.59k
      }
3798
1.59k
    }
3799
42.7k
3800
42.7k
  if (T.isOSBinFormatELF() && 
!SplitDWARFInlining16.8k
)
3801
16.8k
    CmdArgs.push_back("-fno-split-dwarf-inlining");
3802
42.7k
3803
  // After we've dealt with all combinations of things that could
3804
  // make DebugInfoKind be other than None or DebugLineTablesOnly,
3805
  // figure out if we need to "upgrade" it to standalone debug info.
3806
  // We parse these two '-f' options whether or not they will be used,
3807
  // to claim them even if you wrote "-fstandalone-debug -gline-tables-only"
3808
42.7k
  bool NeedFullDebug = Args.hasFlag(
3809
42.7k
      options::OPT_fstandalone_debug, options::OPT_fno_standalone_debug,
3810
42.7k
      DebuggerTuning == llvm::DebuggerKind::LLDB ||
3811
24.7k
          TC.GetDefaultStandaloneDebug());
3812
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_fstandalone_debug))
3813
5.80k
    (void)checkDebugInfoOption(A, Args, D, TC);
3814
42.7k
3815
42.7k
  if (DebugInfoKind == codegenoptions::LimitedDebugInfo) {
3816
6.35k
    if (Args.hasFlag(options::OPT_fno_eliminate_unused_debug_types,
3817
6.35k
                     options::OPT_feliminate_unused_debug_types, false))
3818
1
      DebugInfoKind = codegenoptions::UnusedTypeInfo;
3819
6.35k
    else if (NeedFullDebug)
3820
6.12k
      DebugInfoKind = codegenoptions::FullDebugInfo;
3821
6.35k
  }
3822
42.7k
3823
42.7k
  if (Args.hasFlag(options::OPT_gembed_source, options::OPT_gno_embed_source,
3824
2
                   false)) {
3825
    // Source embedding is a vendor extension to DWARF v5. By now we have
3826
    // checked if a DWARF version was stated explicitly, and have otherwise
3827
    // fallen back to the target default, so if this is still not at least 5
3828
    // we emit an error.
3829
2
    const Arg *A = Args.getLastArg(options::OPT_gembed_source);
3830
2
    if (DWARFVersion < 5)
3831
1
      D.Diag(diag::err_drv_argument_only_allowed_with)
3832
1
          << A->getAsString(Args) << "-gdwarf-5";
3833
1
    else if (checkDebugInfoOption(A, Args, D, TC))
3834
1
      CmdArgs.push_back("-gembed-source");
3835
2
  }
3836
42.7k
3837
42.7k
  if (EmitCodeView) {
3838
28
    CmdArgs.push_back("-gcodeview");
3839
28
3840
    // Emit codeview type hashes if requested.
3841
28
    if (Args.hasFlag(options::OPT_gcodeview_ghash,
3842
2
                     options::OPT_gno_codeview_ghash, false)) {
3843
2
      CmdArgs.push_back("-gcodeview-ghash");
3844
2
    }
3845
28
  }
3846
42.7k
3847
  // Omit inline line tables if requested.
3848
42.7k
  if (Args.hasFlag(options::OPT_gno_inline_line_tables,
3849
1
                   options::OPT_ginline_line_tables, false)) {
3850
1
    CmdArgs.push_back("-gno-inline-line-tables");
3851
1
  }
3852
42.7k
3853
  // Adjust the debug info kind for the given toolchain.
3854
42.7k
  TC.adjustDebugInfoKind(DebugInfoKind, Args);
3855
42.7k
3856
  // When emitting remarks, we need at least debug lines in the output.
3857
42.7k
  if (willEmitRemarks(Args) &&
3858
34
      DebugInfoKind <= codegenoptions::DebugDirectivesOnly)
3859
33
    DebugInfoKind = codegenoptions::DebugLineTablesOnly;
3860
42.7k
3861
42.7k
  RenderDebugEnablingArgs(Args, CmdArgs, DebugInfoKind, DWARFVersion,
3862
42.7k
                          DebuggerTuning);
3863
42.7k
3864
  // -fdebug-macro turns on macro debug info generation.
3865
42.7k
  if (Args.hasFlag(options::OPT_fdebug_macro, options::OPT_fno_debug_macro,
3866
42.7k
                   false))
3867
1
    if (checkDebugInfoOption(Args.getLastArg(options::OPT_fdebug_macro), Args,
3868
1
                             D, TC))
3869
1
      CmdArgs.push_back("-debug-info-macro");
3870
42.7k
3871
  // -ggnu-pubnames turns on gnu style pubnames in the backend.
3872
42.7k
  const auto *PubnamesArg =
3873
42.7k
      Args.getLastArg(options::OPT_ggnu_pubnames, options::OPT_gno_gnu_pubnames,
3874
42.7k
                      options::OPT_gpubnames, options::OPT_gno_pubnames);
3875
42.7k
  if (DwarfFission != DwarfFissionKind::None ||
3876
42.7k
      (PubnamesArg && 
checkDebugInfoOption(PubnamesArg, Args, D, TC)7
))
3877
35
    if (!PubnamesArg ||
3878
8
        (!PubnamesArg->getOption().matches(options::OPT_gno_gnu_pubnames) &&
3879
6
         !PubnamesArg->getOption().matches(options::OPT_gno_pubnames)))
3880
29
      CmdArgs.push_back(PubnamesArg && PubnamesArg->getOption().matches(
3881
2
                                           options::OPT_gpubnames)
3882
1
                            ? "-gpubnames"
3883
28
                            : "-ggnu-pubnames");
3884
42.7k
3885
42.7k
  if (Args.hasFlag(options::OPT_fdebug_ranges_base_address,
3886
1
                   options::OPT_fno_debug_ranges_base_address, false)) {
3887
1
    CmdArgs.push_back("-fdebug-ranges-base-address");
3888
1
  }
3889
42.7k
3890
  // -gdwarf-aranges turns on the emission of the aranges section in the
3891
  // backend.
3892
  // Always enabled for SCE tuning.
3893
42.7k
  bool NeedAranges = DebuggerTuning == llvm::DebuggerKind::SCE;
3894
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_gdwarf_aranges))
3895
1
    NeedAranges = checkDebugInfoOption(A, Args, D, TC) || 
NeedAranges0
;
3896
42.7k
  if (NeedAranges) {
3897
131
    CmdArgs.push_back("-mllvm");
3898
131
    CmdArgs.push_back("-generate-arange-section");
3899
131
  }
3900
42.7k
3901
42.7k
  if (Args.hasFlag(options::OPT_fforce_dwarf_frame,
3902
42.7k
                   options::OPT_fno_force_dwarf_frame, false))
3903
1
    CmdArgs.push_back("-fforce-dwarf-frame");
3904
42.7k
3905
42.7k
  if (Args.hasFlag(options::OPT_fdebug_types_section,
3906
3
                   options::OPT_fno_debug_types_section, false)) {
3907
3
    if (!T.isOSBinFormatELF()) {
3908
1
      D.Diag(diag::err_drv_unsupported_opt_for_target)
3909
1
          << Args.getLastArg(options::OPT_fdebug_types_section)
3910
1
                 ->getAsString(Args)
3911
1
          << T.getTriple();
3912
2
    } else if (checkDebugInfoOption(
3913
2
                   Args.getLastArg(options::OPT_fdebug_types_section), Args, D,
3914
2
                   TC)) {
3915
2
      CmdArgs.push_back("-mllvm");
3916
2
      CmdArgs.push_back("-generate-type-units");
3917
2
    }
3918
3
  }
3919
42.7k
3920
  // Decide how to render forward declarations of template instantiations.
3921
  // SCE wants full descriptions, others just get them in the name.
3922
42.7k
  if (DebuggerTuning == llvm::DebuggerKind::SCE)
3923
130
    CmdArgs.push_back("-debug-forward-template-params");
3924
42.7k
3925
  // Do we need to explicitly import anonymous namespaces into the parent
3926
  // scope?
3927
42.7k
  if (DebuggerTuning == llvm::DebuggerKind::SCE)
3928
130
    CmdArgs.push_back("-dwarf-explicit-import");
3929
42.7k
3930
42.7k
  RenderDebugInfoCompressionArgs(Args, CmdArgs, D, TC);
3931
42.7k
}
3932
3933
void Clang::ConstructJob(Compilation &C, const JobAction &JA,
3934
                         const InputInfo &Output, const InputInfoList &Inputs,
3935
42.7k
                         const ArgList &Args, const char *LinkingOutput) const {
3936
42.7k
  const auto &TC = getToolChain();
3937
42.7k
  const llvm::Triple &RawTriple = TC.getTriple();
3938
42.7k
  const llvm::Triple &Triple = TC.getEffectiveTriple();
3939
42.7k
  const std::string &TripleStr = Triple.getTriple();
3940
42.7k
3941
42.7k
  bool KernelOrKext =
3942
42.7k
      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
3943
42.7k
  const Driver &D = TC.getDriver();
3944
42.7k
  ArgStringList CmdArgs;
3945
42.7k
3946
  // Check number of inputs for sanity. We need at least one input.
3947
42.7k
  assert(Inputs.size() >= 1 && "Must have at least one input.");
3948
  // CUDA/HIP compilation may have multiple inputs (source file + results of
3949
  // device-side compilations). OpenMP device jobs also take the host IR as a
3950
  // second input. Module precompilation accepts a list of header files to
3951
  // include as part of the module. All other jobs are expected to have exactly
3952
  // one input.
3953
42.7k
  bool IsCuda = JA.isOffloading(Action::OFK_Cuda);
3954
42.7k
  bool IsHIP = JA.isOffloading(Action::OFK_HIP);
3955
42.7k
  bool IsOpenMPDevice = JA.isDeviceOffloading(Action::OFK_OpenMP);
3956
42.7k
  bool IsHeaderModulePrecompile = isa<HeaderModulePrecompileJobAction>(JA);
3957
42.7k
3958
  // A header module compilation doesn't have a main input file, so invent a
3959
  // fake one as a placeholder.
3960
42.7k
  const char *ModuleName = [&]{
3961
42.7k
    auto *ModuleNameArg = Args.getLastArg(options::OPT_fmodule_name_EQ);
3962
42.7k
    return ModuleNameArg ? 
ModuleNameArg->getValue()5
: "";
3963
42.7k
  }();
3964
42.7k
  InputInfo HeaderModuleInput(Inputs[0].getType(), ModuleName, ModuleName);
3965
42.7k
3966
42.7k
  const InputInfo &Input =
3967
42.7k
      IsHeaderModulePrecompile ? 
HeaderModuleInput3
: Inputs[0];
3968
42.7k
3969
42.7k
  InputInfoList ModuleHeaderInputs;
3970
42.7k
  const InputInfo *CudaDeviceInput = nullptr;
3971
42.7k
  const InputInfo *OpenMPDeviceInput = nullptr;
3972
43.1k
  for (const InputInfo &I : Inputs) {
3973
43.1k
    if (&I == &Input) {
3974
      // This is the primary input.
3975
326
    } else if (IsHeaderModulePrecompile &&
3976
7
               types::getPrecompiledType(I.getType()) == types::TY_PCH) {
3977
7
      types::ID Expected = HeaderModuleInput.getType();
3978
7
      if (I.getType() != Expected) {
3979
0
        D.Diag(diag::err_drv_module_header_wrong_kind)
3980
0
            << I.getFilename() << types::getTypeName(I.getType())
3981
0
            << types::getTypeName(Expected);
3982
0
      }
3983
7
      ModuleHeaderInputs.push_back(I);
3984
319
    } else if ((IsCuda || 
IsHIP144
) &&
!CudaDeviceInput243
) {
3985
243
      CudaDeviceInput = &I;
3986
76
    } else if (IsOpenMPDevice && !OpenMPDeviceInput) {
3987
76
      OpenMPDeviceInput = &I;
3988
0
    } else {
3989
0
      llvm_unreachable("unexpectedly given multiple inputs");
3990
0
    }
3991
43.1k
  }
3992
42.7k
3993
42.7k
  const llvm::Triple *AuxTriple =
3994
42.7k
      (IsCuda || 
IsHIP42.2k
) ?
TC.getAuxTriple()767
:
nullptr42.0k
;
3995
42.7k
  bool IsWindowsMSVC = RawTriple.isWindowsMSVCEnvironment();
3996
42.7k
  bool IsIAMCU = RawTriple.isOSIAMCU();
3997
42.7k
3998
  // Adjust IsWindowsXYZ for CUDA/HIP compilations.  Even when compiling in
3999
  // device mode (i.e., getToolchain().getTriple() is NVPTX/AMDGCN, not
4000
  // Windows), we need to pass Windows-specific flags to cc1.
4001
42.7k
  if (IsCuda || 
IsHIP42.2k
)
4002
767
    IsWindowsMSVC |= AuxTriple && 
AuxTriple->isWindowsMSVCEnvironment()440
;
4003
42.7k
4004
  // C++ is not supported for IAMCU.
4005
42.7k
  if (IsIAMCU && 
types::isCXX(Input.getType())9
)
4006
1
    D.Diag(diag::err_drv_clang_unsupported) << "C++ for IAMCU";
4007
42.7k
4008
  // Invoke ourselves in -cc1 mode.
4009
  //
4010
  // FIXME: Implement custom jobs for internal actions.
4011
42.7k
  CmdArgs.push_back("-cc1");
4012
42.7k
4013
  // Add the "effective" target triple.
4014
42.7k
  CmdArgs.push_back("-triple");
4015
42.7k
  CmdArgs.push_back(Args.MakeArgString(TripleStr));
4016
42.7k
4017
42.7k
  if (const Arg *MJ = Args.getLastArg(options::OPT_MJ)) {
4018
4
    DumpCompilationDatabase(C, MJ->getValue(), TripleStr, Output, Input, Args);
4019
4
    Args.ClaimAllArgs(options::OPT_MJ);
4020
42.7k
  } else if (const Arg *GenCDBFragment =
4021
4
                 Args.getLastArg(options::OPT_gen_cdb_fragment_path)) {
4022
4
    DumpCompilationDatabaseFragmentToDir(GenCDBFragment->getValue(), C,
4023
4
                                         TripleStr, Output, Input, Args);
4024
4
    Args.ClaimAllArgs(options::OPT_gen_cdb_fragment_path);
4025
4
  }
4026
42.7k
4027
42.7k
  if (IsCuda || 
IsHIP42.2k
) {
4028
    // We have to pass the triple of the host if compiling for a CUDA/HIP device
4029
    // and vice-versa.
4030
767
    std::string NormalizedTriple;
4031
767
    if (JA.isDeviceOffloading(Action::OFK_Cuda) ||
4032
495
        JA.isDeviceOffloading(Action::OFK_HIP))
4033
440
      NormalizedTriple = C.getSingleOffloadToolChain<Action::OFK_Host>()
4034
440
                             ->getTriple()
4035
440
                             .normalize();
4036
327
    else {
4037
      // Host-side compilation.
4038
327
      NormalizedTriple =
4039
223
          (IsCuda ? C.getSingleOffloadToolChain<Action::OFK_Cuda>()
4040
104
                  : C.getSingleOffloadToolChain<Action::OFK_HIP>())
4041
327
              ->getTriple()
4042
327
              .normalize();
4043
327
      if (IsCuda) {
4044
        // We need to figure out which CUDA version we're compiling for, as that
4045
        // determines how we load and launch GPU kernels.
4046
223
        auto *CTC = static_cast<const toolchains::CudaToolChain *>(
4047
223
            C.getSingleOffloadToolChain<Action::OFK_Cuda>());
4048
223
        assert(CTC && "Expected valid CUDA Toolchain.");
4049
223
        if (CTC && CTC->CudaInstallation.version() != CudaVersion::UNKNOWN)
4050
38
          CmdArgs.push_back(Args.MakeArgString(
4051
38
              Twine("-target-sdk-version=") +
4052
38
              CudaVersionToString(CTC->CudaInstallation.version())));
4053
223
      }
4054
327
    }
4055
767
    CmdArgs.push_back("-aux-triple");
4056
767
    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4057
767
  }
4058
42.7k
4059
42.7k
  if (Args.hasFlag(options::OPT_fsycl, options::OPT_fno_sycl, false)) {
4060
10
    CmdArgs.push_back("-fsycl");
4061
10
    CmdArgs.push_back("-fsycl-is-device");
4062
10
4063
10
    if (Arg *A = Args.getLastArg(options::OPT_sycl_std_EQ)) {
4064
5
      A->render(Args, CmdArgs);
4065
5
    } else {
4066
      // Ensure the default version in SYCL mode is 1.2.1 (aka 2017)
4067
5
      CmdArgs.push_back("-sycl-std=2017");
4068
5
    }
4069
10
  }
4070
42.7k
4071
42.7k
  if (IsOpenMPDevice) {
4072
    // We have to pass the triple of the host if compiling for an OpenMP device.
4073
107
    std::string NormalizedTriple =
4074
107
        C.getSingleOffloadToolChain<Action::OFK_Host>()
4075
107
            ->getTriple()
4076
107
            .normalize();
4077
107
    CmdArgs.push_back("-aux-triple");
4078
107
    CmdArgs.push_back(Args.MakeArgString(NormalizedTriple));
4079
107
  }
4080
42.7k
4081
42.7k
  if (Triple.isOSWindows() && 
(7.75k
Triple.getArch() == llvm::Triple::arm7.75k
||
4082
7.75k
                               Triple.getArch() == llvm::Triple::thumb)) {
4083
61
    unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 
40
: 6;
4084
61
    unsigned Version = 0;
4085
61
    bool Failure =
4086
61
        Triple.getArchName().substr(Offset).consumeInteger(10, Version);
4087
61
    if (Failure || Version < 7)
4088
2
      D.Diag(diag::err_target_unsupported_arch) << Triple.getArchName()
4089
2
                                                << TripleStr;
4090
61
  }
4091
42.7k
4092
  // Push all default warning arguments that are specific to
4093
  // the given target.  These come before user provided warning options
4094
  // are provided.
4095
42.7k
  TC.addClangWarningOptions(CmdArgs);
4096
42.7k
4097
  // Select the appropriate action.
4098
42.7k
  RewriteKind rewriteKind = RK_None;
4099
42.7k
4100
  // If CollectArgsForIntegratedAssembler() isn't called below, claim the args
4101
  // it claims when not running an assembler. Otherwise, clang would emit
4102
  // "argument unused" warnings for assembler flags when e.g. adding "-E" to
4103
  // flags while debugging something. That'd be somewhat inconvenient, and it's
4104
  // also inconsistent with most other flags -- we don't warn on
4105
  // -ffunction-sections not being used in -E mode either for example, even
4106
  // though it's not really used either.
4107
42.7k
  if (!isa<AssembleJobAction>(JA)) {
4108
    // The args claimed here should match the args used in
4109
    // CollectArgsForIntegratedAssembler().
4110
33.3k
    if (TC.useIntegratedAs()) {
4111
32.4k
      Args.ClaimAllArgs(options::OPT_mrelax_all);
4112
32.4k
      Args.ClaimAllArgs(options::OPT_mno_relax_all);
4113
32.4k
      Args.ClaimAllArgs(options::OPT_mincremental_linker_compatible);
4114
32.4k
      Args.ClaimAllArgs(options::OPT_mno_incremental_linker_compatible);
4115
32.4k
      switch (C.getDefaultToolChain().getArch()) {
4116
493
      case llvm::Triple::arm:
4117
493
      case llvm::Triple::armeb:
4118
493
      case llvm::Triple::thumb:
4119
493
      case llvm::Triple::thumbeb:
4120
493
        Args.ClaimAllArgs(options::OPT_mimplicit_it_EQ);
4121
493
        break;
4122
31.9k
      default:
4123
31.9k
        break;
4124
33.3k
      }
4125
33.3k
    }
4126
33.3k
    Args.ClaimAllArgs(options::OPT_Wa_COMMA);
4127
33.3k
    Args.ClaimAllArgs(options::OPT_Xassembler);
4128
33.3k
  }
4129
42.7k
4130
42.7k
  if (isa<AnalyzeJobAction>(JA)) {
4131
41
    assert(JA.getType() == types::TY_Plist && "Invalid output type.");
4132
41
    CmdArgs.push_back("-analyze");
4133
42.7k
  } else if (isa<MigrateJobAction>(JA)) {
4134
0
    CmdArgs.push_back("-migrate");
4135
42.7k
  } else if (isa<PreprocessJobAction>(JA)) {
4136
4.15k
    if (Output.getType() == types::TY_Dependencies)
4137
2.91k
      CmdArgs.push_back("-Eonly");
4138
1.24k
    else {
4139
1.24k
      CmdArgs.push_back("-E");
4140
1.24k
      if (Args.hasArg(options::OPT_rewrite_objc) &&
4141
5
          !Args.hasArg(options::OPT_g_Group))
4142
4
        CmdArgs.push_back("-P");
4143
1.24k
    }
4144
38.5k
  } else if (isa<AssembleJobAction>(JA)) {
4145
9.39k
    CmdArgs.push_back("-emit-obj");
4146
9.39k
4147
9.39k
    CollectArgsForIntegratedAssembler(C, Args, CmdArgs, D);
4148
9.39k
4149
    // Also ignore explicit -force_cpusubtype_ALL option.
4150
9.39k
    (void)Args.hasArg(options::OPT_force__cpusubtype__ALL);
4151
29.1k
  } else if (isa<PrecompileJobAction>(JA)) {
4152
74
    if (JA.getType() == types::TY_Nothing)
4153
31
      CmdArgs.push_back("-fsyntax-only");
4154
43
    else if (JA.getType() == types::TY_ModuleFile)
4155
8
      CmdArgs.push_back(IsHeaderModulePrecompile
4156
2
                            ? "-emit-header-module"
4157
6
                            : "-emit-module-interface");
4158
35
    else
4159
35
      CmdArgs.push_back("-emit-pch");
4160
29.1k
  } else if (isa<VerifyPCHJobAction>(JA)) {
4161
2
    CmdArgs.push_back("-verify-pch");
4162
29.1k
  } else {
4163
29.1k
    assert((isa<CompileJobAction>(JA) || isa<BackendJobAction>(JA)) &&
4164
29.1k
           "Invalid action for clang tool.");
4165
29.1k
    if (JA.getType() == types::TY_Nothing) {
4166
26.6k
      CmdArgs.push_back("-fsyntax-only");
4167
2.46k
    } else if (JA.getType() == types::TY_LLVM_IR ||
4168
1.99k
               JA.getType() == types::TY_LTO_IR) {
4169
474
      CmdArgs.push_back("-emit-llvm");
4170
1.98k
    } else if (JA.getType() == types::TY_LLVM_BC ||
4171
1.72k
               JA.getType() == types::TY_LTO_BC) {
4172
401
      CmdArgs.push_back("-emit-llvm-bc");
4173
1.58k
    } else if (JA.getType() == types::TY_IFS ||
4174
1.58k
               JA.getType() == types::TY_IFS_CPP) {
4175
22
      StringRef ArgStr =
4176
22
          Args.hasArg(options::OPT_interface_stub_version_EQ)
4177
7
              ? Args.getLastArgValue(options::OPT_interface_stub_version_EQ)
4178
15
              : "experimental-ifs-v2";
4179
22
      CmdArgs.push_back("-emit-interface-stubs");
4180
22
      CmdArgs.push_back(
4181
22
          Args.MakeArgString(Twine("-interface-stub-version=") + ArgStr.str()));
4182
1.56k
    } else if (JA.getType() == types::TY_PP_Asm) {
4183
1.54k
      CmdArgs.push_back("-S");
4184
14
    } else if (JA.getType() == types::TY_AST) {
4185
9
      CmdArgs.push_back("-emit-pch");
4186
5
    } else if (JA.getType() == types::TY_ModuleFile) {
4187
0
      CmdArgs.push_back("-module-file-info");
4188
5
    } else if (JA.getType() == types::TY_RewrittenObjC) {
4189
5
      CmdArgs.push_back("-rewrite-objc");
4190
5
      rewriteKind = RK_NonFragile;
4191
3
    } else 
if (0
JA.getType() == types::TY_RewrittenLegacyObjC0
) {
4192
3
      CmdArgs.push_back("-rewrite-objc");
4193
3
      rewriteKind = RK_Fragile;
4194
18.4E
    } else {
4195
18.4E
      assert(JA.getType() == types::TY_PP_Asm && "Unexpected output type!");
4196
18.4E
    }
4197
29.1k
4198
    // Preserve use-list order by default when emitting bitcode, so that
4199
    // loading the bitcode up in 'opt' or 'llc' and running passes gives the
4200
    // same result as running passes here.  For LTO, we don't need to preserve
4201
    // the use-list order, since serialization to bitcode is part of the flow.
4202
29.1k
    if (JA.getType() == types::TY_LLVM_BC)
4203
264
      CmdArgs.push_back("-emit-llvm-uselists");
4204
29.1k
4205
    // Device-side jobs do not support LTO.
4206
29.1k
    bool isDeviceOffloadAction = !(JA.isDeviceOffloading(Action::OFK_None) ||
4207
393
                                   JA.isDeviceOffloading(Action::OFK_Host));
4208
29.1k
4209
29.1k
    if (D.isUsingLTO() && 
!isDeviceOffloadAction158
) {
4210
150
      Args.AddLastArg(CmdArgs, options::OPT_flto, options::OPT_flto_EQ);
4211
150
      CmdArgs.push_back("-flto-unit");
4212
150
    }
4213
29.1k
  }
4214
42.7k
4215
42.7k
  if (const Arg *A = Args.getLastArg(options::OPT_fthinlto_index_EQ)) {
4216
24
    if (!types::isLLVMIR(Input.getType()))
4217
1
      D.Diag(diag::err_drv_arg_requires_bitcode_input) << A->getAsString(Args);
4218
24
    Args.AddLastArg(CmdArgs, options::OPT_fthinlto_index_EQ);
4219
24
  }
4220
42.7k
4221
42.7k
  if (Args.getLastArg(options::OPT_fthin_link_bitcode_EQ))
4222
1
    Args.AddLastArg(CmdArgs, options::OPT_fthin_link_bitcode_EQ);
4223
42.7k
4224
42.7k
  if (Args.getLastArg(options::OPT_save_temps_EQ))
4225
284
    Args.AddLastArg(CmdArgs, options::OPT_save_temps_EQ);
4226
42.7k
4227
42.7k
  if (Args.hasFlag(options::OPT_fmemory_profile,
4228
42.7k
                   options::OPT_fno_memory_profile, false))
4229
1
    Args.AddLastArg(CmdArgs, options::OPT_fmemory_profile);
4230
42.7k
4231
  // Embed-bitcode option.
4232
  // Only white-listed flags below are allowed to be embedded.
4233
42.7k
  if (C.getDriver().embedBitcodeInObject() && 
!C.getDriver().isUsingLTO()32
&&
4234
27
      (isa<BackendJobAction>(JA) || 
isa<AssembleJobAction>(JA)26
)) {
4235
    // Add flags implied by -fembed-bitcode.
4236
12
    Args.AddLastArg(CmdArgs, options::OPT_fembed_bitcode_EQ);
4237
    // Disable all llvm IR level optimizations.
4238
12
    CmdArgs.push_back("-disable-llvm-passes");
4239
12
4240
    // Render target options.
4241
12
    TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4242
12
4243
    // reject options that shouldn't be supported in bitcode
4244
    // also reject kernel/kext
4245
12
    static const constexpr unsigned kBitcodeOptionBlacklist[] = {
4246
12
        options::OPT_mkernel,
4247
12
        options::OPT_fapple_kext,
4248
12
        options::OPT_ffunction_sections,
4249
12
        options::OPT_fno_function_sections,
4250
12
        options::OPT_fdata_sections,
4251
12
        options::OPT_fno_data_sections,
4252
12
        options::OPT_fbasic_block_sections_EQ,
4253
12
        options::OPT_funique_internal_linkage_names,
4254
12
        options::OPT_fno_unique_internal_linkage_names,
4255
12
        options::OPT_funique_section_names,
4256
12
        options::OPT_fno_unique_section_names,
4257
12
        options::OPT_funique_basic_block_section_names,
4258
12
        options::OPT_fno_unique_basic_block_section_names,
4259
12
        options::OPT_mrestrict_it,
4260
12
        options::OPT_mno_restrict_it,
4261
12
        options::OPT_mstackrealign,
4262
12
        options::OPT_mno_stackrealign,
4263
12
        options::OPT_mstack_alignment,
4264
12
        options::OPT_mcmodel_EQ,
4265
12
        options::OPT_mlong_calls,
4266
12
        options::OPT_mno_long_calls,
4267
12
        options::OPT_ggnu_pubnames,
4268
12
        options::OPT_gdwarf_aranges,
4269
12
        options::OPT_fdebug_types_section,
4270
12
        options::OPT_fno_debug_types_section,
4271
12
        options::OPT_fdwarf_directory_asm,
4272
12
        options::OPT_fno_dwarf_directory_asm,
4273
12
        options::OPT_mrelax_all,
4274
12
        options::OPT_mno_relax_all,
4275
12
        options::OPT_ftrap_function_EQ,
4276
12
        options::OPT_ffixed_r9,
4277
12
        options::OPT_mfix_cortex_a53_835769,
4278
12
        options::OPT_mno_fix_cortex_a53_835769,
4279
12
        options::OPT_ffixed_x18,
4280
12
        options::OPT_mglobal_merge,
4281
12
        options::OPT_mno_global_merge,
4282
12
        options::OPT_mred_zone,
4283
12
        options::OPT_mno_red_zone,
4284
12
        options::OPT_Wa_COMMA,
4285
12
        options::OPT_Xassembler,
4286
12
        options::OPT_mllvm,
4287
12
    };
4288
12
    for (const auto &A : Args)
4289
98
      if (llvm::find(kBitcodeOptionBlacklist, A->getOption().getID()) !=
4290
98
          std::end(kBitcodeOptionBlacklist))
4291
0
        D.Diag(diag::err_drv_unsupported_embed_bitcode) << A->getSpelling();
4292
12
4293
    // Render the CodeGen options that need to be passed.
4294
12
    if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4295
12
                      options::OPT_fno_optimize_sibling_calls))
4296
0
      CmdArgs.push_back("-mdisable-tail-calls");
4297
12
4298
12
    RenderFloatingPointOptions(TC, D, isOptimizationLevelFast(Args), Args,
4299
12
                               CmdArgs, JA);
4300
12
4301
    // Render ABI arguments
4302
12
    switch (TC.getArch()) {
4303
8
    default: break;
4304
3
    case llvm::Triple::arm:
4305
3
    case llvm::Triple::armeb:
4306
3
    case llvm::Triple::thumbeb:
4307
3
      RenderARMABI(Triple, Args, CmdArgs);
4308
3
      break;
4309
1
    case llvm::Triple::aarch64:
4310
1
    case llvm::Triple::aarch64_32:
4311
1
    case llvm::Triple::aarch64_be:
4312
1
      RenderAArch64ABI(Triple, Args, CmdArgs);
4313
1
      break;
4314
12
    }
4315
12
4316
    // Optimization level for CodeGen.
4317
12
    if (const Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4318
0
      if (A->getOption().matches(options::OPT_O4)) {
4319
0
        CmdArgs.push_back("-O3");
4320
0
        D.Diag(diag::warn_O4_is_O3);
4321
0
      } else {
4322
0
        A->render(Args, CmdArgs);
4323
0
      }
4324
0
    }
4325
12
4326
    // Input/Output file.
4327
12
    if (Output.getType() == types::TY_Dependencies) {
4328
      // Handled with other dependency code.
4329
12
    } else if (Output.isFilename()) {
4330
12
      CmdArgs.push_back("-o");
4331
12
      CmdArgs.push_back(Output.getFilename());
4332
0
    } else {
4333
0
      assert(Output.isNothing() && "Input output.");
4334
0
    }
4335
12
4336
12
    for (const auto &II : Inputs) {
4337
12
      addDashXForInput(Args, II, CmdArgs);
4338
12
      if (II.isFilename())
4339
12
        CmdArgs.push_back(II.getFilename());
4340
0
      else
4341
0
        II.getInputArg().renderAsInput(Args, CmdArgs);
4342
12
    }
4343
12
4344
12
    C.addCommand(
4345
12
        std::make_unique<Command>(JA, *this, ResponseFileSupport::AtFileUTF8(),
4346
12
                                  D.getClangProgramPath(), CmdArgs, Inputs));
4347
12
    return;
4348
12
  }
4349
42.7k
4350
42.7k
  if (C.getDriver().embedBitcodeMarkerOnly() && 
!C.getDriver().isUsingLTO()3
)
4351
3
    CmdArgs.push_back("-fembed-bitcode=marker");
4352
42.7k
4353
  // We normally speed up the clang process a bit by skipping destructors at
4354
  // exit, but when we're generating diagnostics we can rely on some of the
4355
  // cleanup.
4356
42.7k
  if (!C.isForDiagnostics())
4357
42.7k
    CmdArgs.push_back("-disable-free");
4358
42.7k
4359
#ifdef NDEBUG
4360
  const bool IsAssertBuild = false;
4361
#else
4362
42.7k
  const bool IsAssertBuild = true;
4363
42.7k
#endif
4364
42.7k
4365
  // Disable the verification pass in -asserts builds.
4366
42.7k
  if (!IsAssertBuild)
4367
0
    CmdArgs.push_back("-disable-llvm-verifier");
4368
42.7k
4369
  // Discard value names in assert builds unless otherwise specified.
4370
42.7k
  if (Args.hasFlag(options::OPT_fdiscard_value_names,
4371
2
                   options::OPT_fno_discard_value_names, !IsAssertBuild)) {
4372
2
    if (Args.hasArg(options::OPT_fdiscard_value_names) &&
4373
2
        (std::any_of(Inputs.begin(), Inputs.end(),
4374
2
                     [](const clang::driver::InputInfo &II) {
4375
2
                       return types::isLLVMIR(II.getType());
4376
1
                     }))) {
4377
1
      D.Diag(diag::warn_ignoring_fdiscard_for_bitcode);
4378
1
    }
4379
2
    CmdArgs.push_back("-discard-value-names");
4380
2
  }
4381
42.7k
4382
  // Set the main file name, so that debug info works even with
4383
  // -save-temps.
4384
42.7k
  CmdArgs.push_back("-main-file-name");
4385
42.7k
  CmdArgs.push_back(getBaseInputName(Args, Input));
4386
42.7k
4387
  // Some flags which affect the language (via preprocessor
4388
  // defines).
4389
42.7k
  if (Args.hasArg(options::OPT_static))
4390
105
    CmdArgs.push_back("-static-define");
4391
42.7k
4392
42.7k
  if (Args.hasArg(options::OPT_municode))
4393
1
    CmdArgs.push_back("-DUNICODE");
4394
42.7k
4395
42.7k
  if (isa<AnalyzeJobAction>(JA))
4396
41
    RenderAnalyzerOptions(Args, CmdArgs, Triple, Input);
4397
42.7k
4398
42.7k
  if (isa<AnalyzeJobAction>(JA) ||
4399
42.7k
      (isa<PreprocessJobAction>(JA) && 
Args.hasArg(options::OPT__analyze)4.15k
))
4400
42
    CmdArgs.push_back("-setup-static-analyzer");
4401
42.7k
4402
  // Enable compatilibily mode to avoid analyzer-config related errors.
4403
  // Since we can't access frontend flags through hasArg, let's manually iterate
4404
  // through them.
4405
42.7k
  bool FoundAnalyzerConfig = false;
4406
42.7k
  for (auto Arg : Args.filtered(options::OPT_Xclang))
4407
1.44k
    if (StringRef(Arg->getValue()) == "-analyzer-config") {
4408
8
      FoundAnalyzerConfig = true;
4409
8
      break;
4410
8
    }
4411
42.7k
  if (!FoundAnalyzerConfig)
4412
42.7k
    for (auto Arg : Args.filtered(options::OPT_Xanalyzer))
4413
4
      if (StringRef(Arg->getValue()) == "-analyzer-config") {
4414
4
        FoundAnalyzerConfig = true;
4415
4
        break;
4416
4
      }
4417
42.7k
  if (FoundAnalyzerConfig)
4418
12
    CmdArgs.push_back("-analyzer-config-compatibility-mode=true");
4419
42.7k
4420
42.7k
  CheckCodeGenerationOptions(D, Args);
4421
42.7k
4422
42.7k
  unsigned FunctionAlignment = ParseFunctionAlignment(TC, Args);
4423
42.7k
  assert(FunctionAlignment <= 31 && "function alignment will be truncated!");
4424
42.7k
  if (FunctionAlignment) {
4425
4
    CmdArgs.push_back("-function-alignment");
4426
4
    CmdArgs.push_back(Args.MakeArgString(std::to_string(FunctionAlignment)));
4427
4
  }
4428
42.7k
4429
42.7k
  llvm::Reloc::Model RelocationModel;
4430
42.7k
  unsigned PICLevel;
4431
42.7k
  bool IsPIE;
4432
42.7k
  std::tie(RelocationModel, PICLevel, IsPIE) = ParsePICArgs(TC, Args);
4433
42.7k
4434
42.7k
  bool IsROPI = RelocationModel == llvm::Reloc::ROPI ||
4435
42.7k
                RelocationModel == llvm::Reloc::ROPI_RWPI;
4436
42.7k
  bool IsRWPI = RelocationModel == llvm::Reloc::RWPI ||
4437
42.7k
                RelocationModel == llvm::Reloc::ROPI_RWPI;
4438
42.7k
4439
42.7k
  if (Args.hasArg(options::OPT_mcmse) &&
4440
15
      !Args.hasArg(options::OPT_fallow_unsupported)) {
4441
12
    if (IsROPI)
4442
2
      D.Diag(diag::err_cmse_pi_are_incompatible) << IsROPI;
4443
12
    if (IsRWPI)
4444
2
      D.Diag(diag::err_cmse_pi_are_incompatible) << !IsRWPI;
4445
12
  }
4446
42.7k
4447
42.7k
  if (IsROPI && 
types::isCXX(Input.getType())17
&&
4448
3
      !Args.hasArg(options::OPT_fallow_unsupported))
4449
2
    D.Diag(diag::err_drv_ropi_incompatible_with_cxx);
4450
42.7k
4451
42.7k
  const char *RMName = RelocationModelName(RelocationModel);
4452
42.7k
  if (
RMName42.7k
) {
4453
42.7k
    CmdArgs.push_back("-mrelocation-model");
4454
42.7k
    CmdArgs.push_back(RMName);
4455
42.7k
  }
4456
42.7k
  if (PICLevel > 0) {
4457
26.8k
    CmdArgs.push_back("-pic-level");
4458
26.0k
    CmdArgs.push_back(PICLevel == 1 ? 
"1"724
: "2");
4459
26.8k
    if (IsPIE)
4460
380
      CmdArgs.push_back("-pic-is-pie");
4461
26.8k
  }
4462
42.7k
4463
42.7k
  if (RelocationModel == llvm::Reloc::ROPI ||
4464
42.7k
      RelocationModel == llvm::Reloc::ROPI_RWPI)
4465
17
    CmdArgs.push_back("-fropi");
4466
42.7k
  if (RelocationModel == llvm::Reloc::RWPI ||
4467
42.7k
      RelocationModel == llvm::Reloc::ROPI_RWPI)
4468
12
    CmdArgs.push_back("-frwpi");
4469
42.7k
4470
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_meabi)) {
4471
28
    CmdArgs.push_back("-meabi");
4472
28
    CmdArgs.push_back(A->getValue());
4473
28
  }
4474
42.7k
4475
  // The default is -fno-semantic-interposition. We render it just because we
4476
  // require explicit -fno-semantic-interposition to infer dso_local.
4477
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_fsemantic_interposition,
4478
5
                               options::OPT_fno_semantic_interposition))
4479
5
    if (RelocationModel != llvm::Reloc::Static && 
!IsPIE4
)
4480
3
      A->render(Args, CmdArgs);
4481
42.7k
4482
42.7k
  {
4483
42.7k
    std::string Model;
4484
42.7k
    if (Arg *A = Args.getLastArg(options::OPT_mthread_model)) {
4485
6
      if (!TC.isThreadModelSupported(A->getValue()))
4486
2
        D.Diag(diag::err_drv_invalid_thread_model_for_target)
4487
2
            << A->getValue() << A->getAsString(Args);
4488
6
      Model = A->getValue();
4489
6
    } else
4490
42.7k
      Model = TC.getThreadModel();
4491
42.7k
    if (Model != "posix") {
4492
4
      CmdArgs.push_back("-mthread-model");
4493
4
      CmdArgs.push_back(Args.MakeArgString(Model));
4494
4
    }
4495
42.7k
  }
4496
42.7k
4497
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fveclib);
4498
42.7k
4499
42.7k
  if (Args.hasFlag(options::OPT_fmerge_all_constants,
4500
42.7k
                   options::OPT_fno_merge_all_constants, false))
4501
1
    CmdArgs.push_back("-fmerge-all-constants");
4502
42.7k
4503
42.7k
  if (Args.hasFlag(options::OPT_fno_delete_null_pointer_checks,
4504
42.7k
                   options::OPT_fdelete_null_pointer_checks, false))
4505
2
    CmdArgs.push_back("-fno-delete-null-pointer-checks");
4506
42.7k
4507
  // LLVM Code Generator Options.
4508
42.7k
4509
42.7k
  if (Args.hasArg(options::OPT_frewrite_map_file) ||
4510
42.7k
      Args.hasArg(options::OPT_frewrite_map_file_EQ)) {
4511
8
    for (const Arg *A : Args.filtered(options::OPT_frewrite_map_file,
4512
11
                                      options::OPT_frewrite_map_file_EQ)) {
4513
11
      StringRef Map = A->getValue();
4514
11
      if (!llvm::sys::fs::exists(Map)) {
4515
1
        D.Diag(diag::err_drv_no_such_file) << Map;
4516
10
      } else {
4517
10
        CmdArgs.push_back("-frewrite-map-file");
4518
10
        CmdArgs.push_back(A->getValue());
4519
10
        A->claim();
4520
10
      }
4521
11
    }
4522
8
  }
4523
42.7k
4524
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_Wframe_larger_than_EQ)) {
4525
2
    StringRef v = A->getValue();
4526
2
    CmdArgs.push_back("-mllvm");
4527
2
    CmdArgs.push_back(Args.MakeArgString("-warn-stack-size=" + v));
4528
2
    A->claim();
4529
2
  }
4530
42.7k
4531
42.7k
  if (!Args.hasFlag(options::OPT_fjump_tables, options::OPT_fno_jump_tables,
4532
42.7k
                    true))
4533
0
    CmdArgs.push_back("-fno-jump-tables");
4534
42.7k
4535
42.7k
  if (Args.hasFlag(options::OPT_fprofile_sample_accurate,
4536
42.7k
                   options::OPT_fno_profile_sample_accurate, false))
4537
3
    CmdArgs.push_back("-fprofile-sample-accurate");
4538
42.7k
4539
42.7k
  if (!Args.hasFlag(options::OPT_fpreserve_as_comments,
4540
42.7k
                    options::OPT_fno_preserve_as_comments, true))
4541
1
    CmdArgs.push_back("-fno-preserve-as-comments");
4542
42.7k
4543
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_mregparm_EQ)) {
4544
0
    CmdArgs.push_back("-mregparm");
4545
0
    CmdArgs.push_back(A->getValue());
4546
0
  }
4547
42.7k
4548
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_maix_struct_return,
4549
4
                               options::OPT_msvr4_struct_return)) {
4550
4
    if (TC.getArch() != llvm::Triple::ppc) {
4551
4
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4552
4
          << A->getSpelling() << RawTriple.str();
4553
0
    } else if (A->getOption().matches(options::OPT_maix_struct_return)) {
4554
0
      CmdArgs.push_back("-maix-struct-return");
4555
0
    } else {
4556
0
      assert(A->getOption().matches(options::OPT_msvr4_struct_return));
4557
0
      CmdArgs.push_back("-msvr4-struct-return");
4558
0
    }
4559
4
  }
4560
42.7k
4561
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_fpcc_struct_return,
4562
0
                               options::OPT_freg_struct_return)) {
4563
0
    if (TC.getArch() != llvm::Triple::x86) {
4564
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4565
0
          << A->getSpelling() << RawTriple.str();
4566
0
    } else if (A->getOption().matches(options::OPT_fpcc_struct_return)) {
4567
0
      CmdArgs.push_back("-fpcc-struct-return");
4568
0
    } else {
4569
0
      assert(A->getOption().matches(options::OPT_freg_struct_return));
4570
0
      CmdArgs.push_back("-freg-struct-return");
4571
0
    }
4572
0
  }
4573
42.7k
4574
42.7k
  if (Args.hasFlag(options::OPT_mrtd, options::OPT_mno_rtd, false))
4575
0
    CmdArgs.push_back("-fdefault-calling-conv=stdcall");
4576
42.7k
4577
42.7k
  if (Args.hasArg(options::OPT_fenable_matrix)) {
4578
    // enable-matrix is needed by both the LangOpts and by LLVM.
4579
14
    CmdArgs.push_back("-fenable-matrix");
4580
14
    CmdArgs.push_back("-mllvm");
4581
14
    CmdArgs.push_back("-enable-matrix");
4582
14
  }
4583
42.7k
4584
42.7k
  CodeGenOptions::FramePointerKind FPKeepKind =
4585
42.7k
                  getFramePointerKind(Args, RawTriple);
4586
42.7k
  const char *FPKeepKindStr = nullptr;
4587
42.7k
  switch (FPKeepKind) {
4588
7.87k
  case CodeGenOptions::FramePointerKind::None:
4589
7.87k
    FPKeepKindStr = "-mframe-pointer=none";
4590
7.87k
    break;
4591
1.25k
  case CodeGenOptions::FramePointerKind::NonLeaf:
4592
1.25k
    FPKeepKindStr = "-mframe-pointer=non-leaf";
4593
1.25k
    break;
4594
33.6k
  case CodeGenOptions::FramePointerKind::All:
4595
33.6k
    FPKeepKindStr = "-mframe-pointer=all";
4596
33.6k
    break;
4597
42.7k
  }
4598
42.7k
  assert(FPKeepKindStr && "unknown FramePointerKind");
4599
42.7k
  CmdArgs.push_back(FPKeepKindStr);
4600
42.7k
4601
42.7k
  if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
4602
42.7k
                    options::OPT_fno_zero_initialized_in_bss, true))
4603
1
    CmdArgs.push_back("-fno-zero-initialized-in-bss");
4604
42.7k
4605
42.7k
  bool OFastEnabled = isOptimizationLevelFast(Args);
4606
  // If -Ofast is the optimization level, then -fstrict-aliasing should be
4607
  // enabled.  This alias option is being used to simplify the hasFlag logic.
4608
42.7k
  OptSpecifier StrictAliasingAliasOption =
4609
42.7k
      OFastEnabled ? 
options::OPT_Ofast25
: options::OPT_fstrict_aliasing;
4610
  // We turn strict aliasing off by default if we're in CL mode, since MSVC
4611
  // doesn't do any TBAA.
4612
42.7k
  bool TBAAOnByDefault = !D.IsCLMode();
4613
42.7k
  if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
4614
42.7k
                    options::OPT_fno_strict_aliasing, TBAAOnByDefault))
4615
538
    CmdArgs.push_back("-relaxed-aliasing");
4616
42.7k
  if (!Args.hasFlag(options::OPT_fstruct_path_tbaa,
4617
42.7k
                    options::OPT_fno_struct_path_tbaa))
4618
0
    CmdArgs.push_back("-no-struct-path-tbaa");
4619
42.7k
  if (Args.hasFlag(options::OPT_fstrict_enums, options::OPT_fno_strict_enums,
4620
42.7k
                   false))
4621
0
    CmdArgs.push_back("-fstrict-enums");
4622
42.7k
  if (!Args.hasFlag(options::OPT_fstrict_return, options::OPT_fno_strict_return,
4623
42.7k
                    true))
4624
1
    CmdArgs.push_back("-fno-strict-return");
4625
42.7k
  if (Args.hasFlag(options::OPT_fallow_editor_placeholders,
4626
42.7k
                   options::OPT_fno_allow_editor_placeholders, false))
4627
996
    CmdArgs.push_back("-fallow-editor-placeholders");
4628
42.7k
  if (Args.hasFlag(options::OPT_fstrict_vtable_pointers,
4629
42.7k
                   options::OPT_fno_strict_vtable_pointers,
4630
42.7k
                   false))
4631
0
    CmdArgs.push_back("-fstrict-vtable-pointers");
4632
42.7k
  if (Args.hasFlag(options::OPT_fforce_emit_vtables,
4633
42.7k
                   options::OPT_fno_force_emit_vtables,
4634
42.7k
                   false))
4635
0
    CmdArgs.push_back("-fforce-emit-vtables");
4636
42.7k
  if (!Args.hasFlag(options::OPT_foptimize_sibling_calls,
4637
42.7k
                    options::OPT_fno_optimize_sibling_calls))
4638
1
    CmdArgs.push_back("-mdisable-tail-calls");
4639
42.7k
  if (Args.hasFlag(options::OPT_fno_escaping_block_tail_calls,
4640
42.7k
                   options::OPT_fescaping_block_tail_calls, false))
4641
1
    CmdArgs.push_back("-fno-escaping-block-tail-calls");
4642
42.7k
4643
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_ffine_grained_bitfield_accesses,
4644
42.7k
                  options::OPT_fno_fine_grained_bitfield_accesses);
4645
42.7k
4646
  // Handle segmented stacks.
4647
42.7k
  if (Args.hasArg(options::OPT_fsplit_stack))
4648
5
    CmdArgs.push_back("-split-stacks");
4649
42.7k
4650
42.7k
  RenderFloatingPointOptions(TC, D, OFastEnabled, Args, CmdArgs, JA);
4651
42.7k
4652
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_mdouble_EQ)) {
4653
2
    if (TC.getArch() == llvm::Triple::avr)
4654
1
      A->render(Args, CmdArgs);
4655
1
    else
4656
1
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4657
1
          << A->getAsString(Args) << TripleStr;
4658
2
  }
4659
42.7k
4660
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_LongDouble_Group)) {
4661
14
    if (TC.getTriple().isX86())
4662
5
      A->render(Args, CmdArgs);
4663
9
    else if ((TC.getArch() == llvm::Triple::ppc || 
TC.getTriple().isPPC64()6
) &&
4664
7
             (A->getOption().getID() != options::OPT_mlong_double_80))
4665
6
      A->render(Args, CmdArgs);
4666
3
    else
4667
3
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4668
3
          << A->getAsString(Args) << TripleStr;
4669
14
  }
4670
42.7k
4671
  // Decide whether to use verbose asm. Verbose assembly is the default on
4672
  // toolchains which have the integrated assembler on by default.
4673
42.7k
  bool IsIntegratedAssemblerDefault = TC.IsIntegratedAssemblerDefault();
4674
42.7k
  if (!Args.hasFlag(options::OPT_fverbose_asm, options::OPT_fno_verbose_asm,
4675
42.7k
                    IsIntegratedAssemblerDefault))
4676
1.05k
    CmdArgs.push_back("-fno-verbose-asm");
4677
42.7k
4678
42.7k
  if (!TC.useIntegratedAs())
4679
943
    CmdArgs.push_back("-no-integrated-as");
4680
42.7k
4681
42.7k
  if (Args.hasArg(options::OPT_fdebug_pass_structure)) {
4682
0
    CmdArgs.push_back("-mdebug-pass");
4683
0
    CmdArgs.push_back("Structure");
4684
0
  }
4685
42.7k
  if (Args.hasArg(options::OPT_fdebug_pass_arguments)) {
4686
0
    CmdArgs.push_back("-mdebug-pass");
4687
0
    CmdArgs.push_back("Arguments");
4688
0
  }
4689
42.7k
4690
  // Enable -mconstructor-aliases except on darwin, where we have to work around
4691
  // a linker bug (see <rdar://problem/7651567>), and CUDA device code, where
4692
  // aliases aren't supported. Similarly, aliases aren't yet supported for AIX.
4693
42.7k
  if (!RawTriple.isOSDarwin() && 
!RawTriple.isNVPTX()24.7k
&&
!RawTriple.isOSAIX()24.3k
)
4694
24.3k
    CmdArgs.push_back("-mconstructor-aliases");
4695
42.7k
4696
  // Darwin's kernel doesn't support guard variables; just die if we
4697
  // try to use them.
4698
42.7k
  if (KernelOrKext && 
RawTriple.isOSDarwin()23
)
4699
20
    CmdArgs.push_back("-fforbid-guard-variables");
4700
42.7k
4701
42.7k
  if (Args.hasFlag(options::OPT_mms_bitfields, options::OPT_mno_ms_bitfields,
4702
97
                   Triple.isWindowsGNUEnvironment())) {
4703
97
    CmdArgs.push_back("-mms-bitfields");
4704
97
  }
4705
42.7k
4706
42.7k
  if (Args.hasFlag(options::OPT_mpie_copy_relocations,
4707
42.7k
                   options::OPT_mno_pie_copy_relocations,
4708
0
                   false)) {
4709
0
    CmdArgs.push_back("-mpie-copy-relocations");
4710
0
  }
4711
42.7k
4712
42.7k
  if (Args.hasFlag(options::OPT_fno_plt, options::OPT_fplt, false)) {
4713
0
    CmdArgs.push_back("-fno-plt");
4714
0
  }
4715
42.7k
4716
  // -fhosted is default.
4717
  // TODO: Audit uses of KernelOrKext and see where it'd be more appropriate to
4718
  // use Freestanding.
4719
42.7k
  bool Freestanding =
4720
42.7k
      Args.hasFlag(options::OPT_ffreestanding, options::OPT_fhosted, false) ||
4721
42.7k
      KernelOrKext;
4722
42.7k
  if (Freestanding)
4723
74
    CmdArgs.push_back("-ffreestanding");
4724
42.7k
4725
  // This is a coarse approximation of what llvm-gcc actually does, both
4726
  // -fasynchronous-unwind-tables and -fnon-call-exceptions interact in more
4727
  // complicated ways.
4728
42.7k
  bool AsynchronousUnwindTables =
4729
42.7k
      Args.hasFlag(options::OPT_fasynchronous_unwind_tables,
4730
42.7k
                   options::OPT_fno_asynchronous_unwind_tables,
4731
42.7k
                   (TC.IsUnwindTablesDefault(Args) ||
4732
14.5k
                    TC.getSanitizerArgs().needsUnwindTables()) &&
4733
28.2k
                       !Freestanding);
4734
42.7k
  if (Args.hasFlag(options::OPT_funwind_tables, options::OPT_fno_unwind_tables,
4735
42.7k
                   AsynchronousUnwindTables))
4736
28.2k
    CmdArgs.push_back("-munwind-tables");
4737
42.7k
4738
  // Prepare `-aux-target-cpu` and `-aux-target-feature` unless
4739
  // `--gpu-use-aux-triple-only` is specified.
4740
42.7k
  if (!Args.getLastArg(options::OPT_gpu_use_aux_triple_only) &&
4741
42.7k
      ((IsCuda && 
JA.isDeviceOffloading(Action::OFK_Cuda)495
) ||
4742
42.4k
       (IsHIP && 
JA.isDeviceOffloading(Action::OFK_HIP)270
))) {
4743
439
    const ArgList &HostArgs =
4744
439
        C.getArgsForToolChain(nullptr, StringRef(), Action::OFK_None);
4745
439
    std::string HostCPU =
4746
439
        getCPUName(HostArgs, *TC.getAuxTriple(), /*FromAs*/ false);
4747
439
    if (!HostCPU.empty()) {
4748
439
      CmdArgs.push_back("-aux-target-cpu");
4749
439
      CmdArgs.push_back(Args.MakeArgString(HostCPU));
4750
439
    }
4751
439
    getTargetFeatures(D, *TC.getAuxTriple(), HostArgs, CmdArgs,
4752
439
                      /*ForAS*/ false, /*IsAux*/ true);
4753
439
  }
4754
42.7k
4755
42.7k
  TC.addClangTargetOptions(Args, CmdArgs, JA.getOffloadingDeviceKind());
4756
42.7k
4757
  // FIXME: Handle -mtune=.
4758
42.7k
  (void)Args.hasArg(options::OPT_mtune_EQ);
4759
42.7k
4760
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_mcmodel_EQ)) {
4761
21
    StringRef CM = A->getValue();
4762
21
    if (CM == "small" || 
CM == "kernel"16
||
CM == "medium"11
||
CM == "large"5
||
4763
2
        CM == "tiny")
4764
20
      A->render(Args, CmdArgs);
4765
1
    else
4766
1
      D.Diag(diag::err_drv_invalid_argument_to_option)
4767
1
          << CM << A->getOption().getName();
4768
21
  }
4769
42.7k
4770
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_mtls_size_EQ)) {
4771
7
    StringRef Value = A->getValue();
4772
7
    unsigned TLSSize = 0;
4773
7
    Value.getAsInteger(10, TLSSize);
4774
7
    if (!Triple.isAArch64() || 
!Triple.isOSBinFormatELF()6
)
4775
2
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4776
2
          << A->getOption().getName() << TripleStr;
4777
7
    if (TLSSize != 12 && 
TLSSize != 246
&&
TLSSize != 323
&&
TLSSize != 482
)
4778
1
      D.Diag(diag::err_drv_invalid_int_value)
4779
1
          << A->getOption().getName() << Value;
4780
7
    Args.AddLastArg(CmdArgs, options::OPT_mtls_size_EQ);
4781
7
  }
4782
42.7k
4783
  // Add the target cpu
4784
42.7k
  std::string CPU = getCPUName(Args, Triple, /*FromAs*/ false);
4785
42.7k
  if (!CPU.empty()) {
4786
42.2k
    CmdArgs.push_back("-target-cpu");
4787
42.2k
    CmdArgs.push_back(Args.MakeArgString(CPU));
4788
42.2k
  }
4789
42.7k
4790
42.7k
  RenderTargetOptions(Triple, Args, KernelOrKext, CmdArgs);
4791
42.7k
4792
  // These two are potentially updated by AddClangCLArgs.
4793
42.7k
  codegenoptions::DebugInfoKind DebugInfoKind = codegenoptions::NoDebugInfo;
4794
42.7k
  bool EmitCodeView = false;
4795
42.7k
4796
  // Add clang-cl arguments.
4797
42.7k
  types::ID InputType = Input.getType();
4798
42.7k
  if (D.IsCLMode())
4799
538
    AddClangCLArgs(Args, InputType, CmdArgs, &DebugInfoKind, &EmitCodeView);
4800
42.7k
4801
42.7k
  DwarfFissionKind DwarfFission;
4802
42.7k
  RenderDebugOptions(TC, D, RawTriple, Args, EmitCodeView, CmdArgs,
4803
42.7k
                     DebugInfoKind, DwarfFission);
4804
42.7k
4805
  // Add the split debug info name to the command lines here so we
4806
  // can propagate it to the backend.
4807
42.7k
  bool SplitDWARF = (DwarfFission != DwarfFissionKind::None) &&
4808
28
                    TC.getTriple().isOSBinFormatELF() &&
4809
23
                    (isa<AssembleJobAction>(JA) || 
isa<CompileJobAction>(JA)10
||
4810
10
                     isa<BackendJobAction>(JA));
4811
42.7k
  if (SplitDWARF) {
4812
22
    const char *SplitDWARFOut = SplitDebugName(Args, Input, Output);
4813
22
    CmdArgs.push_back("-split-dwarf-file");
4814
22
    CmdArgs.push_back(SplitDWARFOut);
4815
22
    if (DwarfFission == DwarfFissionKind::Split) {
4816
20
      CmdArgs.push_back("-split-dwarf-output");
4817
20
      CmdArgs.push_back(SplitDWARFOut);
4818
20
    }
4819
22
  }
4820
42.7k
4821
  // Pass the linker version in use.
4822
42.7k
  if (Arg *
A42.7k
= Args.getLastArg(options::OPT_mlinker_version_EQ)) {
4823
42.7k
    CmdArgs.push_back("-target-linker-version");
4824
42.7k
    CmdArgs.push_back(A->getValue());
4825
42.7k
  }
4826
42.7k
4827
  // Explicitly error on some things we know we don't support and can't just
4828
  // ignore.
4829
42.7k
  if (
!Args.hasArg(options::OPT_fallow_unsupported)42.7k
) {
4830
42.7k
    Arg *Unsupported;
4831
42.7k
    if (types::isCXX(InputType) && 
RawTriple.isOSDarwin()28.4k
&&
4832
12.5k
        TC.getArch() == llvm::Triple::x86) {
4833
22
      if ((Unsupported = Args.getLastArg(options::OPT_fapple_kext)) ||
4834
22
          (Unsupported = Args.getLastArg(options::OPT_mkernel)))
4835
1
        D.Diag(diag::err_drv_clang_unsupported_opt_cxx_darwin_i386)
4836
1
            << Unsupported->getOption().getName();
4837
22
    }
4838
    // The faltivec option has been superseded by the maltivec option.
4839
42.7k
    if ((Unsupported = Args.getLastArg(options::OPT_faltivec)))
4840
1
      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4841
1
          << Unsupported->getOption().getName()
4842
1
          << "please use -maltivec and include altivec.h explicitly";
4843
42.7k
    if ((Unsupported = Args.getLastArg(options::OPT_fno_altivec)))
4844
1
      D.Diag(diag::err_drv_clang_unsupported_opt_faltivec)
4845
1
          << Unsupported->getOption().getName() << "please use -mno-altivec";
4846
42.7k
  }
4847
42.7k
4848
42.7k
  Args.AddAllArgs(CmdArgs, options::OPT_v);
4849
42.7k
4850
42.7k
  if (Args.getLastArg(options::OPT_H)) {
4851
1
    CmdArgs.push_back("-H");
4852
1
    CmdArgs.push_back("-sys-header-deps");
4853
1
  }
4854
42.7k
4855
42.7k
  if (D.CCPrintHeaders && 
!D.CCGenDiagnostics11
) {
4856
6
    CmdArgs.push_back("-header-include-file");
4857
0
    CmdArgs.push_back(D.CCPrintHeadersFilename ? D.CCPrintHeadersFilename
4858
6
                                               : "-");
4859
6
    CmdArgs.push_back("-sys-header-deps");
4860
6
  }
4861
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_P);
4862
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_print_ivar_layout);
4863
42.7k
4864
42.7k
  if (D.CCLogDiagnostics && 
!D.CCGenDiagnostics12
) {
4865
7
    CmdArgs.push_back("-diagnostic-log-file");
4866
2
    CmdArgs.push_back(D.CCLogDiagnosticsFilename ? D.CCLogDiagnosticsFilename
4867
5
                                                 : "-");
4868
7
  }
4869
42.7k
4870
  // Give the gen diagnostics more chances to succeed, by avoiding intentional
4871
  // crashes.
4872
42.7k
  if (D.CCGenDiagnostics)
4873
27
    CmdArgs.push_back("-disable-pragma-debug-crash");
4874
42.7k
4875
42.7k
  bool UseSeparateSections = isUseSeparateSections(Triple);
4876
42.7k
4877
42.7k
  if (Args.hasFlag(options::OPT_ffunction_sections,
4878
40
                   options::OPT_fno_function_sections, UseSeparateSections)) {
4879
40
    CmdArgs.push_back("-ffunction-sections");
4880
40
  }
4881
42.7k
4882
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_fbasic_block_sections_EQ)) {
4883
6
    if (Triple.isX86() && 
Triple.isOSBinFormatELF()5
) {
4884
4
      StringRef Val = A->getValue();
4885
4
      if (Val != "all" && 
Val != "labels"3
&&
Val != "none"2
&&
4886
1
          !(Val.startswith("list=") && llvm::sys::fs::exists(Val.substr(5))))
4887
0
        D.Diag(diag::err_drv_invalid_value)
4888
0
            << A->getAsString(Args) << A->getValue();
4889
4
      else
4890
4
        A->render(Args, CmdArgs);
4891
2
    } else {
4892
2
      D.Diag(diag::err_drv_unsupported_opt_for_target)
4893
2
          << A->getAsString(Args) << TripleStr;
4894
2
    }
4895
6
  }
4896
42.7k
4897
42.7k
  if (Args.hasFlag(options::OPT_fdata_sections, options::OPT_fno_data_sections,
4898
18
                   UseSeparateSections)) {
4899
18
    CmdArgs.push_back("-fdata-sections");
4900
18
  }
4901
42.7k
4902
42.7k
  if (!Args.hasFlag(options::OPT_funique_section_names,
4903
42.7k
                    options::OPT_fno_unique_section_names, true))
4904
1
    CmdArgs.push_back("-fno-unique-section-names");
4905
42.7k
4906
42.7k
  if (Args.hasFlag(options::OPT_funique_internal_linkage_names,
4907
42.7k
                   options::OPT_fno_unique_internal_linkage_names, false))
4908
1
    CmdArgs.push_back("-funique-internal-linkage-names");
4909
42.7k
4910
42.7k
  if (Args.hasFlag(options::OPT_funique_basic_block_section_names,
4911
42.7k
                   options::OPT_fno_unique_basic_block_section_names, false))
4912
1
    CmdArgs.push_back("-funique-basic-block-section-names");
4913
42.7k
4914
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_finstrument_functions,
4915
42.7k
                  options::OPT_finstrument_functions_after_inlining,
4916
42.7k
                  options::OPT_finstrument_function_entry_bare);
4917
42.7k
4918
  // NVPTX/AMDGCN doesn't support PGO or coverage. There's no runtime support
4919
  // for sampling, overhead of call arc collection is way too high and there's
4920
  // no way to collect the output.
4921
42.7k
  if (!Triple.isNVPTX() && 
!Triple.isAMDGCN()42.4k
)
4922
42.0k
    addPGOAndCoverageFlags(TC, C, D, Output, Args, CmdArgs);
4923
42.7k
4924
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_fclang_abi_compat_EQ);
4925
42.7k
4926
  // Add runtime flag for PS4 when PGO, coverage, or sanitizers are enabled.
4927
42.7k
  if (RawTriple.isPS4CPU() &&
4928
128
      !Args.hasArg(options::OPT_nostdlib, options::OPT_nodefaultlibs)) {
4929
122
    PS4cpu::addProfileRTArgs(TC, Args, CmdArgs);
4930
122
    PS4cpu::addSanitizerArgs(TC, CmdArgs);
4931
122
  }
4932
42.7k
4933
  // Pass options for controlling the default header search paths.
4934
42.7k
  if (Args.hasArg(options::OPT_nostdinc)) {
4935
55
    CmdArgs.push_back("-nostdsysteminc");
4936
55
    CmdArgs.push_back("-nobuiltininc");
4937
42.7k
  } else {
4938
42.7k
    if (Args.hasArg(options::OPT_nostdlibinc))
4939
15
      CmdArgs.push_back("-nostdsysteminc");
4940
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_nostdincxx);
4941
42.7k
    Args.AddLastArg(CmdArgs, options::OPT_nobuiltininc);
4942
42.7k
  }
4943
42.7k
4944
  // Pass the path to compiler resource files.
4945
42.7k
  CmdArgs.push_back("-resource-dir");
4946
42.7k
  CmdArgs.push_back(D.ResourceDir.c_str());
4947
42.7k
4948
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_working_directory);
4949
42.7k
4950
42.7k
  RenderARCMigrateToolOptions(D, Args, CmdArgs);
4951
42.7k
4952
  // Add preprocessing options like -I, -D, etc. if we are using the
4953
  // preprocessor.
4954
  //
4955
  // FIXME: Support -fpreprocessed
4956
42.7k
  if (types::getPreprocessedType(InputType) != types::TY_INVALID)
4957
42.4k
    AddPreprocessingOptions(C, JA, D, Args, CmdArgs, Output, Inputs);
4958
42.7k
4959
  // Don't warn about "clang -c -DPIC -fPIC test.i" because libtool.m4 assumes
4960
  // that "The compiler can only warn and ignore the option if not recognized".
4961
  // When building with ccache, it will pass -D options to clang even on
4962
  // preprocessed inputs and configure concludes that -fPIC is not supported.
4963
42.7k
  Args.ClaimAllArgs(options::OPT_D);
4964
42.7k
4965
  // Manually translate -O4 to -O3; let clang reject others.
4966
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_O_Group)) {
4967
6.47k
    if (A->getOption().matches(options::OPT_O4)) {
4968
7
      CmdArgs.push_back("-O3");
4969
7
      D.Diag(diag::warn_O4_is_O3);
4970
6.46k
    } else {
4971
6.46k
      A->render(Args, CmdArgs);
4972
6.46k
    }
4973
6.47k
  }
4974
42.7k
4975
  // Warn about ignored options to clang.
4976
42.7k
  for (const Arg *A :
4977
130
       Args.filtered(options::OPT_clang_ignored_gcc_optimization_f_Group)) {
4978
130
    D.Diag(diag::warn_ignored_gcc_optimization) << A->getAsString(Args);
4979
130
    A->claim();
4980
130
  }
4981
42.7k
4982
42.7k
  for (const Arg *A :
4983
4
       Args.filtered(options::OPT_clang_ignored_legacy_options_Group)) {
4984
4
    D.Diag(diag::warn_ignored_clang_option) << A->getAsString(Args);
4985
4
    A->claim();
4986
4
  }
4987
42.7k
4988
42.7k
  claimNoWarnArgs(Args);
4989
42.7k
4990
42.7k
  Args.AddAllArgs(CmdArgs, options::OPT_R_Group);
4991
42.7k
4992
42.7k
  Args.AddAllArgs(CmdArgs, options::OPT_W_Group);
4993
42.7k
  if (Args.hasFlag(options::OPT_pedantic, options::OPT_no_pedantic, false))
4994
7
    CmdArgs.push_back("-pedantic");
4995
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_pedantic_errors);
4996
42.7k
  Args.AddLastArg(CmdArgs, options::OPT_w);
4997
42.7k
4998
  // Fixed point flags
4999
42.7k
  if (Args.hasFlag(options::OPT_ffixed_point, options::OPT_fno_fixed_point,
5000
42.7k
                   /*Default=*/false))
5001
22
    Args.AddLastArg(CmdArgs, options::OPT_ffixed_point);
5002
42.7k
5003
  // Handle -{std, ansi, trigraphs} -- take the last of -{std, ansi}
5004
  // (-ansi is equivalent to -std=c89 or -std=c++98).
5005
  //
5006
  // If a std is supplied, only add -trigraphs if it follows the
5007
  // option.
5008
42.7k
  bool ImplyVCPPCXXVer = false;
5009
42.7k
  const Arg *Std = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi);
5010
42.7k
  if (Std) {
5011
25.5k
    if (Std->getOption().matches(options::OPT_ansi))
5012
5
      if (types::isCXX(InputType))
5013
1
        CmdArgs.push_back("-std=c++98");
5014
4
      else
5015
4
        CmdArgs.push_back("-std=c89");
5016
25.5k
    else
5017
25.5k
      Std->render(Args, CmdArgs);
5018
25.5k
5019
    // If -f(no-)trigraphs appears after the language standard flag, honor it.
5020
25.5k
    if (Arg *A = Args.getLastArg(options::OPT_std_EQ, options::OPT_ansi,
5021
25.5k
                                 options::OPT_ftrigraphs,
5022
25.5k
                                 options::OPT_fno_trigraphs))
5023
25.5k
      if (A != Std)
5024
3
        A->render(Args, CmdArgs);
5025
17.1k
  } else {
5026
    // Honor -std-default.
5027
    //
5028
    // FIXME: Clang doesn't correctly handle -std= when the input language
5029
    // doesn't match. For the time being just ignore this for C++ inputs;
5030
    // eventually we want to do all the standard defaulting here instead of
5031
    // splitting it between the driver and clang -cc1.
5032
17.1k
    if (!types::isCXX(InputType))
5033
12.3k
      Args.AddAllArgsTranslated(CmdArgs, options::OPT_std_default_EQ, "-std=",
5034
12.3k
                                /*Joined=*/true);
5035
4.86k
    else if (IsWindowsMSVC)
5036
161
      ImplyVCPPCXXVer = true;
5037
17.1k
5038
17.1k
    Args.AddLastArg(CmdArgs, options::OPT_ftrigraphs,
5039
17.1k
                    options::OPT_fno_trigraphs);
5040
17.1k
5041
    // HIP headers has minimum C++ standard requirements. Therefore set the
5042
    // default language standard.
5043
17.1k
    if (IsHIP)
5044
264
      CmdArgs.push_back(IsWindowsMSVC ? 
"-std=c++14"6
:
"-std=c++11"258
);
5045
17.1k
  }
5046
42.7k
5047
  // GCC's behavior for -Wwrite-strings is a bit strange:
5048
  //  * In C, this "warning flag" changes the types of string literals from
5049
  //    'char[N]' to 'const char[N]', and thus triggers an unrelated warning
5050
  //    for the discarded qualifier.
5051
  //  * In C++, this is just a normal warning flag.
5052
  //
5053
  // Implementing this warning correctly in C is hard, so we follow GCC's
5054
  // behavior for now. FIXME: Directly diagnose uses of a string literal as
5055
  // a non-const char* in C, rather than using this crude hack.
5056
42.7k
  if (!types::isCXX(InputType)) {
5057
    // FIXME: This should behave just like a warning flag, and thus should also
5058
    // respect -Weverything, -Wno-everything, -Werror=write-strings, and so on.
5059
14.3k
    Arg *WriteStrings =
5060
14.3k
        Args.getLastArg(options::OPT_Wwrite_strings,
5061
14.3k
                        options::OPT_Wno_write_strings, options::OPT_w);
5062
14.3k
    if (WriteStrings &&
5063
137
        WriteStrings->getOption().matches(options::OPT_Wwrite_strings))
5064
1
      CmdArgs.push_back("-fconst-strings");
5065
14.3k
  }
5066
42.7k
5067
  // GCC provides a macro definition '__DEPRECATED' when -Wdeprecated is active
5068
  // during C++ compilation, which it is by default. GCC keeps this define even
5069
  // in the presence of '-w', match this behavior bug-for-bug.
5070
42.7k
  if (types::isCXX(InputType) &&
5071
28.4k
      Args.hasFlag(options::OPT_Wdeprecated, options::OPT_Wno_deprecated,
5072
28.4k
                   true)) {
5073
28.4k
    CmdArgs.push_back("-fdeprecated-macro");
5074
28.4k
  }
5075
42.7k
5076
  // Translate GCC's misnamer '-fasm' arguments to '-fgnu-keywords'.
5077
42.7k
  if (Arg *Asm = Args.getLastArg(options::OPT_fasm, options::OPT_fno_asm)) {
5078
2
    if (Asm->getOption().matches(options::OPT_fasm))
5079
1
      CmdArgs.push_back("-fgnu-keywords");
5080
1
    else
5081
1
      CmdArgs.push_back("-fno-gnu-keywords");
5082
2
  }
5083
42.7k
5084
42.7k
  if (ShouldDisableDwarfDirectory(Args, TC))
5085
943
    CmdArgs.push_back("-fno-dwarf-directory-asm");
5086
42.7k
5087
42.7k
  if (!ShouldEnableAutolink(Args, TC, JA))
5088
449
    CmdArgs.push_back("-fno-autolink");
5089
42.7k
5090
  // Add in -fdebug-compilation-dir if necessary.
5091
42.7k
  addDebugCompDirArg(Args, CmdArgs, D.getVFS());
5092
42.7k
5093
42.7k
  addDebugPrefixMapArg(D, Args, CmdArgs);
5094
42.7k
5095
42.7k
  if (Arg *A = Args.getLastArg(options::OPT_ftemplate_depth_,
5096
2
                               options::OPT_ftemplate_depth_EQ)) {
5097
2
    CmdArgs.push_back("-ftemplate-depth");
5098
2
    CmdArgs.push_back(A->getValue());
5099