Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/Driver/ToolChains/Arch/X86.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- X86.cpp - X86 Helpers for Tools ------------------------*- 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 "X86.h"
10
#include "ToolChains/CommonArgs.h"
11
#include "clang/Driver/Driver.h"
12
#include "clang/Driver/DriverDiagnostic.h"
13
#include "clang/Driver/Options.h"
14
#include "llvm/ADT/StringExtras.h"
15
#include "llvm/ADT/StringMap.h"
16
#include "llvm/Option/ArgList.h"
17
#include "llvm/TargetParser/Host.h"
18
19
using namespace clang::driver;
20
using namespace clang::driver::tools;
21
using namespace clang;
22
using namespace llvm::opt;
23
24
std::string x86::getX86TargetCPU(const Driver &D, const ArgList &Args,
25
0
                                 const llvm::Triple &Triple) {
26
0
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
27
0
    StringRef CPU = A->getValue();
28
0
    if (CPU != "native")
29
0
      return std::string(CPU);
30
31
    // FIXME: Reject attempts to use -march=native unless the target matches
32
    // the host.
33
0
    CPU = llvm::sys::getHostCPUName();
34
0
    if (!CPU.empty() && CPU != "generic")
35
0
      return std::string(CPU);
36
0
  }
37
38
0
  if (const Arg *A = Args.getLastArg(options::OPT__SLASH_arch)) {
39
    // Mapping built by looking at lib/Basic's X86TargetInfo::initFeatureMap().
40
    // The keys are case-sensitive; this matches link.exe.
41
    // 32-bit and 64-bit /arch: flags.
42
0
    llvm::StringMap<StringRef> ArchMap({
43
0
        {"AVX", "sandybridge"},
44
0
        {"AVX2", "haswell"},
45
0
        {"AVX512F", "knl"},
46
0
        {"AVX512", "skylake-avx512"},
47
0
    });
48
0
    if (Triple.getArch() == llvm::Triple::x86) {
49
      // 32-bit-only /arch: flags.
50
0
      ArchMap.insert({
51
0
          {"IA32", "i386"},
52
0
          {"SSE", "pentium3"},
53
0
          {"SSE2", "pentium4"},
54
0
      });
55
0
    }
56
0
    StringRef CPU = ArchMap.lookup(A->getValue());
57
0
    if (CPU.empty()) {
58
0
      std::vector<StringRef> ValidArchs{ArchMap.keys().begin(),
59
0
                                        ArchMap.keys().end()};
60
0
      sort(ValidArchs);
61
0
      D.Diag(diag::warn_drv_invalid_arch_name_with_suggestion)
62
0
          << A->getValue() << (Triple.getArch() == llvm::Triple::x86)
63
0
          << join(ValidArchs, ", ");
64
0
    }
65
0
    return std::string(CPU);
66
0
  }
67
68
  // Select the default CPU if none was given (or detection failed).
69
70
0
  if (!Triple.isX86())
71
0
    return ""; // This routine is only handling x86 targets.
72
73
0
  bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
74
75
  // FIXME: Need target hooks.
76
0
  if (Triple.isOSDarwin()) {
77
0
    if (Triple.getArchName() == "x86_64h")
78
0
      return "core-avx2";
79
    // macosx10.12 drops support for all pre-Penryn Macs.
80
    // Simulators can still run on 10.11 though, like Xcode.
81
0
    if (Triple.isMacOSX() && !Triple.isOSVersionLT(10, 12))
82
0
      return "penryn";
83
84
0
    if (Triple.isDriverKit())
85
0
      return "nehalem";
86
87
    // The oldest x86_64 Macs have core2/Merom; the oldest x86 Macs have Yonah.
88
0
    return Is64Bit ? "core2" : "yonah";
89
0
  }
90
91
  // Set up default CPU name for PS4/PS5 compilers.
92
0
  if (Triple.isPS4())
93
0
    return "btver2";
94
0
  if (Triple.isPS5())
95
0
    return "znver2";
96
97
  // On Android use targets compatible with gcc
98
0
  if (Triple.isAndroid())
99
0
    return Is64Bit ? "x86-64" : "i686";
100
101
  // Everything else goes to x86-64 in 64-bit mode.
102
0
  if (Is64Bit)
103
0
    return "x86-64";
104
105
0
  switch (Triple.getOS()) {
106
0
  case llvm::Triple::NetBSD:
107
0
    return "i486";
108
0
  case llvm::Triple::Haiku:
109
0
  case llvm::Triple::OpenBSD:
110
0
    return "i586";
111
0
  case llvm::Triple::FreeBSD:
112
0
    return "i686";
113
0
  default:
114
    // Fallback to p4.
115
0
    return "pentium4";
116
0
  }
117
0
}
118
119
void x86::getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
120
                               const ArgList &Args,
