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 "clang/Driver/Driver.h"
11#include "clang/Options/Options.h"
12#include "llvm/ADT/STLExtras.h"
13#include "llvm/ADT/StringExtras.h"
14#include "llvm/ADT/StringMap.h"
15#include "llvm/Option/ArgList.h"
16#include "llvm/TargetParser/Host.h"
17#include "llvm/TargetParser/X86TargetParser.h"
18
19using namespace clang::driver;
20using namespace clang::driver::tools;
21using namespace clang;
22using namespace llvm::opt;
23
24std::string x86::getX86TargetCPU(const Driver &D, const ArgList &Args,
25 const llvm::Triple &Triple) {
26 if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ)) {
27 StringRef CPU = A->getValue();
28 if (CPU != "native")
29 return std::string(CPU);
30
31 // FIXME: Reject attempts to use -march=native unless the target matches
32 // the host.
33 CPU = llvm::sys::getHostCPUName();
34 if (!CPU.empty() && CPU != "generic")
35 return std::string(CPU);
36 }
37
38 if (const Arg *A = Args.getLastArg(Ids: 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 llvm::StringMap<StringRef> ArchMap({
43 {"AVX", "sandybridge"},
44 {"AVX2", "haswell"},
45 {"AVX512F", "knl"},
46 {"AVX512", "skylake-avx512"},
47 {"AVX10.1", "sapphirerapids"},
48 {"AVX10.2", "sapphirerapids"},
49 });
50 if (Triple.getArch() == llvm::Triple::x86) {
51 // 32-bit-only /arch: flags.
52 ArchMap.insert(List: {
53 {"IA32", "i386"},
54 {"SSE", "pentium3"},
55 {"SSE2", "pentium4"},
56 });
57 }
58 StringRef CPU = ArchMap.lookup(Key: A->getValue());
59 if (CPU.empty()) {
60 std::vector<StringRef> ValidArchs{ArchMap.keys().begin(),
61 ArchMap.keys().end()};
62 sort(C&: ValidArchs);
63 D.Diag(DiagID: diag::warn_drv_invalid_arch_name_with_suggestion)
64 << A->getValue() << (Triple.getArch() == llvm::Triple::x86)
65 << join(R&: ValidArchs, Separator: ", ");
66 }
67 return std::string(CPU);
68 }
69
70 // Select the default CPU if none was given (or detection failed).
71
72 if (!Triple.isX86())
73 return ""; // This routine is only handling x86 targets.
74
75 bool Is64Bit = Triple.getArch() == llvm::Triple::x86_64;
76
77 // FIXME: Need target hooks.
78 if (Triple.isOSDarwin()) {
79 if (Triple.getArchName() == "x86_64h")
80 return "core-avx2";
81 // macosx10.12 drops support for all pre-Penryn Macs.
82 // Simulators can still run on 10.11 though, like Xcode.
83 if (Triple.isMacOSX() && !Triple.isOSVersionLT(Major: 10, Minor: 12))
84 return "penryn";
85
86 if (Triple.isDriverKit())
87 return "nehalem";
88
89 // The oldest x86_64 Macs have core2/Merom; the oldest x86 Macs have Yonah.
90 return Is64Bit ? "core2" : "yonah";
91 }
92
93 // Set up default CPU name for PS4/PS5 compilers.
94 if (Triple.isPS4())
95 return "btver2";
96 if (Triple.isPS5())
97 return "znver2";
98
99 // On Android use targets compatible with gcc
100 if (Triple.isAndroid())
101 return Is64Bit ? "x86-64" : "i686";
102
103 // Everything else goes to x86-64 in 64-bit mode.
104 if (Is64Bit)
105 return "x86-64";
106
107 switch (Triple.getOS()) {
108 case llvm::Triple::NetBSD:
109 return "i486";
110 case llvm::Triple::Haiku:
111 case llvm::Triple::OpenBSD:
112 return "i586";
113 default:
114 // Fallback to p4.
115 return "pentium4";
116 }
117}
118
119void x86::getX86TargetFeatures(const Driver &D, const llvm::Triple &Triple,
120 const ArgList &Args,
121 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 if (const Arg *A = Args.getLastArg(Ids: options::OPT_mabi_EQ)) {
125 StringRef DefaultAbi =
126 (Triple.isOSWindows() || Triple.isUEFI()) ? "ms" : "sysv";
127 if (A->getValue() != DefaultAbi)
128 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
129 << A->getSpelling() << Triple.getTriple();
130 }
131
132 // If -march=native, autodetect the feature list.
133 if (const Arg *A = Args.getLastArg(Ids: options::OPT_march_EQ)) {
134 if (StringRef(A->getValue()) == "native") {
135 for (auto &F : llvm::sys::getHostCPUFeatures())
136 Features.push_back(
137 x: Args.MakeArgString(Str: (F.second ? "+" : "-") + F.first()));
138 }
139 }
140
141 if (Triple.getArchName() == "x86_64h") {
142 // x86_64h implies quite a few of the more modern subtarget features
143 // for Haswell class CPUs, but not all of them. Opt-out of a few.
144 Features.push_back(x: "-rdrnd");
145 Features.push_back(x: "-aes");
146 Features.push_back(x: "-pclmul");
147 Features.push_back(x: "-rtm");
148 Features.push_back(x: "-fsgsbase");
149 }
150
151 const llvm::Triple::ArchType ArchType = Triple.getArch();
152
153 // Add features to be compatible with gcc for Android.
154 if (Triple.isAndroid()) {
155 if (ArchType == llvm::Triple::x86_64) {
156 Features.push_back(x: "+sse4.2");
157 Features.push_back(x: "+popcnt");
158 Features.push_back(x: "+cx16");
159 } else
160 Features.push_back(x: "+ssse3");
161 }
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 auto SpectreOpt = options::ID::OPT_INVALID;
170 if (Args.hasArgNoClaim(Ids: options::OPT_mretpoline, Ids: options::OPT_mno_retpoline,
171 Ids: options::OPT_mspeculative_load_hardening,
172 Ids: options::OPT_mno_speculative_load_hardening)) {
173 if (Args.hasFlag(Pos: options::OPT_mretpoline, Neg: options::OPT_mno_retpoline,
174 Default: false)) {
175 Features.push_back(x: "+retpoline-indirect-calls");
176 Features.push_back(x: "+retpoline-indirect-branches");
177 SpectreOpt = options::OPT_mretpoline;
178 } else if (Args.hasFlag(Pos: options::OPT_mspeculative_load_hardening,
179 Neg: options::OPT_mno_speculative_load_hardening,
180 Default: false)) {
181 // On x86, speculative load hardening relies on at least using retpolines
182 // for indirect calls.
183 Features.push_back(x: "+retpoline-indirect-calls");
184 SpectreOpt = options::OPT_mspeculative_load_hardening;
185 }
186 } else if (Args.hasFlag(Pos: options::OPT_mretpoline_external_thunk,
187 Neg: options::OPT_mno_retpoline_external_thunk, Default: false)) {
188 // FIXME: Add a warning about failing to specify `-mretpoline` and
189 // eventually switch to an error here.
190 Features.push_back(x: "+retpoline-indirect-calls");
191 Features.push_back(x: "+retpoline-indirect-branches");
192 SpectreOpt = options::OPT_mretpoline_external_thunk;
193 }
194
195 auto LVIOpt = options::ID::OPT_INVALID;
196 if (Args.hasFlag(Pos: options::OPT_mlvi_hardening, Neg: options::OPT_mno_lvi_hardening,
197 Default: false)) {
198 Features.push_back(x: "+lvi-load-hardening");
199 Features.push_back(x: "+lvi-cfi"); // load hardening implies CFI protection
200 LVIOpt = options::OPT_mlvi_hardening;
201 } else if (Args.hasFlag(Pos: options::OPT_mlvi_cfi, Neg: options::OPT_mno_lvi_cfi,
202 Default: false)) {
203 Features.push_back(x: "+lvi-cfi");
204 LVIOpt = options::OPT_mlvi_cfi;
205 }
206
207 if (Args.hasFlag(Pos: options::OPT_m_seses, Neg: options::OPT_mno_seses, Default: false)) {
208 if (LVIOpt == options::OPT_mlvi_hardening)
209 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
210 << D.getOpts().getOptionName(id: options::OPT_mlvi_hardening)
211 << D.getOpts().getOptionName(id: options::OPT_m_seses);
212
213 if (SpectreOpt != options::ID::OPT_INVALID)
214 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
215 << D.getOpts().getOptionName(id: SpectreOpt)
216 << D.getOpts().getOptionName(id: options::OPT_m_seses);
217
218 Features.push_back(x: "+seses");
219 if (!Args.hasArg(Ids: options::OPT_mno_lvi_cfi)) {
220 Features.push_back(x: "+lvi-cfi");
221 LVIOpt = options::OPT_mlvi_cfi;
222 }
223 }
224
225 if (SpectreOpt != options::ID::OPT_INVALID &&
226 LVIOpt != options::ID::OPT_INVALID) {
227 D.Diag(DiagID: diag::err_drv_argument_not_allowed_with)
228 << D.getOpts().getOptionName(id: SpectreOpt)
229 << D.getOpts().getOptionName(id: LVIOpt);
230 }
231
232 enum class EGPRFeature { Unknown, Disabled, Enabled };
233 EGPRFeature EGPROpt = EGPRFeature::Unknown;
234 // Now add any that the user explicitly requested on the command line,
235 // which may override the defaults.
236 for (const Arg *A : Args.filtered(Ids: options::OPT_m_x86_Features_Group,
237 Ids: options::OPT_mgeneral_regs_only)) {
238 StringRef Name = A->getOption().getName();
239 A->claim();
240
241 // Skip over "-m".
242 assert(Name.starts_with("m") && "Invalid feature name.");
243 Name = Name.substr(Start: 1);
244
245 // Replace -mgeneral-regs-only with -x87, -mmx, -sse
246 if (A->getOption().getID() == options::OPT_mgeneral_regs_only) {
247 Features.insert(position: Features.end(), l: {"-x87", "-mmx", "-sse"});
248 continue;
249 }
250
251 bool IsNegative = Name.starts_with(Prefix: "no-");
252
253 bool Not64Bit = ArchType != llvm::Triple::x86_64;
254 if (Not64Bit && Name == "uintr")
255 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
256 << A->getSpelling() << Triple.getTriple();
257
258 if (IsNegative)
259 Name = Name.substr(Start: 3);
260
261 if (A->getOption().matches(ID: options::OPT_mapxf) ||
262 A->getOption().matches(ID: options::OPT_mno_apxf)) {
263 if (IsNegative) {
264 EGPROpt = EGPRFeature::Disabled;
265 } else {
266 EGPROpt = EGPRFeature::Enabled;
267 if (Not64Bit)
268 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
269 << StringRef("-mapxf") << Triple.getTriple();
270 }
271 continue;
272 }
273
274 if (A->getOption().matches(ID: options::OPT_mapx_features_EQ) ||
275 A->getOption().matches(ID: options::OPT_mno_apx_features_EQ)) {
276 if (Not64Bit && !IsNegative)
277 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
278 << StringRef("-mapx-features=") << Triple.getTriple();
279
280 for (StringRef Value : A->getValues()) {
281 if (Value != "egpr" && Value != "push2pop2" && Value != "ppx" &&
282 Value != "ndd" && Value != "ccmp" && Value != "nf" &&
283 Value != "cf" && Value != "zu" && Value != "jmpabs")
284 D.Diag(DiagID: clang::diag::err_drv_unsupported_option_argument)
285 << A->getSpelling() << Value;
286
287 if (Value == "egpr") {
288 EGPROpt = IsNegative ? EGPRFeature::Disabled : EGPRFeature::Enabled;
289 }
290
291 Features.push_back(
292 x: Args.MakeArgString(Str: (IsNegative ? "-" : "+") + Value));
293 }
294 continue;
295 }
296
297 if (Name == "egpr") {
298 EGPROpt = IsNegative ? EGPRFeature::Disabled : EGPRFeature::Enabled;
299 }
300 Features.push_back(x: Args.MakeArgString(Str: (IsNegative ? "-" : "+") + Name));
301 }
302
303 // Enable/disable straight line speculation hardening.
304 if (Arg *A = Args.getLastArg(Ids: options::OPT_mharden_sls_EQ)) {
305 StringRef Scope = A->getValue();
306 if (Scope == "all") {
307 Features.push_back(x: "+harden-sls-ijmp");
308 Features.push_back(x: "+harden-sls-ret");
309 } else if (Scope == "return") {
310 Features.push_back(x: "+harden-sls-ret");
311 } else if (Scope == "indirect-jmp") {
312 Features.push_back(x: "+harden-sls-ijmp");
313 } else if (Scope != "none") {
314 D.Diag(DiagID: diag::err_drv_unsupported_option_argument)
315 << A->getSpelling() << Scope;
316 }
317 }
318
319 // -mno-gather, -mno-scatter support
320 if (Args.hasArg(Ids: options::OPT_mno_gather))
321 Features.push_back(x: "+prefer-no-gather");
322 if (Args.hasArg(Ids: options::OPT_mno_scatter))
323 Features.push_back(x: "+prefer-no-scatter");
324 if (Args.hasArg(Ids: options::OPT_mapx_inline_asm_use_gpr32))
325 Features.push_back(x: "+inline-asm-use-gpr32");
326
327 // Warn for removed 3dnow support
328 if (const Arg *A =
329 Args.getLastArg(Ids: options::OPT_m3dnowa, Ids: options::OPT_mno_3dnowa,
330 Ids: options::OPT_mno_3dnow)) {
331 if (A->getOption().matches(ID: options::OPT_m3dnowa))
332 D.Diag(DiagID: diag::warn_drv_clang_unsupported) << A->getAsString(Args);
333 }
334 if (const Arg *A =
335 Args.getLastArg(Ids: options::OPT_m3dnow, Ids: options::OPT_mno_3dnow)) {
336 if (A->getOption().matches(ID: options::OPT_m3dnow))
337 D.Diag(DiagID: diag::warn_drv_clang_unsupported) << A->getAsString(Args);
338 }
339
340 // Handle features corresponding to "-ffixed-X" options
341 if (Args.hasArg(Ids: options::OPT_ffixed_edi)) {
342 if (ArchType != llvm::Triple::x86)
343 D.Diag(DiagID: diag::err_drv_unsupported_opt_for_target)
344 << "-ffixed-edi" << Triple.getTriple();
345 else
346 Features.push_back(x: "+reserve-edi");
347 }
348#define RESERVE_REG(REG) \
349 if (Args.hasArg(options::OPT_ffixed_##REG)) \
350 Features.push_back("+reserve-" #REG);
351 RESERVE_REG(r8)
352 RESERVE_REG(r9)
353 RESERVE_REG(r10)
354 RESERVE_REG(r11)
355 RESERVE_REG(r12)
356 RESERVE_REG(r13)
357 RESERVE_REG(r14)
358 RESERVE_REG(r15)
359#undef RESERVE_REG
360
361 bool NeedDetectEGPR = Args.hasArg(
362 Ids: options::OPT_ffixed_r16, Ids: options::OPT_ffixed_r17, Ids: options::OPT_ffixed_r18,
363 Ids: options::OPT_ffixed_r19, Ids: options::OPT_ffixed_r20, Ids: options::OPT_ffixed_r21,
364 Ids: options::OPT_ffixed_r22, Ids: options::OPT_ffixed_r23, Ids: options::OPT_ffixed_r24,
365 Ids: options::OPT_ffixed_r25, Ids: options::OPT_ffixed_r26, Ids: options::OPT_ffixed_r27,
366 Ids: options::OPT_ffixed_r28, Ids: options::OPT_ffixed_r29, Ids: options::OPT_ffixed_r30,
367 Ids: options::OPT_ffixed_r31);
368 if (NeedDetectEGPR && EGPROpt == EGPRFeature::Unknown &&
369 ArchType == llvm::Triple::x86_64) {
370 SmallVector<StringRef, 16> CPUFeatures;
371 llvm::X86::getFeaturesForCPU(CPU: getX86TargetCPU(D, Args, Triple), Features&: CPUFeatures);
372 EGPROpt = llvm::is_contained(Range&: CPUFeatures, Element: "+egpr") ? EGPRFeature::Enabled
373 : EGPRFeature::Disabled;
374 }
375#define RESERVE_EGPR(REG) \
376 if (Args.hasArg(options::OPT_ffixed_##REG)) { \
377 if (EGPROpt != EGPRFeature::Enabled) \
378 D.Diag(diag::err_drv_unsupported_opt_for_target) \
379 << "-ffixed-" #REG << Triple.getTriple(); \
380 else \
381 Features.push_back("+reserve-" #REG); \
382 }
383 RESERVE_EGPR(r16)
384 RESERVE_EGPR(r17)
385 RESERVE_EGPR(r18)
386 RESERVE_EGPR(r19)
387 RESERVE_EGPR(r20)
388 RESERVE_EGPR(r21)
389 RESERVE_EGPR(r22)
390 RESERVE_EGPR(r23)
391 RESERVE_EGPR(r24)
392 RESERVE_EGPR(r25)
393 RESERVE_EGPR(r26)
394 RESERVE_EGPR(r27)
395 RESERVE_EGPR(r28)
396 RESERVE_EGPR(r29)
397 RESERVE_EGPR(r30)
398 RESERVE_EGPR(r31)
399#undef RESERVE_EGPR
400}
401