1 //===--- ARM.cpp - ARM (not AArch64) 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 "ARM.h"
10 #include "clang/Driver/Driver.h"
11 #include "clang/Driver/DriverDiagnostic.h"
12 #include "clang/Driver/Options.h"
13 #include "llvm/ADT/StringSwitch.h"
14 #include "llvm/Option/ArgList.h"
15 #include "llvm/Support/TargetParser.h"
16 #include "llvm/Support/Host.h"
17 
18 using namespace clang::driver;
19 using namespace clang::driver::tools;
20 using namespace clang;
21 using namespace llvm::opt;
22 
23 // Get SubArch (vN).
24 int arm::getARMSubArchVersionNumber(const llvm::Triple &Triple) {
25   llvm::StringRef Arch = Triple.getArchName();
26   return llvm::ARM::parseArchVersion(Arch);
27 }
28 
29 // True if M-profile.
30 bool arm::isARMMProfile(const llvm::Triple &Triple) {
31   llvm::StringRef Arch = Triple.getArchName();
32   return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::M;
33 }
34 
35 // True if A-profile.
36 bool arm::isARMAProfile(const llvm::Triple &Triple) {
37   llvm::StringRef Arch = Triple.getArchName();
38   return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::A;
39 }
40 
41 // Get Arch/CPU from args.
42 void arm::getARMArchCPUFromArgs(const ArgList &Args, llvm::StringRef &Arch,
43                                 llvm::StringRef &CPU, bool FromAs) {
44   if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ))
45     CPU = A->getValue();
46   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
47     Arch = A->getValue();
48   if (!FromAs)
49     return;
50 
51   for (const Arg *A :
52        Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
53     // Use getValues because -Wa can have multiple arguments
54     // e.g. -Wa,-mcpu=foo,-mcpu=bar
55     for (StringRef Value : A->getValues()) {
56       if (Value.startswith("-mcpu="))
57         CPU = Value.substr(6);
58       if (Value.startswith("-march="))
59         Arch = Value.substr(7);
60     }
61   }
62 }
63 
64 // Handle -mhwdiv=.
65 // FIXME: Use ARMTargetParser.
66 static void getARMHWDivFeatures(const Driver &D, const Arg *A,
67                                 const ArgList &Args, StringRef HWDiv,
68                                 std::vector<StringRef> &Features) {
69   uint64_t HWDivID = llvm::ARM::parseHWDiv(HWDiv);
70   if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
71     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
72 }
73 
74 // Handle -mfpu=.
75 static unsigned getARMFPUFeatures(const Driver &D, const Arg *A,
76                                   const ArgList &Args, StringRef FPU,
77                                   std::vector<StringRef> &Features) {
78   unsigned FPUID = llvm::ARM::parseFPU(FPU);
79   if (!llvm::ARM::getFPUFeatures(FPUID, Features))
80     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
81   return FPUID;
82 }
83 
84 // Decode ARM features from string like +[no]featureA+[no]featureB+...
85 static bool DecodeARMFeatures(const Driver &D, StringRef text, StringRef CPU,
86                               llvm::ARM::ArchKind ArchKind,
87                               std::vector<StringRef> &Features,
88                               unsigned &ArgFPUID) {
89   SmallVector<StringRef, 8> Split;
90   text.split(Split, StringRef("+"), -1, false);
91 
92   for (StringRef Feature : Split) {
93     if (!appendArchExtFeatures(CPU, ArchKind, Feature, Features, ArgFPUID))
94       return false;
95   }
96   return true;
97 }
98 
99 static void DecodeARMFeaturesFromCPU(const Driver &D, StringRef CPU,
100                                      std::vector<StringRef> &Features) {
101   CPU = CPU.split("+").first;
102   if (CPU != "generic") {
103     llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
104     uint64_t Extension = llvm::ARM::getDefaultExtensions(CPU, ArchKind);
105     llvm::ARM::getExtensionFeatures(Extension, Features);
106   }
107 }
108 
109 // Check if -march is valid by checking if it can be canonicalised and parsed.
110 // getARMArch is used here instead of just checking the -march value in order
111 // to handle -march=native correctly.
112 static void checkARMArchName(const Driver &D, const Arg *A, const ArgList &Args,
113                              llvm::StringRef ArchName, llvm::StringRef CPUName,
114                              std::vector<StringRef> &Features,
115                              const llvm::Triple &Triple, unsigned &ArgFPUID) {
116   std::pair<StringRef, StringRef> Split = ArchName.split("+");
117 
118   std::string MArch = arm::getARMArch(ArchName, Triple);
119   llvm::ARM::ArchKind ArchKind = llvm::ARM::parseArch(MArch);
120   if (ArchKind == llvm::ARM::ArchKind::INVALID ||
121       (Split.second.size() && !DecodeARMFeatures(D, Split.second, CPUName,
122                                                  ArchKind, Features, ArgFPUID)))
123     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
124 }
125 
126 // Check -mcpu=. Needs ArchName to handle -mcpu=generic.
127 static void checkARMCPUName(const Driver &D, const Arg *A, const ArgList &Args,
128                             llvm::StringRef CPUName, llvm::StringRef ArchName,
129                             std::vector<StringRef> &Features,
130                             const llvm::Triple &Triple, unsigned &ArgFPUID) {
131   std::pair<StringRef, StringRef> Split = CPUName.split("+");
132 
133   std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
134   llvm::ARM::ArchKind ArchKind =
135     arm::getLLVMArchKindForARM(CPU, ArchName, Triple);
136   if (ArchKind == llvm::ARM::ArchKind::INVALID ||
137       (Split.second.size() &&
138        !DecodeARMFeatures(D, Split.second, CPU, ArchKind, Features, ArgFPUID)))
139     D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
140 }
141 
142 bool arm::useAAPCSForMachO(const llvm::Triple &T) {
143   // The backend is hardwired to assume AAPCS for M-class processors, ensure
144   // the frontend matches that.
145   return T.getEnvironment() == llvm::Triple::EABI ||
146          T.getEnvironment() == llvm::Triple::EABIHF ||
147          T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
148 }
149 
150 // Select mode for reading thread pointer (-mtp=soft/cp15).
151 arm::ReadTPMode arm::getReadTPMode(const Driver &D, const ArgList &Args) {
152   if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
153     arm::ReadTPMode ThreadPointer =
154         llvm::StringSwitch<arm::ReadTPMode>(A->getValue())
155             .Case("cp15", ReadTPMode::Cp15)
156             .Case("soft", ReadTPMode::Soft)
157             .Default(ReadTPMode::Invalid);
158     if (ThreadPointer != ReadTPMode::Invalid)
159       return ThreadPointer;
160     if (StringRef(A->getValue()).empty())
161       D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
162     else
163       D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
164     return ReadTPMode::Invalid;
165   }
166   return ReadTPMode::Soft;
167 }
168 
169 void arm::setArchNameInTriple(const Driver &D, const ArgList &Args,
170                               types::ID InputType, llvm::Triple &Triple) {
171   StringRef MCPU, MArch;
172   if (const Arg *A = Args.getLastArg(options::OPT_mcpu_EQ))
173     MCPU = A->getValue();
174   if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
175     MArch = A->getValue();
176 
177   std::string CPU = Triple.isOSBinFormatMachO()
178                         ? tools::arm::getARMCPUForMArch(MArch, Triple).str()
179                         : tools::arm::getARMTargetCPU(MCPU, MArch, Triple);
180   StringRef Suffix = tools::arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
181 
182   bool IsBigEndian = Triple.getArch() == llvm::Triple::armeb ||
183                      Triple.getArch() == llvm::Triple::thumbeb;
184   // Handle pseudo-target flags '-mlittle-endian'/'-EL' and
185   // '-mbig-endian'/'-EB'.
186   if (Arg *A = Args.getLastArg(options::OPT_mlittle_endian,
187                                options::OPT_mbig_endian)) {
188     IsBigEndian = !A->getOption().matches(options::OPT_mlittle_endian);
189   }
190   std::string ArchName = IsBigEndian ? "armeb" : "arm";
191 
192   // FIXME: Thumb should just be another -target-feaure, not in the triple.
193   bool IsMProfile =
194       llvm::ARM::parseArchProfile(Suffix) == llvm::ARM::ProfileKind::M;
195   bool ThumbDefault = IsMProfile ||
196                       // Thumb2 is the default for V7 on Darwin.
197                       (llvm::ARM::parseArchVersion(Suffix) == 7 &&
198                        Triple.isOSBinFormatMachO()) ||
199                       // FIXME: this is invalid for WindowsCE
200                       Triple.isOSWindows();
201 
202   // Check if ARM ISA was explicitly selected (using -mno-thumb or -marm) for
203   // M-Class CPUs/architecture variants, which is not supported.
204   bool ARMModeRequested =
205       !Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault);
206   if (IsMProfile && ARMModeRequested) {
207     if (MCPU.size())
208       D.Diag(diag::err_cpu_unsupported_isa) << CPU << "ARM";
209     else
210       D.Diag(diag::err_arch_unsupported_isa)
211           << tools::arm::getARMArch(MArch, Triple) << "ARM";
212   }
213 
214   // Check to see if an explicit choice to use thumb has been made via
215   // -mthumb. For assembler files we must check for -mthumb in the options
216   // passed to the assembler via -Wa or -Xassembler.
217   bool IsThumb = false;
218   if (InputType != types::TY_PP_Asm)
219     IsThumb =
220         Args.hasFlag(options::OPT_mthumb, options::OPT_mno_thumb, ThumbDefault);
221   else {
222     // Ideally we would check for these flags in
223     // CollectArgsForIntegratedAssembler but we can't change the ArchName at
224     // that point.
225     llvm::StringRef WaMArch, WaMCPU;
226     for (const auto *A :
227          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
228       for (StringRef Value : A->getValues()) {
229         // There is no assembler equivalent of -mno-thumb, -marm, or -mno-arm.
230         if (Value == "-mthumb")
231           IsThumb = true;
232         else if (Value.startswith("-march="))
233           WaMArch = Value.substr(7);
234         else if (Value.startswith("-mcpu="))
235           WaMCPU = Value.substr(6);
236       }
237     }
238 
239     if (WaMCPU.size() || WaMArch.size()) {
240       // The way this works means that we prefer -Wa,-mcpu's architecture
241       // over -Wa,-march. Which matches the compiler behaviour.
242       Suffix = tools::arm::getLLVMArchSuffixForARM(WaMCPU, WaMArch, Triple);
243     }
244   }
245 
246   // Assembly files should start in ARM mode, unless arch is M-profile, or
247   // -mthumb has been passed explicitly to the assembler. Windows is always
248   // thumb.
249   if (IsThumb || IsMProfile || Triple.isOSWindows()) {
250     if (IsBigEndian)
251       ArchName = "thumbeb";
252     else
253       ArchName = "thumb";
254   }
255   Triple.setArchName(ArchName + Suffix.str());
256 }
257 
258 void arm::setFloatABIInTriple(const Driver &D, const ArgList &Args,
259                               llvm::Triple &Triple) {
260   bool isHardFloat =
261       (arm::getARMFloatABI(D, Triple, Args) == arm::FloatABI::Hard);
262 
263   switch (Triple.getEnvironment()) {
264   case llvm::Triple::GNUEABI:
265   case llvm::Triple::GNUEABIHF:
266     Triple.setEnvironment(isHardFloat ? llvm::Triple::GNUEABIHF
267                                       : llvm::Triple::GNUEABI);
268     break;
269   case llvm::Triple::EABI:
270   case llvm::Triple::EABIHF:
271     Triple.setEnvironment(isHardFloat ? llvm::Triple::EABIHF
272                                       : llvm::Triple::EABI);
273     break;
274   case llvm::Triple::MuslEABI:
275   case llvm::Triple::MuslEABIHF:
276     Triple.setEnvironment(isHardFloat ? llvm::Triple::MuslEABIHF
277                                       : llvm::Triple::MuslEABI);
278     break;
279   default: {
280     arm::FloatABI DefaultABI = arm::getDefaultFloatABI(Triple);
281     if (DefaultABI != arm::FloatABI::Invalid &&
282         isHardFloat != (DefaultABI == arm::FloatABI::Hard)) {
283       Arg *ABIArg =
284           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
285                           options::OPT_mfloat_abi_EQ);
286       assert(ABIArg && "Non-default float abi expected to be from arg");
287       D.Diag(diag::err_drv_unsupported_opt_for_target)
288           << ABIArg->getAsString(Args) << Triple.getTriple();
289     }
290     break;
291   }
292   }
293 }
294 
295 arm::FloatABI arm::getARMFloatABI(const ToolChain &TC, const ArgList &Args) {
296   return arm::getARMFloatABI(TC.getDriver(), TC.getEffectiveTriple(), Args);
297 }
298 
299 arm::FloatABI arm::getDefaultFloatABI(const llvm::Triple &Triple) {
300   auto SubArch = getARMSubArchVersionNumber(Triple);
301   switch (Triple.getOS()) {
302   case llvm::Triple::Darwin:
303   case llvm::Triple::MacOSX:
304   case llvm::Triple::IOS:
305   case llvm::Triple::TvOS:
306     // Darwin defaults to "softfp" for v6 and v7.
307     if (Triple.isWatchABI())
308       return FloatABI::Hard;
309     else
310       return (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
311 
312   case llvm::Triple::WatchOS:
313     return FloatABI::Hard;
314 
315   // FIXME: this is invalid for WindowsCE
316   case llvm::Triple::Win32:
317     // It is incorrect to select hard float ABI on MachO platforms if the ABI is
318     // "apcs-gnu".
319     if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple))
320       return FloatABI::Soft;
321     return FloatABI::Hard;
322 
323   case llvm::Triple::NetBSD:
324     switch (Triple.getEnvironment()) {
325     case llvm::Triple::EABIHF:
326     case llvm::Triple::GNUEABIHF:
327       return FloatABI::Hard;
328     default:
329       return FloatABI::Soft;
330     }
331     break;
332 
333   case llvm::Triple::FreeBSD:
334     switch (Triple.getEnvironment()) {
335     case llvm::Triple::GNUEABIHF:
336       return FloatABI::Hard;
337     default:
338       // FreeBSD defaults to soft float
339       return FloatABI::Soft;
340     }
341     break;
342 
343   case llvm::Triple::OpenBSD:
344     return FloatABI::SoftFP;
345 
346   default:
347     switch (Triple.getEnvironment()) {
348     case llvm::Triple::GNUEABIHF:
349     case llvm::Triple::MuslEABIHF:
350     case llvm::Triple::EABIHF:
351       return FloatABI::Hard;
352     case llvm::Triple::GNUEABI:
353     case llvm::Triple::MuslEABI:
354     case llvm::Triple::EABI:
355       // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
356       return FloatABI::SoftFP;
357     case llvm::Triple::Android:
358       return (SubArch >= 7) ? FloatABI::SoftFP : FloatABI::Soft;
359     default:
360       return FloatABI::Invalid;
361     }
362   }
363   return FloatABI::Invalid;
364 }
365 
366 // Select the float ABI as determined by -msoft-float, -mhard-float, and
367 // -mfloat-abi=.
368 arm::FloatABI arm::getARMFloatABI(const Driver &D, const llvm::Triple &Triple,
369                                   const ArgList &Args) {
370   arm::FloatABI ABI = FloatABI::Invalid;
371   if (Arg *A =
372           Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
373                           options::OPT_mfloat_abi_EQ)) {
374     if (A->getOption().matches(options::OPT_msoft_float)) {
375       ABI = FloatABI::Soft;
376     } else if (A->getOption().matches(options::OPT_mhard_float)) {
377       ABI = FloatABI::Hard;
378     } else {
379       ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
380                 .Case("soft", FloatABI::Soft)
381                 .Case("softfp", FloatABI::SoftFP)
382                 .Case("hard", FloatABI::Hard)
383                 .Default(FloatABI::Invalid);
384       if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
385         D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
386         ABI = FloatABI::Soft;
387       }
388     }
389   }
390 
391   // If unspecified, choose the default based on the platform.
392   if (ABI == FloatABI::Invalid)
393     ABI = arm::getDefaultFloatABI(Triple);
394 
395   if (ABI == FloatABI::Invalid) {
396     // Assume "soft", but warn the user we are guessing.
397     if (Triple.isOSBinFormatMachO() &&
398         Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
399       ABI = FloatABI::Hard;
400     else
401       ABI = FloatABI::Soft;
402 
403     if (Triple.getOS() != llvm::Triple::UnknownOS ||
404         !Triple.isOSBinFormatMachO())
405       D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
406   }
407 
408   assert(ABI != FloatABI::Invalid && "must select an ABI");
409   return ABI;
410 }
411 
412 static bool hasIntegerMVE(const std::vector<StringRef> &F) {
413   auto MVE = llvm::find(llvm::reverse(F), "+mve");
414   auto NoMVE = llvm::find(llvm::reverse(F), "-mve");
415   return MVE != F.rend() &&
416          (NoMVE == F.rend() || std::distance(MVE, NoMVE) > 0);
417 }
418 
419 void arm::getARMTargetFeatures(const Driver &D, const llvm::Triple &Triple,
420                                const ArgList &Args, ArgStringList &CmdArgs,
421                                std::vector<StringRef> &Features, bool ForAS) {
422   bool KernelOrKext =
423       Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
424   arm::FloatABI ABI = arm::getARMFloatABI(D, Triple, Args);
425   arm::ReadTPMode ThreadPointer = arm::getReadTPMode(D, Args);
426   llvm::Optional<std::pair<const Arg *, StringRef>> WaCPU, WaFPU, WaHDiv,
427       WaArch;
428 
429   // This vector will accumulate features from the architecture
430   // extension suffixes on -mcpu and -march (e.g. the 'bar' in
431   // -mcpu=foo+bar). We want to apply those after the features derived
432   // from the FPU, in case -mfpu generates a negative feature which
433   // the +bar is supposed to override.
434   std::vector<StringRef> ExtensionFeatures;
435 
436   if (!ForAS) {
437     // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
438     // yet (it uses the -mfloat-abi and -msoft-float options), and it is
439     // stripped out by the ARM target. We should probably pass this a new
440     // -target-option, which is handled by the -cc1/-cc1as invocation.
441     //
442     // FIXME2:  For consistency, it would be ideal if we set up the target
443     // machine state the same when using the frontend or the assembler. We don't
444     // currently do that for the assembler, we pass the options directly to the
445     // backend and never even instantiate the frontend TargetInfo. If we did,
446     // and used its handleTargetFeatures hook, then we could ensure the
447     // assembler and the frontend behave the same.
448 
449     // Use software floating point operations?
450     if (ABI == arm::FloatABI::Soft)
451       Features.push_back("+soft-float");
452 
453     // Use software floating point argument passing?
454     if (ABI != arm::FloatABI::Hard)
455       Features.push_back("+soft-float-abi");
456   } else {
457     // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
458     // to the assembler correctly.
459     for (const Arg *A :
460          Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
461       // We use getValues here because you can have many options per -Wa
462       // We will keep the last one we find for each of these
463       for (StringRef Value : A->getValues()) {
464         if (Value.startswith("-mfpu=")) {
465           WaFPU = std::make_pair(A, Value.substr(6));
466         } else if (Value.startswith("-mcpu=")) {
467           WaCPU = std::make_pair(A, Value.substr(6));
468         } else if (Value.startswith("-mhwdiv=")) {
469           WaHDiv = std::make_pair(A, Value.substr(8));
470         } else if (Value.startswith("-march=")) {
471           WaArch = std::make_pair(A, Value.substr(7));
472         }
473       }
474     }
475   }
476 
477   if (ThreadPointer == arm::ReadTPMode::Cp15)
478     Features.push_back("+read-tp-hard");
479 
480   const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
481   const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
482   StringRef ArchName;
483   StringRef CPUName;
484   unsigned ArchArgFPUID = llvm::ARM::FK_INVALID;
485   unsigned CPUArgFPUID = llvm::ARM::FK_INVALID;
486 
487   // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
488   if (WaCPU) {
489     if (CPUArg)
490       D.Diag(clang::diag::warn_drv_unused_argument)
491           << CPUArg->getAsString(Args);
492     CPUName = WaCPU->second;
493     CPUArg = WaCPU->first;
494   } else if (CPUArg)
495     CPUName = CPUArg->getValue();
496 
497   // Check -march. ClangAs gives preference to -Wa,-march=.
498   if (WaArch) {
499     if (ArchArg)
500       D.Diag(clang::diag::warn_drv_unused_argument)
501           << ArchArg->getAsString(Args);
502     ArchName = WaArch->second;
503     // This will set any features after the base architecture.
504     checkARMArchName(D, WaArch->first, Args, ArchName, CPUName,
505                      ExtensionFeatures, Triple, ArchArgFPUID);
506     // The base architecture was handled in ToolChain::ComputeLLVMTriple because
507     // triple is read only by this point.
508   } else if (ArchArg) {
509     ArchName = ArchArg->getValue();
510     checkARMArchName(D, ArchArg, Args, ArchName, CPUName, ExtensionFeatures,
511                      Triple, ArchArgFPUID);
512   }
513 
514   // Add CPU features for generic CPUs
515   if (CPUName == "native") {
516     llvm::StringMap<bool> HostFeatures;
517     if (llvm::sys::getHostCPUFeatures(HostFeatures))
518       for (auto &F : HostFeatures)
519         Features.push_back(
520             Args.MakeArgString((F.second ? "+" : "-") + F.first()));
521   } else if (!CPUName.empty()) {
522     // This sets the default features for the specified CPU. We certainly don't
523     // want to override the features that have been explicitly specified on the
524     // command line. Therefore, process them directly instead of appending them
525     // at the end later.
526     DecodeARMFeaturesFromCPU(D, CPUName, Features);
527   }
528 
529   if (CPUArg)
530     checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, ExtensionFeatures,
531                     Triple, CPUArgFPUID);
532   // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
533   unsigned FPUID = llvm::ARM::FK_INVALID;
534   const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
535   if (WaFPU) {
536     if (FPUArg)
537       D.Diag(clang::diag::warn_drv_unused_argument)
538           << FPUArg->getAsString(Args);
539     (void)getARMFPUFeatures(D, WaFPU->first, Args, WaFPU->second, Features);
540   } else if (FPUArg) {
541     FPUID = getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
542   } else if (Triple.isAndroid() && getARMSubArchVersionNumber(Triple) >= 7) {
543     const char *AndroidFPU = "neon";
544     FPUID = llvm::ARM::parseFPU(AndroidFPU);
545     if (!llvm::ARM::getFPUFeatures(FPUID, Features))
546       D.Diag(clang::diag::err_drv_clang_unsupported)
547           << std::string("-mfpu=") + AndroidFPU;
548   } else {
549     if (!ForAS) {
550       std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
551       llvm::ARM::ArchKind ArchKind =
552           arm::getLLVMArchKindForARM(CPU, ArchName, Triple);
553       FPUID = llvm::ARM::getDefaultFPU(CPU, ArchKind);
554       (void)llvm::ARM::getFPUFeatures(FPUID, Features);
555     }
556   }
557 
558   // Now we've finished accumulating features from arch, cpu and fpu,
559   // we can append the ones for architecture extensions that we
560   // collected separately.
561   Features.insert(std::end(Features),
562                   std::begin(ExtensionFeatures), std::end(ExtensionFeatures));
563 
564   // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
565   const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
566   if (WaHDiv) {
567     if (HDivArg)
568       D.Diag(clang::diag::warn_drv_unused_argument)
569           << HDivArg->getAsString(Args);
570     getARMHWDivFeatures(D, WaHDiv->first, Args, WaHDiv->second, Features);
571   } else if (HDivArg)
572     getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
573 
574   // Handle (arch-dependent) fp16fml/fullfp16 relationship.
575   // Must happen before any features are disabled due to soft-float.
576   // FIXME: this fp16fml option handling will be reimplemented after the
577   // TargetParser rewrite.
578   const auto ItRNoFullFP16 = std::find(Features.rbegin(), Features.rend(), "-fullfp16");
579   const auto ItRFP16FML = std::find(Features.rbegin(), Features.rend(), "+fp16fml");
580   if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_4a) {
581     const auto ItRFullFP16  = std::find(Features.rbegin(), Features.rend(), "+fullfp16");
582     if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) {
583       // Only entangled feature that can be to the right of this +fullfp16 is -fp16fml.
584       // Only append the +fp16fml if there is no -fp16fml after the +fullfp16.
585       if (std::find(Features.rbegin(), ItRFullFP16, "-fp16fml") == ItRFullFP16)
586         Features.push_back("+fp16fml");
587     }
588     else
589       goto fp16_fml_fallthrough;
590   }
591   else {
592 fp16_fml_fallthrough:
593     // In both of these cases, putting the 'other' feature on the end of the vector will
594     // result in the same effect as placing it immediately after the current feature.
595     if (ItRNoFullFP16 < ItRFP16FML)
596       Features.push_back("-fp16fml");
597     else if (ItRNoFullFP16 > ItRFP16FML)
598       Features.push_back("+fullfp16");
599   }
600 
601   // Setting -msoft-float/-mfloat-abi=soft, -mfpu=none, or adding +nofp to
602   // -march/-mcpu effectively disables the FPU (GCC ignores the -mfpu options in
603   // this case). Note that the ABI can also be set implicitly by the target
604   // selected.
605   if (ABI == arm::FloatABI::Soft) {
606     llvm::ARM::getFPUFeatures(llvm::ARM::FK_NONE, Features);
607 
608     // Disable all features relating to hardware FP, not already disabled by the
609     // above call.
610     Features.insert(Features.end(), {"-dotprod", "-fp16fml", "-bf16", "-mve",
611                                      "-mve.fp", "-fpregs"});
612   } else if (FPUID == llvm::ARM::FK_NONE ||
613              ArchArgFPUID == llvm::ARM::FK_NONE ||
614              CPUArgFPUID == llvm::ARM::FK_NONE) {
615     // -mfpu=none, -march=armvX+nofp or -mcpu=X+nofp is *very* similar to
616     // -mfloat-abi=soft, only that it should not disable MVE-I. They disable the
617     // FPU, but not the FPU registers, thus MVE-I, which depends only on the
618     // latter, is still supported.
619     Features.insert(Features.end(),
620                     {"-dotprod", "-fp16fml", "-bf16", "-mve.fp"});
621     if (!hasIntegerMVE(Features))
622       Features.emplace_back("-fpregs");
623   }
624 
625   // En/disable crc code generation.
626   if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
627     if (A->getOption().matches(options::OPT_mcrc))
628       Features.push_back("+crc");
629     else
630       Features.push_back("-crc");
631   }
632 
633   // For Arch >= ARMv8.0 && A or R profile:  crypto = sha2 + aes
634   // Rather than replace within the feature vector, determine whether each
635   // algorithm is enabled and append this to the end of the vector.
636   // The algorithms can be controlled by their specific feature or the crypto
637   // feature, so their status can be determined by the last occurance of
638   // either in the vector. This allows one to supercede the other.
639   // e.g. +crypto+noaes in -march/-mcpu should enable sha2, but not aes
640   // FIXME: this needs reimplementation after the TargetParser rewrite
641   bool HasSHA2 = false;
642   bool HasAES = false;
643   const auto ItCrypto =
644       llvm::find_if(llvm::reverse(Features), [](const StringRef F) {
645         return F.contains("crypto");
646       });
647   const auto ItSHA2 =
648       llvm::find_if(llvm::reverse(Features), [](const StringRef F) {
649         return F.contains("crypto") || F.contains("sha2");
650       });
651   const auto ItAES =
652       llvm::find_if(llvm::reverse(Features), [](const StringRef F) {
653         return F.contains("crypto") || F.contains("aes");
654       });
655   const bool FoundSHA2 = ItSHA2 != Features.rend();
656   const bool FoundAES = ItAES != Features.rend();
657   if (FoundSHA2)
658     HasSHA2 = ItSHA2->take_front() == "+";
659   if (FoundAES)
660     HasAES = ItAES->take_front() == "+";
661   if (ItCrypto != Features.rend()) {
662     if (HasSHA2 && HasAES)
663       Features.push_back("+crypto");
664     else
665       Features.push_back("-crypto");
666     if (HasSHA2)
667       Features.push_back("+sha2");
668     else
669       Features.push_back("-sha2");
670     if (HasAES)
671       Features.push_back("+aes");
672     else
673       Features.push_back("-aes");
674   }
675 
676   if (HasSHA2 || HasAES) {
677     StringRef ArchSuffix = arm::getLLVMArchSuffixForARM(
678         arm::getARMTargetCPU(CPUName, ArchName, Triple), ArchName, Triple);
679     llvm::ARM::ProfileKind ArchProfile =
680         llvm::ARM::parseArchProfile(ArchSuffix);
681     if (!((llvm::ARM::parseArchVersion(ArchSuffix) >= 8) &&
682           (ArchProfile == llvm::ARM::ProfileKind::A ||
683            ArchProfile == llvm::ARM::ProfileKind::R))) {
684       if (HasSHA2)
685         D.Diag(clang::diag::warn_target_unsupported_extension)
686             << "sha2"
687             << llvm::ARM::getArchName(llvm::ARM::parseArch(ArchSuffix));
688       if (HasAES)
689         D.Diag(clang::diag::warn_target_unsupported_extension)
690             << "aes"
691             << llvm::ARM::getArchName(llvm::ARM::parseArch(ArchSuffix));
692       // With -fno-integrated-as -mfpu=crypto-neon-fp-armv8 some assemblers such
693       // as the GNU assembler will permit the use of crypto instructions as the
694       // fpu will override the architecture. We keep the crypto feature in this
695       // case to preserve compatibility. In all other cases we remove the crypto
696       // feature.
697       if (!Args.hasArg(options::OPT_fno_integrated_as)) {
698         Features.push_back("-sha2");
699         Features.push_back("-aes");
700       }
701     }
702   }
703 
704   // CMSE: Check for target 8M (for -mcmse to be applicable) is performed later.
705   if (Args.getLastArg(options::OPT_mcmse))
706     Features.push_back("+8msecext");
707 
708   // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
709   // neither options are specified, see if we are compiling for kernel/kext and
710   // decide whether to pass "+long-calls" based on the OS and its version.
711   if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
712                                options::OPT_mno_long_calls)) {
713     if (A->getOption().matches(options::OPT_mlong_calls))
714       Features.push_back("+long-calls");
715   } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
716              !Triple.isWatchOS()) {
717       Features.push_back("+long-calls");
718   }
719 
720   // Generate execute-only output (no data access to code sections).
721   // This only makes sense for the compiler, not for the assembler.
722   if (!ForAS) {
723     // Supported only on ARMv6T2 and ARMv7 and above.
724     // Cannot be combined with -mno-movt or -mlong-calls
725     if (Arg *A = Args.getLastArg(options::OPT_mexecute_only, options::OPT_mno_execute_only)) {
726       if (A->getOption().matches(options::OPT_mexecute_only)) {
727         if (getARMSubArchVersionNumber(Triple) < 7 &&
728             llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6T2)
729               D.Diag(diag::err_target_unsupported_execute_only) << Triple.getArchName();
730         else if (Arg *B = Args.getLastArg(options::OPT_mno_movt))
731           D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
732         // Long calls create constant pool entries and have not yet been fixed up
733         // to play nicely with execute-only. Hence, they cannot be used in
734         // execute-only code for now
735         else if (Arg *B = Args.getLastArg(options::OPT_mlong_calls, options::OPT_mno_long_calls)) {
736           if (B->getOption().matches(options::OPT_mlong_calls))
737             D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
738         }
739         Features.push_back("+execute-only");
740       }
741     }
742   }
743 
744   // Kernel code has more strict alignment requirements.
745   if (KernelOrKext)
746     Features.push_back("+strict-align");
747   else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
748                                     options::OPT_munaligned_access)) {
749     if (A->getOption().matches(options::OPT_munaligned_access)) {
750       // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
751       if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
752         D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
753       // v8M Baseline follows on from v6M, so doesn't support unaligned memory
754       // access either.
755       else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
756         D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
757     } else
758       Features.push_back("+strict-align");
759   } else {
760     // Assume pre-ARMv6 doesn't support unaligned accesses.
761     //
762     // ARMv6 may or may not support unaligned accesses depending on the
763     // SCTLR.U bit, which is architecture-specific. We assume ARMv6
764     // Darwin and NetBSD targets support unaligned accesses, and others don't.
765     //
766     // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
767     // which raises an alignment fault on unaligned accesses. Linux
768     // defaults this bit to 0 and handles it as a system-wide (not
769     // per-process) setting. It is therefore safe to assume that ARMv7+
770     // Linux targets support unaligned accesses. The same goes for NaCl.
771     //
772     // The above behavior is consistent with GCC.
773     int VersionNum = getARMSubArchVersionNumber(Triple);
774     if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
775       if (VersionNum < 6 ||
776           Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
777         Features.push_back("+strict-align");
778     } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
779       if (VersionNum < 7)
780         Features.push_back("+strict-align");
781     } else
782       Features.push_back("+strict-align");
783   }
784 
785   // llvm does not support reserving registers in general. There is support
786   // for reserving r9 on ARM though (defined as a platform-specific register
787   // in ARM EABI).
788   if (Args.hasArg(options::OPT_ffixed_r9))
789     Features.push_back("+reserve-r9");
790 
791   // The kext linker doesn't know how to deal with movw/movt.
792   if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
793     Features.push_back("+no-movt");
794 
795   if (Args.hasArg(options::OPT_mno_neg_immediates))
796     Features.push_back("+no-neg-immediates");
797 
798   // Enable/disable straight line speculation hardening.
799   if (Arg *A = Args.getLastArg(options::OPT_mharden_sls_EQ)) {
800     StringRef Scope = A->getValue();
801     bool EnableRetBr = false;
802     bool EnableBlr = false;
803     bool DisableComdat = false;
804     if (Scope != "none") {
805       SmallVector<StringRef, 4> Opts;
806       Scope.split(Opts, ",");
807       for (auto Opt : Opts) {
808         Opt = Opt.trim();
809         if (Opt == "all") {
810           EnableBlr = true;
811           EnableRetBr = true;
812           continue;
813         }
814         if (Opt == "retbr") {
815           EnableRetBr = true;
816           continue;
817         }
818         if (Opt == "blr") {
819           EnableBlr = true;
820           continue;
821         }
822         if (Opt == "comdat") {
823           DisableComdat = false;
824           continue;
825         }
826         if (Opt == "nocomdat") {
827           DisableComdat = true;
828           continue;
829         }
830         D.Diag(diag::err_invalid_sls_hardening)
831             << Scope << A->getAsString(Args);
832         break;
833       }
834     }
835 
836     if (EnableRetBr || EnableBlr)
837       if (!(isARMAProfile(Triple) && getARMSubArchVersionNumber(Triple) >= 7))
838         D.Diag(diag::err_sls_hardening_arm_not_supported)
839             << Scope << A->getAsString(Args);
840 
841     if (EnableRetBr)
842       Features.push_back("+harden-sls-retbr");
843     if (EnableBlr)
844       Features.push_back("+harden-sls-blr");
845     if (DisableComdat) {
846       Features.push_back("+harden-sls-nocomdat");
847     }
848   }
849 
850 }
851 
852 const std::string arm::getARMArch(StringRef Arch, const llvm::Triple &Triple) {
853   std::string MArch;
854   if (!Arch.empty())
855     MArch = std::string(Arch);
856   else
857     MArch = std::string(Triple.getArchName());
858   MArch = StringRef(MArch).split("+").first.lower();
859 
860   // Handle -march=native.
861   if (MArch == "native") {
862     std::string CPU = std::string(llvm::sys::getHostCPUName());
863     if (CPU != "generic") {
864       // Translate the native cpu into the architecture suffix for that CPU.
865       StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
866       // If there is no valid architecture suffix for this CPU we don't know how
867       // to handle it, so return no architecture.
868       if (Suffix.empty())
869         MArch = "";
870       else
871         MArch = std::string("arm") + Suffix.str();
872     }
873   }
874 
875   return MArch;
876 }
877 
878 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
879 StringRef arm::getARMCPUForMArch(StringRef Arch, const llvm::Triple &Triple) {
880   std::string MArch = getARMArch(Arch, Triple);
881   // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
882   // here means an -march=native that we can't handle, so instead return no CPU.
883   if (MArch.empty())
884     return StringRef();
885 
886   // We need to return an empty string here on invalid MArch values as the
887   // various places that call this function can't cope with a null result.
888   return Triple.getARMCPUForArch(MArch);
889 }
890 
891 /// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
892 std::string arm::getARMTargetCPU(StringRef CPU, StringRef Arch,
893                                  const llvm::Triple &Triple) {
894   // FIXME: Warn on inconsistent use of -mcpu and -march.
895   // If we have -mcpu=, use that.
896   if (!CPU.empty()) {
897     std::string MCPU = StringRef(CPU).split("+").first.lower();
898     // Handle -mcpu=native.
899     if (MCPU == "native")
900       return std::string(llvm::sys::getHostCPUName());
901     else
902       return MCPU;
903   }
904 
905   return std::string(getARMCPUForMArch(Arch, Triple));
906 }
907 
908 /// getLLVMArchSuffixForARM - Get the LLVM ArchKind value to use for a
909 /// particular CPU (or Arch, if CPU is generic). This is needed to
910 /// pass to functions like llvm::ARM::getDefaultFPU which need an
911 /// ArchKind as well as a CPU name.
912 llvm::ARM::ArchKind arm::getLLVMArchKindForARM(StringRef CPU, StringRef Arch,
913                                                const llvm::Triple &Triple) {
914   llvm::ARM::ArchKind ArchKind;
915   if (CPU == "generic" || CPU.empty()) {
916     std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
917     ArchKind = llvm::ARM::parseArch(ARMArch);
918     if (ArchKind == llvm::ARM::ArchKind::INVALID)
919       // In case of generic Arch, i.e. "arm",
920       // extract arch from default cpu of the Triple
921       ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
922   } else {
923     // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
924     // armv7k triple if it's actually been specified via "-arch armv7k".
925     ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
926                           ? llvm::ARM::ArchKind::ARMV7K
927                           : llvm::ARM::parseCPUArch(CPU);
928   }
929   return ArchKind;
930 }
931 
932 /// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
933 /// CPU  (or Arch, if CPU is generic).
934 // FIXME: This is redundant with -mcpu, why does LLVM use this.
935 StringRef arm::getLLVMArchSuffixForARM(StringRef CPU, StringRef Arch,
936                                        const llvm::Triple &Triple) {
937   llvm::ARM::ArchKind ArchKind = getLLVMArchKindForARM(CPU, Arch, Triple);
938   if (ArchKind == llvm::ARM::ArchKind::INVALID)
939     return "";
940   return llvm::ARM::getSubArch(ArchKind);
941 }
942 
943 void arm::appendBE8LinkFlag(const ArgList &Args, ArgStringList &CmdArgs,
944                             const llvm::Triple &Triple) {
945   if (Args.hasArg(options::OPT_r))
946     return;
947 
948   // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
949   // to generate BE-8 executables.
950   if (arm::getARMSubArchVersionNumber(Triple) >= 7 || arm::isARMMProfile(Triple))
951     CmdArgs.push_back("--be8");
952 }
953