121
0
                               std::vector<StringRef> &Features) {
122
  // Claim and report unsupported -mabi=. Note: we don't support "sysv_abi" or
123
  // "ms_abi" as default function attributes.
124
0
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mabi_EQ)) {
125
0
    StringRef DefaultAbi = Triple.isOSWindows() ? "ms" : "sysv";
126
0
    if (A->getValue() != DefaultAbi)
127
0
      D.Diag(diag::err_drv_unsupported_opt_for_target)
128
0
          << A->getSpelling() << Triple.getTriple();
129
0
  }
130
131
  // If -march=native, autodetect the feature list.
132
0
  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_march_EQ)) {
133
0
    if (StringRef(A->getValue()) == "native") {
134
0
      llvm::StringMap<bool> HostFeatures;
135
0
      if (llvm::sys::getHostCPUFeatures(HostFeatures))
136
0
        for (auto &F : HostFeatures)
137
0
          Features.push_back(
138
0
              Args.MakeArgString((F.second ? "+" : "-") + F.first()));
139
0
    }
140
0
  }
141
142
0
  if (Triple.getArchName() == "x86_64h") {
143
    // x86_64h implies quite a few of the more modern subtarget features
144
    // for Haswell class CPUs, but not all of them. Opt-out of a few.
145
0
    Features.push_back("-rdrnd");
146
0
    Features.push_back("-aes");
147
0
    Features.push_back("-pclmul");
148
0
    Features.push_back("-rtm");
149
0
    Features.push_back("-fsgsbase");
150
0
  }
151
152
0
  const llvm::Triple::ArchType ArchType = Triple.getArch();
153
  // Add features to be compatible with gcc for Android.
154
0
  if (Triple.isAndroid()) {
155
0
    if (ArchType == llvm::Triple::x86_64) {
156
0
      Features.push_back("+sse4.2");
157
0
      Features.push_back("+popcnt");
158
0
      Features.push_back("+cx16");
159
0
    } else
160
0
      Features.push_back("+ssse3");
161
0
  }
162
163
  // Translate the high level `-mretpoline` flag to the specific target feature
164
  // flags. We also detect if the user asked for retpoline external thunks but
165
  // failed to ask for retpolines themselves (through any of the different
166
  // flags). This is a bit hacky but keeps existing usages working. We should
167
  // consider deprecating this and instead warn if the user requests external
168
  // retpoline thunks and *doesn't* request some form of retpolines.
169
0
  auto SpectreOpt = clang::driver::options::ID::OPT_INVALID;
170
0
  if (Args.hasArgNoClaim(options::OPT_mretpoline, options::OPT_mno_retpoline,
171
0
                         options::OPT_mspeculative_load_hardening,
172
0
                         options::OPT_mno_speculative_load_hardening)) {
173
0
    if (Args.hasFlag(options::OPT_mretpoline, options::OPT_mno_retpoline,
174
0
                     false)) {
175
0
      Features.push_back("+retpoline-indirect-calls");
176
0
      Features.push_back("+retpoline-indirect-branches");
177
0
      SpectreOpt = options::OPT_mretpoline;
178
0
    } else if (Args.hasFlag(options::OPT_mspeculative_load_hardening,
179
0
                            options::OPT_mno_speculative_load_hardening,
180
0
                            false)) {
181
      // On x86, speculative load hardening relies on at least using retpolines
182
      // for indirect calls.
183
0
      Features.push_back("+retpoline-indirect-calls");
184
0
      SpectreOpt = options::OPT_mspeculative_load_hardening;
185
0
    }
186
0
  } else if (Args.hasFlag(options::OPT_mretpoline_external_thunk,
187
0
                          options::OPT_mno_retpoline_external_thunk, false)) {
188
    // FIXME: Add a warning about failing to specify `-mretpoline` and
189
    // eventually switch to an error here.
190
0
    Features.push_back("+retpoline-indirect-calls");
191
0
    Features.push_back("+retpoline-indirect-branches");
192
0
    SpectreOpt = options::OPT_mretpoline_external_thunk;
193
0
  }
194
195
0
  auto LVIOpt = clang::driver::options::ID::OPT_INVALID;
196
0
  if (Args.hasFlag(options::OPT_mlvi_hardening, options::OPT_mno_lvi_hardening,
197
0
                   false)) {
198
0
    Features.push_back("+lvi-load-hardening");
199
0
    Features.push_back("+lvi-cfi"); // load hardening implies CFI protection
200
0
    LVIOpt = options::OPT_mlvi_hardening;
201
0
  } else if (Args.hasFlag(options::OPT_mlvi_cfi, options::OPT_mno_lvi_cfi,
202
0
                          false)) {
203
0
    Features.push_back("+lvi-cfi");
204
0
    LVIOpt = options::OPT_mlvi_cfi;
205
0
  }
