Coverage Report

Created: 2020-02-25 14:32

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