Clang Project

clang_source_code/lib/Driver/ToolChains/Arch/ARM.cpp
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
17using namespace clang::driver;
18using namespace clang::driver::tools;
19using namespace clang;
20using namespace llvm::opt;
21
22// Get SubArch (vN).
23int arm::getARMSubArchVersionNumber(const llvm::Triple &Triple) {
24  llvm::StringRef Arch = Triple.getArchName();
25  return llvm::ARM::parseArchVersion(Arch);
26}
27
28// True if M-profile.
29bool arm::isARMMProfile(const llvm::Triple &Triple) {
30  llvm::StringRef Arch = Triple.getArchName();
31  return llvm::ARM::parseArchProfile(Arch) == llvm::ARM::ProfileKind::M;
32}
33
34// Get Arch/CPU from args.
35void arm::getARMArchCPUFromArgs(const ArgList &Argsllvm::StringRef &Arch,
36                                llvm::StringRef &CPUbool FromAs) {
37  if (const Arg *A = Args.getLastArg(clang::driver::options::OPT_mcpu_EQ))
38    CPU = A->getValue();
39  if (const Arg *A = Args.getLastArg(options::OPT_march_EQ))
40    Arch = A->getValue();
41  if (!FromAs)
42    return;
43
44  for (const Arg *A :
45       Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
46    StringRef Value = A->getValue();
47    if (Value.startswith("-mcpu="))
48      CPU = Value.substr(6);
49    if (Value.startswith("-march="))
50      Arch = Value.substr(7);
51  }
52}
53
54// Handle -mhwdiv=.
55// FIXME: Use ARMTargetParser.
56static void getARMHWDivFeatures(const Driver &Dconst Arg *A,
57                                const ArgList &ArgsStringRef HWDiv,
58                                std::vector<StringRef> &Features) {
59  unsigned HWDivID = llvm::ARM::parseHWDiv(HWDiv);
60  if (!llvm::ARM::getHWDivFeatures(HWDivID, Features))
61    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
62}
63
64// Handle -mfpu=.
65static void getARMFPUFeatures(const Driver &Dconst Arg *A,
66                              const ArgList &ArgsStringRef FPU,
67                              std::vector<StringRef> &Features) {
68  unsigned FPUID = llvm::ARM::parseFPU(FPU);
69  if (!llvm::ARM::getFPUFeatures(FPUID, Features))
70    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
71}
72
73// Decode ARM features from string like +[no]featureA+[no]featureB+...
74static bool DecodeARMFeatures(const Driver &DStringRef text,
75                              std::vector<StringRef> &Features) {
76  SmallVector<StringRef8Split;
77  text.split(Split, StringRef("+"), -1false);
78
79  for (StringRef Feature : Split) {
80    StringRef FeatureName = llvm::ARM::getArchExtFeature(Feature);
81    if (!FeatureName.empty())
82      Features.push_back(FeatureName);
83    else
84      return false;
85  }
86  return true;
87}
88
89static void DecodeARMFeaturesFromCPU(const Driver &DStringRef CPU,
90                                     std::vector<StringRef> &Features) {
91  if (CPU != "generic") {
92    llvm::ARM::ArchKind ArchKind = llvm::ARM::parseCPUArch(CPU);
93    unsigned Extension = llvm::ARM::getDefaultExtensions(CPU, ArchKind);
94    llvm::ARM::getExtensionFeatures(Extension, Features);
95  }
96}
97
98// Check if -march is valid by checking if it can be canonicalised and parsed.
99// getARMArch is used here instead of just checking the -march value in order
100// to handle -march=native correctly.
101static void checkARMArchName(const Driver &Dconst Arg *Aconst ArgList &Args,
102                             llvm::StringRef ArchName,
103                             std::vector<StringRef> &Features,
104                             const llvm::Triple &Triple) {
105  std::pair<StringRefStringRefSplit = ArchName.split("+");
106
107  std::string MArch = arm::getARMArch(ArchName, Triple);
108  if (llvm::ARM::parseArch(MArch) == llvm::ARM::ArchKind::INVALID ||
109      (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
110    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
111}
112
113// Check -mcpu=. Needs ArchName to handle -mcpu=generic.
114static void checkARMCPUName(const Driver &Dconst Arg *Aconst ArgList &Args,
115                            llvm::StringRef CPUNamellvm::StringRef ArchName,
116                            std::vector<StringRef> &Features,
117                            const llvm::Triple &Triple) {
118  std::pair<StringRefStringRefSplit = CPUName.split("+");
119
120  std::string CPU = arm::getARMTargetCPU(CPUName, ArchName, Triple);
121  if (arm::getLLVMArchSuffixForARM(CPU, ArchName, Triple).empty() ||
122      (Split.second.size() && !DecodeARMFeatures(D, Split.second, Features)))
123    D.Diag(clang::diag::err_drv_clang_unsupported) << A->getAsString(Args);
124}
125
126bool arm::useAAPCSForMachO(const llvm::Triple &T) {
127  // The backend is hardwired to assume AAPCS for M-class processors, ensure
128  // the frontend matches that.
129  return T.getEnvironment() == llvm::Triple::EABI ||
130         T.getOS() == llvm::Triple::UnknownOS || isARMMProfile(T);
131}
132
133// Select mode for reading thread pointer (-mtp=soft/cp15).
134arm::ReadTPMode arm::getReadTPMode(const ToolChain &TCconst ArgList &Args) {
135  if (Arg *A = Args.getLastArg(options::OPT_mtp_mode_EQ)) {
136    const Driver &D = TC.getDriver();
137    arm::ReadTPMode ThreadPointer =
138        llvm::StringSwitch<arm::ReadTPMode>(A->getValue())
139            .Case("cp15", ReadTPMode::Cp15)
140            .Case("soft", ReadTPMode::Soft)
141            .Default(ReadTPMode::Invalid);
142    if (ThreadPointer != ReadTPMode::Invalid)
143      return ThreadPointer;
144    if (StringRef(A->getValue()).empty())
145      D.Diag(diag::err_drv_missing_arg_mtp) << A->getAsString(Args);
146    else
147      D.Diag(diag::err_drv_invalid_mtp) << A->getAsString(Args);
148    return ReadTPMode::Invalid;
149  }
150  return ReadTPMode::Soft;
151}
152
153// Select the float ABI as determined by -msoft-float, -mhard-float, and
154// -mfloat-abi=.
155arm::FloatABI arm::getARMFloatABI(const ToolChain &TCconst ArgList &Args) {
156  const Driver &D = TC.getDriver();
157  const llvm::Triple &Triple = TC.getEffectiveTriple();
158  auto SubArch = getARMSubArchVersionNumber(Triple);
159  arm::FloatABI ABI = FloatABI::Invalid;
160  if (Arg *A =
161          Args.getLastArg(options::OPT_msoft_float, options::OPT_mhard_float,
162                          options::OPT_mfloat_abi_EQ)) {
163    if (A->getOption().matches(options::OPT_msoft_float)) {
164      ABI = FloatABI::Soft;
165    } else if (A->getOption().matches(options::OPT_mhard_float)) {
166      ABI = FloatABI::Hard;
167    } else {
168      ABI = llvm::StringSwitch<arm::FloatABI>(A->getValue())
169                .Case("soft", FloatABI::Soft)
170                .Case("softfp", FloatABI::SoftFP)
171                .Case("hard", FloatABI::Hard)
172                .Default(FloatABI::Invalid);
173      if (ABI == FloatABI::Invalid && !StringRef(A->getValue()).empty()) {
174        D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
175        ABI = FloatABI::Soft;
176      }
177    }
178
179    // It is incorrect to select hard float ABI on MachO platforms if the ABI is
180    // "apcs-gnu".
181    if (Triple.isOSBinFormatMachO() && !useAAPCSForMachO(Triple) &&
182        ABI == FloatABI::Hard) {
183      D.Diag(diag::err_drv_unsupported_opt_for_target) << A->getAsString(Args)
184                                                       << Triple.getArchName();
185    }
186  }
187
188  // If unspecified, choose the default based on the platform.
189  if (ABI == FloatABI::Invalid) {
190    switch (Triple.getOS()) {
191    case llvm::Triple::Darwin:
192    case llvm::Triple::MacOSX:
193    case llvm::Triple::IOS:
194    case llvm::Triple::TvOS: {
195      // Darwin defaults to "softfp" for v6 and v7.
196      ABI = (SubArch == 6 || SubArch == 7) ? FloatABI::SoftFP : FloatABI::Soft;
197      ABI = Triple.isWatchABI() ? FloatABI::Hard : ABI;
198      break;
199    }
200    case llvm::Triple::WatchOS:
201      ABI = FloatABI::Hard;
202      break;
203
204    // FIXME: this is invalid for WindowsCE
205    case llvm::Triple::Win32:
206      ABI = FloatABI::Hard;
207      break;
208
209    case llvm::Triple::NetBSD:
210      switch (Triple.getEnvironment()) {
211      case llvm::Triple::EABIHF:
212      case llvm::Triple::GNUEABIHF:
213        ABI = FloatABI::Hard;
214        break;
215      default:
216        ABI = FloatABI::Soft;
217        break;
218      }
219      break;
220
221    case llvm::Triple::FreeBSD:
222      switch (Triple.getEnvironment()) {
223      case llvm::Triple::GNUEABIHF:
224        ABI = FloatABI::Hard;
225        break;
226      default:
227        // FreeBSD defaults to soft float
228        ABI = FloatABI::Soft;
229        break;
230      }
231      break;
232
233    case llvm::Triple::OpenBSD:
234      ABI = FloatABI::SoftFP;
235      break;
236
237    default:
238      switch (Triple.getEnvironment()) {
239      case llvm::Triple::GNUEABIHF:
240      case llvm::Triple::MuslEABIHF:
241      case llvm::Triple::EABIHF:
242        ABI = FloatABI::Hard;
243        break;
244      case llvm::Triple::GNUEABI:
245      case llvm::Triple::MuslEABI:
246      case llvm::Triple::EABI:
247        // EABI is always AAPCS, and if it was not marked 'hard', it's softfp
248        ABI = FloatABI::SoftFP;
249        break;
250      case llvm::Triple::Android:
251        ABI = (SubArch >= 7) ? FloatABI::SoftFP : FloatABI::Soft;
252        break;
253      default:
254        // Assume "soft", but warn the user we are guessing.
255        if (Triple.isOSBinFormatMachO() &&
256            Triple.getSubArch() == llvm::Triple::ARMSubArch_v7em)
257          ABI = FloatABI::Hard;
258        else
259          ABI = FloatABI::Soft;
260
261        if (Triple.getOS() != llvm::Triple::UnknownOS ||
262            !Triple.isOSBinFormatMachO())
263          D.Diag(diag::warn_drv_assuming_mfloat_abi_is) << "soft";
264        break;
265      }
266    }
267  }
268
269   (0) . __assert_fail ("ABI != FloatABI..Invalid && \"must select an ABI\"", "/home/seafit/code_projects/clang_source/clang/lib/Driver/ToolChains/Arch/ARM.cpp", 269, __PRETTY_FUNCTION__))" file_link="../../../../../include/assert.h.html#88" macro="true">assert(ABI != FloatABI::Invalid && "must select an ABI");
270  return ABI;
271}
272
273void arm::getARMTargetFeatures(const ToolChain &TC,
274                               const llvm::Triple &Triple,
275                               const ArgList &Args,
276                               ArgStringList &CmdArgs,
277                               std::vector<StringRef> &Features,
278                               bool ForAS) {
279  const Driver &D = TC.getDriver();
280
281  bool KernelOrKext =
282      Args.hasArg(options::OPT_mkernel, options::OPT_fapple_kext);
283  arm::FloatABI ABI = arm::getARMFloatABI(TCArgs);
284  arm::ReadTPMode ThreadPointer = arm::getReadTPMode(TCArgs);
285  const Arg *WaCPU = nullptr, *WaFPU = nullptr;
286  const Arg *WaHDiv = nullptr, *WaArch = nullptr;
287
288  if (!ForAS) {
289    // FIXME: Note, this is a hack, the LLVM backend doesn't actually use these
290    // yet (it uses the -mfloat-abi and -msoft-float options), and it is
291    // stripped out by the ARM target. We should probably pass this a new
292    // -target-option, which is handled by the -cc1/-cc1as invocation.
293    //
294    // FIXME2:  For consistency, it would be ideal if we set up the target
295    // machine state the same when using the frontend or the assembler. We don't
296    // currently do that for the assembler, we pass the options directly to the
297    // backend and never even instantiate the frontend TargetInfo. If we did,
298    // and used its handleTargetFeatures hook, then we could ensure the
299    // assembler and the frontend behave the same.
300
301    // Use software floating point operations?
302    if (ABI == arm::FloatABI::Soft)
303      Features.push_back("+soft-float");
304
305    // Use software floating point argument passing?
306    if (ABI != arm::FloatABI::Hard)
307      Features.push_back("+soft-float-abi");
308  } else {
309    // Here, we make sure that -Wa,-mfpu/cpu/arch/hwdiv will be passed down
310    // to the assembler correctly.
311    for (const Arg *A :
312         Args.filtered(options::OPT_Wa_COMMA, options::OPT_Xassembler)) {
313      StringRef Value = A->getValue();
314      if (Value.startswith("-mfpu=")) {
315        WaFPU = A;
316      } else if (Value.startswith("-mcpu=")) {
317        WaCPU = A;
318      } else if (Value.startswith("-mhwdiv=")) {
319        WaHDiv = A;
320      } else if (Value.startswith("-march=")) {
321        WaArch = A;
322      }
323    }
324  }
325
326  if (ThreadPointer == arm::ReadTPMode::Cp15)
327    Features.push_back("+read-tp-hard");
328
329  // Check -march. ClangAs gives preference to -Wa,-march=.
330  const Arg *ArchArg = Args.getLastArg(options::OPT_march_EQ);
331  StringRef ArchName;
332  if (WaArch) {
333    if (ArchArg)
334      D.Diag(clang::diag::warn_drv_unused_argument)
335          << ArchArg->getAsString(Args);
336    ArchName = StringRef(WaArch->getValue()).substr(7);
337    checkARMArchName(D, WaArch, Args, ArchName, Features, Triple);
338    // FIXME: Set Arch.
339    D.Diag(clang::diag::warn_drv_unused_argument) << WaArch->getAsString(Args);
340  } else if (ArchArg) {
341    ArchName = ArchArg->getValue();
342    checkARMArchName(D, ArchArg, Args, ArchName, Features, Triple);
343  }
344
345  // Check -mcpu. ClangAs gives preference to -Wa,-mcpu=.
346  const Arg *CPUArg = Args.getLastArg(options::OPT_mcpu_EQ);
347  StringRef CPUName;
348  if (WaCPU) {
349    if (CPUArg)
350      D.Diag(clang::diag::warn_drv_unused_argument)
351          << CPUArg->getAsString(Args);
352    CPUName = StringRef(WaCPU->getValue()).substr(6);
353    checkARMCPUName(D, WaCPU, Args, CPUName, ArchName, Features, Triple);
354  } else if (CPUArg) {
355    CPUName = CPUArg->getValue();
356    checkARMCPUName(D, CPUArg, Args, CPUName, ArchName, Features, Triple);
357  }
358
359  // Add CPU features for generic CPUs
360  if (CPUName == "native") {
361    llvm::StringMap<bool> HostFeatures;
362    if (llvm::sys::getHostCPUFeatures(HostFeatures))
363      for (auto &F : HostFeatures)
364        Features.push_back(
365            Args.MakeArgString((F.second ? "+" : "-") + F.first()));
366  } else if (!CPUName.empty()) {
367    DecodeARMFeaturesFromCPU(D, CPUName, Features);
368  }
369
370  // Honor -mfpu=. ClangAs gives preference to -Wa,-mfpu=.
371  const Arg *FPUArg = Args.getLastArg(options::OPT_mfpu_EQ);
372  if (WaFPU) {
373    if (FPUArg)
374      D.Diag(clang::diag::warn_drv_unused_argument)
375          << FPUArg->getAsString(Args);
376    getARMFPUFeatures(D, WaFPU, Args, StringRef(WaFPU->getValue()).substr(6),
377                      Features);
378  } else if (FPUArg) {
379    getARMFPUFeatures(D, FPUArg, Args, FPUArg->getValue(), Features);
380  } else if (Triple.isAndroid() && getARMSubArchVersionNumber(Triple) >= 7) {
381    const char *AndroidFPU = "neon";
382    if (!llvm::ARM::getFPUFeatures(llvm::ARM::parseFPU(AndroidFPU), Features))
383      D.Diag(clang::diag::err_drv_clang_unsupported)
384          << std::string("-mfpu=") + AndroidFPU;
385  }
386
387  // Honor -mhwdiv=. ClangAs gives preference to -Wa,-mhwdiv=.
388  const Arg *HDivArg = Args.getLastArg(options::OPT_mhwdiv_EQ);
389  if (WaHDiv) {
390    if (HDivArg)
391      D.Diag(clang::diag::warn_drv_unused_argument)
392          << HDivArg->getAsString(Args);
393    getARMHWDivFeatures(D, WaHDiv, Args,
394                        StringRef(WaHDiv->getValue()).substr(8), Features);
395  } else if (HDivArg)
396    getARMHWDivFeatures(D, HDivArg, Args, HDivArg->getValue(), Features);
397
398  // Handle (arch-dependent) fp16fml/fullfp16 relationship.
399  // Must happen before any features are disabled due to soft-float.
400  // FIXME: this fp16fml option handling will be reimplemented after the
401  // TargetParser rewrite.
402  const auto ItRNoFullFP16 = std::find(Features.rbegin(), Features.rend(), "-fullfp16");
403  const auto ItRFP16FML = std::find(Features.rbegin(), Features.rend(), "+fp16fml");
404  if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8_4a) {
405    const auto ItRFullFP16  = std::find(Features.rbegin(), Features.rend(), "+fullfp16");
406    if (ItRFullFP16 < ItRNoFullFP16 && ItRFullFP16 < ItRFP16FML) {
407      // Only entangled feature that can be to the right of this +fullfp16 is -fp16fml.
408      // Only append the +fp16fml if there is no -fp16fml after the +fullfp16.
409      if (std::find(Features.rbegin(), ItRFullFP16, "-fp16fml") == ItRFullFP16)
410        Features.push_back("+fp16fml");
411    }
412    else
413      goto fp16_fml_fallthrough;
414  }
415  else {
416fp16_fml_fallthrough:
417    // In both of these cases, putting the 'other' feature on the end of the vector will
418    // result in the same effect as placing it immediately after the current feature.
419    if (ItRNoFullFP16 < ItRFP16FML)
420      Features.push_back("-fp16fml");
421    else if (ItRNoFullFP16 > ItRFP16FML)
422      Features.push_back("+fullfp16");
423  }
424
425  // Setting -msoft-float/-mfloat-abi=soft effectively disables the FPU (GCC
426  // ignores the -mfpu options in this case).
427  // Note that the ABI can also be set implicitly by the target selected.
428  if (ABI == arm::FloatABI::Soft) {
429    llvm::ARM::getFPUFeatures(llvm::ARM::FK_NONE, Features);
430
431    // Disable hardware FP features which have been enabled.
432    // FIXME: Disabling vfp2 and neon should be enough as all the other
433    //        features are dependent on these 2 features in LLVM. However
434    //        there is currently no easy way to test this in clang, so for
435    //        now just be explicit and disable all known dependent features
436    //        as well.
437    for (std::string Feature : {"vfp2""vfp3""vfp4""fp-armv8""fullfp16",
438                                "neon""crypto""dotprod""fp16fml"})
439      if (std::find(std::begin(Features), std::end(Features), "+" + Feature) != std::end(Features))
440        Features.push_back(Args.MakeArgString("-" + Feature));
441  }
442
443  // En/disable crc code generation.
444  if (Arg *A = Args.getLastArg(options::OPT_mcrc, options::OPT_mnocrc)) {
445    if (A->getOption().matches(options::OPT_mcrc))
446      Features.push_back("+crc");
447    else
448      Features.push_back("-crc");
449  }
450
451  // For Arch >= ARMv8.0:  crypto = sha2 + aes
452  // FIXME: this needs reimplementation after the TargetParser rewrite
453  if (ArchName.find_lower("armv8a") != StringRef::npos ||
454      ArchName.find_lower("armv8.1a") != StringRef::npos ||
455      ArchName.find_lower("armv8.2a") != StringRef::npos ||
456      ArchName.find_lower("armv8.3a") != StringRef::npos ||
457      ArchName.find_lower("armv8.4a") != StringRef::npos) {
458    if (ArchName.find_lower("+crypto") != StringRef::npos) {
459      if (ArchName.find_lower("+nosha2") == StringRef::npos)
460        Features.push_back("+sha2");
461      if (ArchName.find_lower("+noaes") == StringRef::npos)
462        Features.push_back("+aes");
463    } else if (ArchName.find_lower("-crypto") != StringRef::npos) {
464      if (ArchName.find_lower("+sha2") == StringRef::npos)
465        Features.push_back("-sha2");
466      if (ArchName.find_lower("+aes") == StringRef::npos)
467        Features.push_back("-aes");
468    }
469  }
470
471  // Look for the last occurrence of -mlong-calls or -mno-long-calls. If
472  // neither options are specified, see if we are compiling for kernel/kext and
473  // decide whether to pass "+long-calls" based on the OS and its version.
474  if (Arg *A = Args.getLastArg(options::OPT_mlong_calls,
475                               options::OPT_mno_long_calls)) {
476    if (A->getOption().matches(options::OPT_mlong_calls))
477      Features.push_back("+long-calls");
478  } else if (KernelOrKext && (!Triple.isiOS() || Triple.isOSVersionLT(6)) &&
479             !Triple.isWatchOS()) {
480      Features.push_back("+long-calls");
481  }
482
483  // Generate execute-only output (no data access to code sections).
484  // This only makes sense for the compiler, not for the assembler.
485  if (!ForAS) {
486    // Supported only on ARMv6T2 and ARMv7 and above.
487    // Cannot be combined with -mno-movt or -mlong-calls
488    if (Arg *A = Args.getLastArg(options::OPT_mexecute_only, options::OPT_mno_execute_only)) {
489      if (A->getOption().matches(options::OPT_mexecute_only)) {
490        if (getARMSubArchVersionNumber(Triple) < 7 &&
491            llvm::ARM::parseArch(Triple.getArchName()) != llvm::ARM::ArchKind::ARMV6T2)
492              D.Diag(diag::err_target_unsupported_execute_only) << Triple.getArchName();
493        else if (Arg *B = Args.getLastArg(options::OPT_mno_movt))
494          D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
495        // Long calls create constant pool entries and have not yet been fixed up
496        // to play nicely with execute-only. Hence, they cannot be used in
497        // execute-only code for now
498        else if (Arg *B = Args.getLastArg(options::OPT_mlong_calls, options::OPT_mno_long_calls)) {
499          if (B->getOption().matches(options::OPT_mlong_calls))
500            D.Diag(diag::err_opt_not_valid_with_opt) << A->getAsString(Args) << B->getAsString(Args);
501        }
502        Features.push_back("+execute-only");
503      }
504    }
505  }
506
507  // Kernel code has more strict alignment requirements.
508  if (KernelOrKext)
509    Features.push_back("+strict-align");
510  else if (Arg *A = Args.getLastArg(options::OPT_mno_unaligned_access,
511                                    options::OPT_munaligned_access)) {
512    if (A->getOption().matches(options::OPT_munaligned_access)) {
513      // No v6M core supports unaligned memory access (v6M ARM ARM A3.2).
514      if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
515        D.Diag(diag::err_target_unsupported_unaligned) << "v6m";
516      // v8M Baseline follows on from v6M, so doesn't support unaligned memory
517      // access either.
518      else if (Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v8m_baseline)
519        D.Diag(diag::err_target_unsupported_unaligned) << "v8m.base";
520    } else
521      Features.push_back("+strict-align");
522  } else {
523    // Assume pre-ARMv6 doesn't support unaligned accesses.
524    //
525    // ARMv6 may or may not support unaligned accesses depending on the
526    // SCTLR.U bit, which is architecture-specific. We assume ARMv6
527    // Darwin and NetBSD targets support unaligned accesses, and others don't.
528    //
529    // ARMv7 always has SCTLR.U set to 1, but it has a new SCTLR.A bit
530    // which raises an alignment fault on unaligned accesses. Linux
531    // defaults this bit to 0 and handles it as a system-wide (not
532    // per-process) setting. It is therefore safe to assume that ARMv7+
533    // Linux targets support unaligned accesses. The same goes for NaCl.
534    //
535    // The above behavior is consistent with GCC.
536    int VersionNum = getARMSubArchVersionNumber(Triple);
537    if (Triple.isOSDarwin() || Triple.isOSNetBSD()) {
538      if (VersionNum < 6 ||
539          Triple.getSubArch() == llvm::Triple::SubArchType::ARMSubArch_v6m)
540        Features.push_back("+strict-align");
541    } else if (Triple.isOSLinux() || Triple.isOSNaCl()) {
542      if (VersionNum < 7)
543        Features.push_back("+strict-align");
544    } else
545      Features.push_back("+strict-align");
546  }
547
548  // llvm does not support reserving registers in general. There is support
549  // for reserving r9 on ARM though (defined as a platform-specific register
550  // in ARM EABI).
551  if (Args.hasArg(options::OPT_ffixed_r9))
552    Features.push_back("+reserve-r9");
553
554  // The kext linker doesn't know how to deal with movw/movt.
555  if (KernelOrKext || Args.hasArg(options::OPT_mno_movt))
556    Features.push_back("+no-movt");
557
558  if (Args.hasArg(options::OPT_mno_neg_immediates))
559    Features.push_back("+no-neg-immediates");
560}
561
562const std::string arm::getARMArch(StringRef Archconst llvm::Triple &Triple) {
563  std::string MArch;
564  if (!Arch.empty())
565    MArch = Arch;
566  else
567    MArch = Triple.getArchName();
568  MArch = StringRef(MArch).split("+").first.lower();
569
570  // Handle -march=native.
571  if (MArch == "native") {
572    std::string CPU = llvm::sys::getHostCPUName();
573    if (CPU != "generic") {
574      // Translate the native cpu into the architecture suffix for that CPU.
575      StringRef Suffix = arm::getLLVMArchSuffixForARM(CPU, MArch, Triple);
576      // If there is no valid architecture suffix for this CPU we don't know how
577      // to handle it, so return no architecture.
578      if (Suffix.empty())
579        MArch = "";
580      else
581        MArch = std::string("arm") + Suffix.str();
582    }
583  }
584
585  return MArch;
586}
587
588/// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
589StringRef arm::getARMCPUForMArch(StringRef Archconst llvm::Triple &Triple) {
590  std::string MArch = getARMArch(Arch, Triple);
591  // getARMCPUForArch defaults to the triple if MArch is empty, but empty MArch
592  // here means an -march=native that we can't handle, so instead return no CPU.
593  if (MArch.empty())
594    return StringRef();
595
596  // We need to return an empty string here on invalid MArch values as the
597  // various places that call this function can't cope with a null result.
598  return Triple.getARMCPUForArch(MArch);
599}
600
601/// getARMTargetCPU - Get the (LLVM) name of the ARM cpu we are targeting.
602std::string arm::getARMTargetCPU(StringRef CPUStringRef Arch,
603                                 const llvm::Triple &Triple) {
604  // FIXME: Warn on inconsistent use of -mcpu and -march.
605  // If we have -mcpu=, use that.
606  if (!CPU.empty()) {
607    std::string MCPU = StringRef(CPU).split("+").first.lower();
608    // Handle -mcpu=native.
609    if (MCPU == "native")
610      return llvm::sys::getHostCPUName();
611    else
612      return MCPU;
613  }
614
615  return getARMCPUForMArch(Arch, Triple);
616}
617
618/// getLLVMArchSuffixForARM - Get the LLVM arch name to use for a particular
619/// CPU  (or Arch, if CPU is generic).
620// FIXME: This is redundant with -mcpu, why does LLVM use this.
621StringRef arm::getLLVMArchSuffixForARM(StringRef CPUStringRef Arch,
622                                       const llvm::Triple &Triple) {
623  llvm::ARM::ArchKind ArchKind;
624  if (CPU == "generic") {
625    std::string ARMArch = tools::arm::getARMArch(Arch, Triple);
626    ArchKind = llvm::ARM::parseArch(ARMArch);
627    if (ArchKind == llvm::ARM::ArchKind::INVALID)
628      // In case of generic Arch, i.e. "arm",
629      // extract arch from default cpu of the Triple
630      ArchKind = llvm::ARM::parseCPUArch(Triple.getARMCPUForArch(ARMArch));
631  } else {
632    // FIXME: horrible hack to get around the fact that Cortex-A7 is only an
633    // armv7k triple if it's actually been specified via "-arch armv7k".
634    ArchKind = (Arch == "armv7k" || Arch == "thumbv7k")
635                          ? llvm::ARM::ArchKind::ARMV7K
636                          : llvm::ARM::parseCPUArch(CPU);
637  }
638  if (ArchKind == llvm::ARM::ArchKind::INVALID)
639    return "";
640  return llvm::ARM::getSubArch(ArchKind);
641}
642
643void arm::appendBE8LinkFlag(const ArgList &Args, ArgStringList &CmdArgs,
644                            const llvm::Triple &Triple) {
645  if (Args.hasArg(options::OPT_r))
646    return;
647
648  // ARMv7 (and later) and ARMv6-M do not support BE-32, so instruct the linker
649  // to generate BE-8 executables.
650  if (arm::getARMSubArchVersionNumber(Triple) >= 7 || arm::isARMMProfile(Triple))
651    CmdArgs.push_back("--be8");
652}
653