206
207
0
  if (Args.hasFlag(options::OPT_m_seses, options::OPT_mno_seses, false)) {
208
0
    if (LVIOpt == options::OPT_mlvi_hardening)
209
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
210
0
          << D.getOpts().getOptionName(options::OPT_mlvi_hardening)
211
0
          << D.getOpts().getOptionName(options::OPT_m_seses);
212
213
0
    if (SpectreOpt != clang::driver::options::ID::OPT_INVALID)
214
0
      D.Diag(diag::err_drv_argument_not_allowed_with)
215
0
          << D.getOpts().getOptionName(SpectreOpt)
216
0
          << D.getOpts().getOptionName(options::OPT_m_seses);
217
218
0
    Features.push_back("+seses");
219
0
    if (!Args.hasArg(options::OPT_mno_lvi_cfi)) {
220
0
      Features.push_back("+lvi-cfi");
221
0
      LVIOpt = options::OPT_mlvi_cfi;
222
0
    }
223
0
  }
224
225
0
  if (SpectreOpt != clang::driver::options::ID::OPT_INVALID &&
226
0
      LVIOpt != clang::driver::options::ID::OPT_INVALID) {
227
0
    D.Diag(diag::err_drv_argument_not_allowed_with)
228
0
        << D.getOpts().getOptionName(SpectreOpt)
229
0
        << D.getOpts().getOptionName(LVIOpt);
230
0
  }
231
232
0
  for (const Arg *A : Args.filtered(options::OPT_m_x86_AVX10_Features_Group)) {
233
0
    StringRef Name = A->getOption().getName();
234
0
    A->claim();
235
236
    // Skip over "-m".
237
0
    assert(Name.starts_with("m") && "Invalid feature name.");
238
0
    Name = Name.substr(1);
239
240
0
    bool IsNegative = Name.consume_front("no-");
241
242
0
#ifndef NDEBUG
243
0
    assert(Name.starts_with("avx10.") && "Invalid AVX10 feature name.");
244
0
    StringRef Version, Width;
245
0
    std::tie(Version, Width) = Name.substr(6).split('-');
246
0
    assert(Version == "1" && "Invalid AVX10 feature name.");
247
0
    assert((Width == "256" || Width == "512") && "Invalid AVX10 feature name.");
248
0
#endif
249
250
0
    Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
251
0
  }
252
253
  // Now add any that the user explicitly requested on the command line,
254
  // which may override the defaults.
255
0
  for (const Arg *A : Args.filtered(options::OPT_m_x86_Features_Group,
256
0
                                    options::OPT_mgeneral_regs_only)) {
257
0
    StringRef Name = A->getOption().getName();
258
0
    A->claim();
259
260
    // Skip over "-m".
261
0
    assert(Name.starts_with("m") && "Invalid feature name.");
262
0
    Name = Name.substr(1);
263
264
    // Replace -mgeneral-regs-only with -x87, -mmx, -sse
265
0
    if (A->getOption().getID() == options::OPT_mgeneral_regs_only) {
266
0
      Features.insert(Features.end(), {"-x87", "-mmx", "-sse"});
267
0
      continue;
268
0
    }
269
270
0
    bool IsNegative = Name.starts_with("no-");
271
0
    if (A->getOption().matches(options::OPT_mapx_features_EQ) ||
272
0
        A->getOption().matches(options::OPT_mno_apx_features_EQ)) {
273
274
0
      for (StringRef Value : A->getValues()) {
275
0
        if (Value == "egpr" || Value == "push2pop2" || Value == "ppx" ||
276
0
            Value == "ndd" || Value == "ccmp" || Value == "cf") {
277
0
          Features.push_back(
278
0
              Args.MakeArgString((IsNegative ? "-" : "+") + Value));
279
0
          continue;
280
0
        }
281
0
        D.Diag(clang::diag::err_drv_unsupported_option_argument)
282
0
            << A->getSpelling() << Value;
283
0
      }
284
0
      continue;
285
0
    }
286
0
    if (IsNegative)
287
0
      Name = Name.substr(3);
288
0
    Features.push_back(Args.MakeArgString((IsNegative ? "-" : "+") + Name));
289
0
  }
290
291
  // Enable/disable straight line speculation hardening.
292
0
  if (Arg *A = Args.getLastArg(options::OPT_mharden_sls_EQ)) {
293
0
    StringRef Scope = A->getValue();
294
0
    if (Scope == "all") {
295
0
      Features.push_back("+harden-sls-ijmp");
296
0
      Features.push_back("+harden-sls-ret");
297
0
    } else if (Scope == "return") {
298
0
      Features.push_back("+harden-sls-ret");
299
0
    } else if (Scope == "indirect-jmp") {
300
0
      Features.push_back("+harden-sls-ijmp");
301
0
    } else if (Scope != "none") {
302
0
      D.Diag(diag::err_drv_unsupported_option_argument)
303
0
          << A->getSpelling() << Scope;
304
0
    }
305
0
  }
306
307
  // -mno-gather, -mno-scatter support
308
0
  if (Args.hasArg(options::OPT_mno_gather))
309
0
    Features.push_back("+prefer-no-gather");
310
0
  if (Args.hasArg(options::OPT_mno_scatter))
311
0
    Features.push_back("+prefer-no-scatter");
312
0
}