LLVM 19.0.0git
RISCVISAInfo.cpp
Go to the documentation of this file.
1//===-- RISCVISAInfo.cpp - RISC-V Arch String Parser ----------------------===//
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
10#include "llvm/ADT/MapVector.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SetVector.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/Support/Errc.h"
16#include "llvm/Support/Error.h"
18
19#include <array>
20#include <atomic>
21#include <optional>
22#include <string>
23#include <vector>
24
25using namespace llvm;
26
27namespace {
28
29struct RISCVSupportedExtension {
30 const char *Name;
31 /// Supported version.
33
34 bool operator<(const RISCVSupportedExtension &RHS) const {
35 return StringRef(Name) < StringRef(RHS.Name);
36 }
37};
38
39struct RISCVProfile {
41 StringLiteral MArch;
42};
43
44} // end anonymous namespace
45
46static const char *RISCVGImplications[] = {
47 "i", "m", "a", "f", "d", "zicsr", "zifencei"
48};
49
50#define GET_SUPPORTED_EXTENSIONS
51#include "llvm/TargetParser/RISCVTargetParserDef.inc"
52
53#define GET_SUPPORTED_PROFILES
54#include "llvm/TargetParser/RISCVTargetParserDef.inc"
55
56static void verifyTables() {
57#ifndef NDEBUG
58 static std::atomic<bool> TableChecked(false);
59 if (!TableChecked.load(std::memory_order_relaxed)) {
60 assert(llvm::is_sorted(SupportedExtensions) &&
61 "Extensions are not sorted by name");
62 assert(llvm::is_sorted(SupportedExperimentalExtensions) &&
63 "Experimental extensions are not sorted by name");
64 TableChecked.store(true, std::memory_order_relaxed);
65 }
66#endif
67}
68
70 StringRef Description) {
71 outs().indent(4);
72 unsigned VersionWidth = Description.empty() ? 0 : 10;
73 outs() << left_justify(Name, 21) << left_justify(Version, VersionWidth)
74 << Description << "\n";
75}
76
78
79 outs() << "All available -march extensions for RISC-V\n\n";
80 PrintExtension("Name", "Version", (DescMap.empty() ? "" : "Description"));
81
83 for (const auto &E : SupportedExtensions)
84 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
85 for (const auto &E : ExtMap) {
86 std::string Version =
87 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
88 PrintExtension(E.first, Version, DescMap[E.first]);
89 }
90
91 outs() << "\nExperimental extensions\n";
92 ExtMap.clear();
93 for (const auto &E : SupportedExperimentalExtensions)
94 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
95 for (const auto &E : ExtMap) {
96 std::string Version =
97 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
98 PrintExtension(E.first, Version, DescMap["experimental-" + E.first]);
99 }
100
101 outs() << "\nUse -march to specify the target's extension.\n"
102 "For example, clang -march=rv32i_v1p0\n";
103}
104
106 return Ext.consume_front("experimental-");
107}
108
109// This function finds the last character that doesn't belong to a version
110// (e.g. zba1p0 is extension 'zba' of version '1p0'). So the function will
111// consume [0-9]*p[0-9]* starting from the backward. An extension name will not
112// end with a digit or the letter 'p', so this function will parse correctly.
113// NOTE: This function is NOT able to take empty strings or strings that only
114// have version numbers and no extension name. It assumes the extension name
115// will be at least more than one character.
117 assert(!Ext.empty() &&
118 "Already guarded by if-statement in ::parseArchString");
119
120 int Pos = Ext.size() - 1;
121 while (Pos > 0 && isDigit(Ext[Pos]))
122 Pos--;
123 if (Pos > 0 && Ext[Pos] == 'p' && isDigit(Ext[Pos - 1])) {
124 Pos--;
125 while (Pos > 0 && isDigit(Ext[Pos]))
126 Pos--;
127 }
128 return Pos;
129}
130
131namespace {
132struct LessExtName {
133 bool operator()(const RISCVSupportedExtension &LHS, StringRef RHS) {
134 return StringRef(LHS.Name) < RHS;
135 }
136 bool operator()(StringRef LHS, const RISCVSupportedExtension &RHS) {
137 return LHS < StringRef(RHS.Name);
138 }
139};
140} // namespace
141
142static std::optional<RISCVISAUtils::ExtensionVersion>
144 // Find default version of an extension.
145 // TODO: We might set default version based on profile or ISA spec.
146 for (auto &ExtInfo : {ArrayRef(SupportedExtensions),
147 ArrayRef(SupportedExperimentalExtensions)}) {
148 auto I = llvm::lower_bound(ExtInfo, ExtName, LessExtName());
149
150 if (I == ExtInfo.end() || I->Name != ExtName)
151 continue;
152
153 return I->Version;
154 }
155 return std::nullopt;
156}
157
158void RISCVISAInfo::addExtension(StringRef ExtName,
160 Exts[ExtName.str()] = Version;
161}
162
164 if (Ext.starts_with("s"))
165 return "standard supervisor-level extension";
166 if (Ext.starts_with("x"))
167 return "non-standard user-level extension";
168 if (Ext.starts_with("z"))
169 return "standard user-level extension";
170 return StringRef();
171}
172
174 if (Ext.starts_with("s"))
175 return "s";
176 if (Ext.starts_with("x"))
177 return "x";
178 if (Ext.starts_with("z"))
179 return "z";
180 return StringRef();
181}
182
183static std::optional<RISCVISAUtils::ExtensionVersion>
185 auto I =
186 llvm::lower_bound(SupportedExperimentalExtensions, Ext, LessExtName());
187 if (I == std::end(SupportedExperimentalExtensions) || I->Name != Ext)
188 return std::nullopt;
189
190 return I->Version;
191}
192
194 bool IsExperimental = stripExperimentalPrefix(Ext);
195
197 IsExperimental ? ArrayRef(SupportedExperimentalExtensions)
198 : ArrayRef(SupportedExtensions);
199
200 auto I = llvm::lower_bound(ExtInfo, Ext, LessExtName());
201 return I != ExtInfo.end() && I->Name == Ext;
202}
203
205 verifyTables();
206
207 for (auto ExtInfo : {ArrayRef(SupportedExtensions),
208 ArrayRef(SupportedExperimentalExtensions)}) {
209 auto I = llvm::lower_bound(ExtInfo, Ext, LessExtName());
210 if (I != ExtInfo.end() && I->Name == Ext)
211 return true;
212 }
213
214 return false;
215}
216
217bool RISCVISAInfo::isSupportedExtension(StringRef Ext, unsigned MajorVersion,
218 unsigned MinorVersion) {
219 for (auto ExtInfo : {ArrayRef(SupportedExtensions),
220 ArrayRef(SupportedExperimentalExtensions)}) {
221 auto Range =
222 std::equal_range(ExtInfo.begin(), ExtInfo.end(), Ext, LessExtName());
223 for (auto I = Range.first, E = Range.second; I != E; ++I)
224 if (I->Version.Major == MajorVersion && I->Version.Minor == MinorVersion)
225 return true;
226 }
227
228 return false;
229}
230
233
234 if (!isSupportedExtension(Ext))
235 return false;
236
237 return Exts.count(Ext.str()) != 0;
238}
239
240std::vector<std::string> RISCVISAInfo::toFeatures(bool AddAllExtensions,
241 bool IgnoreUnknown) const {
242 std::vector<std::string> Features;
243 for (const auto &[ExtName, _] : Exts) {
244 // i is a base instruction set, not an extension (see
245 // https://github.com/riscv/riscv-isa-manual/blob/main/src/naming.adoc#base-integer-isa)
246 // and is not recognized in clang -cc1
247 if (ExtName == "i")
248 continue;
249 if (IgnoreUnknown && !isSupportedExtension(ExtName))
250 continue;
251
252 if (isExperimentalExtension(ExtName)) {
253 Features.push_back((llvm::Twine("+experimental-") + ExtName).str());
254 } else {
255 Features.push_back((llvm::Twine("+") + ExtName).str());
256 }
257 }
258 if (AddAllExtensions) {
259 for (const RISCVSupportedExtension &Ext : SupportedExtensions) {
260 if (Exts.count(Ext.Name))
261 continue;
262 Features.push_back((llvm::Twine("-") + Ext.Name).str());
263 }
264
265 for (const RISCVSupportedExtension &Ext : SupportedExperimentalExtensions) {
266 if (Exts.count(Ext.Name))
267 continue;
268 Features.push_back((llvm::Twine("-experimental-") + Ext.Name).str());
269 }
270 }
271 return Features;
272}
273
274static Error getStringErrorForInvalidExt(std::string_view ExtName) {
275 if (ExtName.size() == 1) {
277 "unsupported standard user-level extension '" +
278 ExtName + "'");
279 }
281 "unsupported " + getExtensionTypeDesc(ExtName) +
282 " '" + ExtName + "'");
283}
284
285// Extensions may have a version number, and may be separated by
286// an underscore '_' e.g.: rv32i2_m2.
287// Version number is divided into major and minor version numbers,
288// separated by a 'p'. If the minor version is 0 then 'p0' can be
289// omitted from the version string. E.g., rv32i2p0, rv32i2, rv32i2p1.
290static Error getExtensionVersion(StringRef Ext, StringRef In, unsigned &Major,
291 unsigned &Minor, unsigned &ConsumeLength,
292 bool EnableExperimentalExtension,
293 bool ExperimentalExtensionVersionCheck) {
294 StringRef MajorStr, MinorStr;
295 Major = 0;
296 Minor = 0;
297 ConsumeLength = 0;
298 MajorStr = In.take_while(isDigit);
299 In = In.substr(MajorStr.size());
300
301 if (!MajorStr.empty() && In.consume_front("p")) {
302 MinorStr = In.take_while(isDigit);
303 In = In.substr(MajorStr.size() + MinorStr.size() - 1);
304
305 // Expected 'p' to be followed by minor version number.
306 if (MinorStr.empty()) {
307 return createStringError(
309 "minor version number missing after 'p' for extension '" + Ext + "'");
310 }
311 }
312
313 if (!MajorStr.empty() && MajorStr.getAsInteger(10, Major))
314 return createStringError(
316 "Failed to parse major version number for extension '" + Ext + "'");
317
318 if (!MinorStr.empty() && MinorStr.getAsInteger(10, Minor))
319 return createStringError(
321 "Failed to parse minor version number for extension '" + Ext + "'");
322
323 ConsumeLength = MajorStr.size();
324
325 if (!MinorStr.empty())
326 ConsumeLength += MinorStr.size() + 1 /*'p'*/;
327
328 // Expected multi-character extension with version number to have no
329 // subsequent characters (i.e. must either end string or be followed by
330 // an underscore).
331 if (Ext.size() > 1 && In.size())
332 return createStringError(
334 "multi-character extensions must be separated by underscores");
335
336 // If experimental extension, require use of current version number
337 if (auto ExperimentalExtension = isExperimentalExtension(Ext)) {
338 if (!EnableExperimentalExtension)
340 "requires '-menable-experimental-extensions' "
341 "for experimental extension '" +
342 Ext + "'");
343
344 if (ExperimentalExtensionVersionCheck &&
345 (MajorStr.empty() && MinorStr.empty()))
346 return createStringError(
348 "experimental extension requires explicit version number `" + Ext +
349 "`");
350
351 auto SupportedVers = *ExperimentalExtension;
352 if (ExperimentalExtensionVersionCheck &&
353 (Major != SupportedVers.Major || Minor != SupportedVers.Minor)) {
354 std::string Error = "unsupported version number " + MajorStr.str();
355 if (!MinorStr.empty())
356 Error += "." + MinorStr.str();
357 Error += " for experimental extension '" + Ext.str() +
358 "' (this compiler supports " + utostr(SupportedVers.Major) +
359 "." + utostr(SupportedVers.Minor) + ")";
361 }
362 return Error::success();
363 }
364
365 // Exception rule for `g`, we don't have clear version scheme for that on
366 // ISA spec.
367 if (Ext == "g")
368 return Error::success();
369
370 if (MajorStr.empty() && MinorStr.empty()) {
371 if (auto DefaultVersion = findDefaultVersion(Ext)) {
372 Major = DefaultVersion->Major;
373 Minor = DefaultVersion->Minor;
374 }
375 // No matter found or not, return success, assume other place will
376 // verify.
377 return Error::success();
378 }
379
380 if (RISCVISAInfo::isSupportedExtension(Ext, Major, Minor))
381 return Error::success();
382
384 return getStringErrorForInvalidExt(Ext);
385
386 std::string Error = "unsupported version number " + std::string(MajorStr);
387 if (!MinorStr.empty())
388 Error += "." + MinorStr.str();
389 Error += " for extension '" + Ext.str() + "'";
391}
392
395 const std::vector<std::string> &Features) {
396 assert(XLen == 32 || XLen == 64);
397 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
398
399 for (auto &Feature : Features) {
400 StringRef ExtName = Feature;
401 assert(ExtName.size() > 1 && (ExtName[0] == '+' || ExtName[0] == '-'));
402 bool Add = ExtName[0] == '+';
403 ExtName = ExtName.drop_front(1); // Drop '+' or '-'
404 bool Experimental = stripExperimentalPrefix(ExtName);
405 auto ExtensionInfos = Experimental
406 ? ArrayRef(SupportedExperimentalExtensions)
407 : ArrayRef(SupportedExtensions);
408 auto ExtensionInfoIterator =
409 llvm::lower_bound(ExtensionInfos, ExtName, LessExtName());
410
411 // Not all features is related to ISA extension, like `relax` or
412 // `save-restore`, skip those feature.
413 if (ExtensionInfoIterator == ExtensionInfos.end() ||
414 ExtensionInfoIterator->Name != ExtName)
415 continue;
416
417 if (Add)
418 ISAInfo->addExtension(ExtName, ExtensionInfoIterator->Version);
419 else
420 ISAInfo->Exts.erase(ExtName.str());
421 }
422
423 return RISCVISAInfo::postProcessAndChecking(std::move(ISAInfo));
424}
425
428 if (llvm::any_of(Arch, isupper)) {
430 "string must be lowercase");
431 }
432 // Must start with a valid base ISA name.
433 unsigned XLen;
434 if (Arch.starts_with("rv32i") || Arch.starts_with("rv32e"))
435 XLen = 32;
436 else if (Arch.starts_with("rv64i") || Arch.starts_with("rv64e"))
437 XLen = 64;
438 else
440 "arch string must begin with valid base ISA");
441 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
442 // Discard rv32/rv64 prefix.
443 Arch = Arch.substr(4);
444
445 // Each extension is of the form ${name}${major_version}p${minor_version}
446 // and separated by _. Split by _ and then extract the name and version
447 // information for each extension.
449 Arch.split(Split, '_');
450 for (StringRef Ext : Split) {
451 StringRef Prefix, MinorVersionStr;
452 std::tie(Prefix, MinorVersionStr) = Ext.rsplit('p');
453 if (MinorVersionStr.empty())
455 "extension lacks version in expected format");
456 unsigned MajorVersion, MinorVersion;
457 if (MinorVersionStr.getAsInteger(10, MinorVersion))
459 "failed to parse minor version number");
460
461 // Split Prefix into the extension name and the major version number
462 // (the trailing digits of Prefix).
463 int TrailingDigits = 0;
464 StringRef ExtName = Prefix;
465 while (!ExtName.empty()) {
466 if (!isDigit(ExtName.back()))
467 break;
468 ExtName = ExtName.drop_back(1);
469 TrailingDigits++;
470 }
471 if (!TrailingDigits)
473 "extension lacks version in expected format");
474
475 StringRef MajorVersionStr = Prefix.take_back(TrailingDigits);
476 if (MajorVersionStr.getAsInteger(10, MajorVersion))
478 "failed to parse major version number");
479 ISAInfo->addExtension(ExtName, {MajorVersion, MinorVersion});
480 }
481 ISAInfo->updateFLen();
482 ISAInfo->updateMinVLen();
483 ISAInfo->updateMaxELen();
484 return std::move(ISAInfo);
485}
486
488 std::vector<std::string> &SplitExts) {
490 if (Exts.empty())
491 return Error::success();
492
493 Exts.split(Split, "_");
494
495 for (auto Ext : Split) {
496 if (Ext.empty())
498 "extension name missing after separator '_'");
499
500 SplitExts.push_back(Ext.str());
501 }
502 return Error::success();
503}
504
506 StringRef RawExt,
508 std::map<std::string, unsigned>> &SeenExtMap,
509 bool IgnoreUnknown, bool EnableExperimentalExtension,
510 bool ExperimentalExtensionVersionCheck) {
513 auto Pos = findLastNonVersionCharacter(RawExt) + 1;
514 StringRef Name(RawExt.substr(0, Pos));
515 StringRef Vers(RawExt.substr(Pos));
516
517 if (Type.empty()) {
518 if (IgnoreUnknown)
519 return Error::success();
521 "invalid extension prefix '" + RawExt + "'");
522 }
523
524 if (!IgnoreUnknown && Name.size() == Type.size())
526 Desc + " name missing after '" + Type + "'");
527
528 unsigned Major, Minor, ConsumeLength;
529 if (auto E = getExtensionVersion(Name, Vers, Major, Minor, ConsumeLength,
530 EnableExperimentalExtension,
531 ExperimentalExtensionVersionCheck)) {
532 if (IgnoreUnknown) {
533 consumeError(std::move(E));
534 return Error::success();
535 }
536 return E;
537 }
538
539 // Check if duplicated extension.
540 if (!IgnoreUnknown && SeenExtMap.contains(Name.str()))
542 "duplicated " + Desc + " '" + Name + "'");
543
544 if (IgnoreUnknown && !RISCVISAInfo::isSupportedExtension(Name))
545 return Error::success();
546
547 SeenExtMap[Name.str()] = {Major, Minor};
548 return Error::success();
549}
550
552 StringRef &RawExt,
554 std::map<std::string, unsigned>> &SeenExtMap,
555 bool IgnoreUnknown, bool EnableExperimentalExtension,
556 bool ExperimentalExtensionVersionCheck) {
557 unsigned Major, Minor, ConsumeLength;
558 StringRef Name = RawExt.take_front(1);
559 RawExt.consume_front(Name);
560 if (auto E = getExtensionVersion(Name, RawExt, Major, Minor, ConsumeLength,
561 EnableExperimentalExtension,
562 ExperimentalExtensionVersionCheck)) {
563 if (IgnoreUnknown) {
564 consumeError(std::move(E));
565 RawExt = RawExt.substr(ConsumeLength);
566 return Error::success();
567 }
568 return E;
569 }
570
571 RawExt = RawExt.substr(ConsumeLength);
572
573 // Check if duplicated extension.
574 if (!IgnoreUnknown && SeenExtMap.contains(Name.str()))
576 "duplicated standard user-level extension '" +
577 Name + "'");
578
579 if (IgnoreUnknown && !RISCVISAInfo::isSupportedExtension(Name))
580 return Error::success();
581
582 SeenExtMap[Name.str()] = {Major, Minor};
583 return Error::success();
584}
585
587RISCVISAInfo::parseArchString(StringRef Arch, bool EnableExperimentalExtension,
588 bool ExperimentalExtensionVersionCheck,
589 bool IgnoreUnknown) {
590 // RISC-V ISA strings must be lowercase.
591 if (llvm::any_of(Arch, isupper)) {
593 "string must be lowercase");
594 }
595
596 if (Arch.starts_with("rvi") || Arch.starts_with("rva") ||
597 Arch.starts_with("rvb") || Arch.starts_with("rvm")) {
598 const auto *FoundProfile =
599 llvm::find_if(SupportedProfiles, [Arch](const RISCVProfile &Profile) {
600 return Arch.starts_with(Profile.Name);
601 });
602
603 if (FoundProfile == std::end(SupportedProfiles))
604 return createStringError(errc::invalid_argument, "unsupported profile");
605
606 std::string NewArch = FoundProfile->MArch.str();
607 StringRef ArchWithoutProfile = Arch.substr(FoundProfile->Name.size());
608 if (!ArchWithoutProfile.empty()) {
609 if (!ArchWithoutProfile.starts_with("_"))
610 return createStringError(
612 "additional extensions must be after separator '_'");
613 NewArch += ArchWithoutProfile.str();
614 }
615 return parseArchString(NewArch, EnableExperimentalExtension,
616 ExperimentalExtensionVersionCheck, IgnoreUnknown);
617 }
618
619 bool HasRV64 = Arch.starts_with("rv64");
620 // ISA string must begin with rv32 or rv64.
621 if (!(Arch.starts_with("rv32") || HasRV64) || (Arch.size() < 5)) {
622 return createStringError(
624 "string must begin with rv32{i,e,g} or rv64{i,e,g}");
625 }
626
627 unsigned XLen = HasRV64 ? 64 : 32;
628 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
630 std::map<std::string, unsigned>>
631 SeenExtMap;
632
633 // The canonical order specified in ISA manual.
634 // Ref: Table 22.1 in RISC-V User-Level ISA V2.2
635 char Baseline = Arch[4];
636
637 // First letter should be 'e', 'i' or 'g'.
638 switch (Baseline) {
639 default:
641 "first letter after \'" + Arch.slice(0, 4) +
642 "\' should be 'e', 'i' or 'g'");
643 case 'e':
644 case 'i':
645 break;
646 case 'g':
647 // g expands to extensions in RISCVGImplications.
648 if (Arch.size() > 5 && isDigit(Arch[5]))
650 "version not supported for 'g'");
651 break;
652 }
653
654 if (Arch.back() == '_')
656 "extension name missing after separator '_'");
657
658 // Skip rvxxx
659 StringRef Exts = Arch.substr(5);
660
661 unsigned Major, Minor, ConsumeLength;
662 if (Baseline == 'g') {
663 // Versions for g are disallowed, and this was checked for previously.
664 ConsumeLength = 0;
665
666 // No matter which version is given to `g`, we always set imafd to default
667 // version since the we don't have clear version scheme for that on
668 // ISA spec.
669 for (const auto *Ext : RISCVGImplications) {
670 auto Version = findDefaultVersion(Ext);
671 assert(Version && "Default extension version not found?");
672 // Postpone AddExtension until end of this function
673 SeenExtMap[Ext] = {Version->Major, Version->Minor};
674 }
675 } else {
676 // Baseline is `i` or `e`
677 if (auto E = getExtensionVersion(
678 StringRef(&Baseline, 1), Exts, Major, Minor, ConsumeLength,
679 EnableExperimentalExtension, ExperimentalExtensionVersionCheck)) {
680 if (!IgnoreUnknown)
681 return std::move(E);
682 // If IgnoreUnknown, then ignore an unrecognised version of the baseline
683 // ISA and just use the default supported version.
684 consumeError(std::move(E));
685 auto Version = findDefaultVersion(StringRef(&Baseline, 1));
686 Major = Version->Major;
687 Minor = Version->Minor;
688 }
689
690 // Postpone AddExtension until end of this function
691 SeenExtMap[StringRef(&Baseline, 1).str()] = {Major, Minor};
692 }
693
694 // Consume the base ISA version number and any '_' between rvxxx and the
695 // first extension
696 Exts = Exts.drop_front(ConsumeLength);
697 Exts.consume_front("_");
698
699 std::vector<std::string> SplitExts;
700 if (auto E = splitExtsByUnderscore(Exts, SplitExts))
701 return std::move(E);
702
703 for (auto &Ext : SplitExts) {
704 StringRef CurrExt = Ext;
705 while (!CurrExt.empty()) {
707 if (auto E = processSingleLetterExtension(
708 CurrExt, SeenExtMap, IgnoreUnknown, EnableExperimentalExtension,
709 ExperimentalExtensionVersionCheck))
710 return std::move(E);
711 } else if (CurrExt.front() == 'z' || CurrExt.front() == 's' ||
712 CurrExt.front() == 'x') {
713 // Handle other types of extensions other than the standard
714 // general purpose and standard user-level extensions.
715 // Parse the ISA string containing non-standard user-level
716 // extensions, standard supervisor-level extensions and
717 // non-standard supervisor-level extensions.
718 // These extensions start with 'z', 's', 'x' prefixes, might have a
719 // version number (major, minor) and are separated by a single
720 // underscore '_'. We do not enforce a canonical order for them.
721 if (auto E = processMultiLetterExtension(
722 CurrExt, SeenExtMap, IgnoreUnknown, EnableExperimentalExtension,
723 ExperimentalExtensionVersionCheck))
724 return std::move(E);
725 // Multi-letter extension must be seperate following extension with
726 // underscore
727 break;
728 } else {
729 // FIXME: Could it be ignored by IgnoreUnknown?
731 "invalid standard user-level extension '" +
732 Twine(CurrExt.front()) + "'");
733 }
734 }
735 }
736
737 // Check all Extensions are supported.
738 for (auto &SeenExtAndVers : SeenExtMap) {
739 const std::string &ExtName = SeenExtAndVers.first;
740 RISCVISAUtils::ExtensionVersion ExtVers = SeenExtAndVers.second;
741
743 return getStringErrorForInvalidExt(ExtName);
744 ISAInfo->addExtension(ExtName, ExtVers);
745 }
746
747 return RISCVISAInfo::postProcessAndChecking(std::move(ISAInfo));
748}
749
750Error RISCVISAInfo::checkDependency() {
751 bool HasC = Exts.count("c") != 0;
752 bool HasF = Exts.count("f") != 0;
753 bool HasZfinx = Exts.count("zfinx") != 0;
754 bool HasVector = Exts.count("zve32x") != 0;
755 bool HasZvl = MinVLen != 0;
756 bool HasZcmt = Exts.count("zcmt") != 0;
757
758 if (HasF && HasZfinx)
760 "'f' and 'zfinx' extensions are incompatible");
761
762 if (HasZvl && !HasVector)
763 return createStringError(
765 "'zvl*b' requires 'v' or 'zve*' extension to also be specified");
766
767 if (Exts.count("zvbb") && !HasVector)
768 return createStringError(
770 "'zvbb' requires 'v' or 'zve*' extension to also be specified");
771
772 if (Exts.count("zvbc") && !Exts.count("zve64x"))
773 return createStringError(
775 "'zvbc' requires 'v' or 'zve64*' extension to also be specified");
776
777 if ((Exts.count("zvkb") || Exts.count("zvkg") || Exts.count("zvkned") ||
778 Exts.count("zvknha") || Exts.count("zvksed") || Exts.count("zvksh")) &&
779 !HasVector)
780 return createStringError(
782 "'zvk*' requires 'v' or 'zve*' extension to also be specified");
783
784 if (Exts.count("zvknhb") && !Exts.count("zve64x"))
785 return createStringError(
787 "'zvknhb' requires 'v' or 'zve64*' extension to also be specified");
788
789 if ((HasZcmt || Exts.count("zcmp")) && Exts.count("d") &&
790 (HasC || Exts.count("zcd")))
791 return createStringError(
793 Twine("'") + (HasZcmt ? "zcmt" : "zcmp") +
794 "' extension is incompatible with '" + (HasC ? "c" : "zcd") +
795 "' extension when 'd' extension is enabled");
796
797 if (XLen != 32 && Exts.count("zcf"))
799 "'zcf' is only supported for 'rv32'");
800
801 if (Exts.count("zacas") && !(Exts.count("a") || Exts.count("zamo")))
802 return createStringError(
804 "'zacas' requires 'a' or 'zaamo' extension to also be specified");
805
806 if (Exts.count("zabha") && !(Exts.count("a") || Exts.count("zamo")))
807 return createStringError(
809 "'zabha' requires 'a' or 'zaamo' extension to also be specified");
810
811 return Error::success();
812}
813
816 const char *ImpliedExt;
817
818 bool operator<(const ImpliedExtsEntry &Other) const {
819 return Name < Other.Name;
820 }
821};
822
823static bool operator<(const ImpliedExtsEntry &LHS, StringRef RHS) {
824 return LHS.Name < RHS;
825}
826
827static bool operator<(StringRef LHS, const ImpliedExtsEntry &RHS) {
828 return LHS < RHS.Name;
829}
830
831#define GET_IMPLIED_EXTENSIONS
832#include "llvm/TargetParser/RISCVTargetParserDef.inc"
833
834void RISCVISAInfo::updateImplication() {
835 bool HasE = Exts.count("e") != 0;
836 bool HasI = Exts.count("i") != 0;
837
838 // If not in e extension and i extension does not exist, i extension is
839 // implied
840 if (!HasE && !HasI) {
841 auto Version = findDefaultVersion("i");
842 addExtension("i", Version.value());
843 }
844
845 assert(llvm::is_sorted(ImpliedExts) && "Table not sorted by Name");
846
847 // This loop may execute over 1 iteration since implication can be layered
848 // Exits loop if no more implication is applied
850 for (auto const &Ext : Exts)
851 WorkList.insert(Ext.first);
852
853 while (!WorkList.empty()) {
854 StringRef ExtName = WorkList.pop_back_val();
855 auto Range = std::equal_range(std::begin(ImpliedExts),
856 std::end(ImpliedExts), ExtName);
857 std::for_each(Range.first, Range.second,
858 [&](const ImpliedExtsEntry &Implied) {
859 const char *ImpliedExt = Implied.ImpliedExt;
860 if (WorkList.count(ImpliedExt))
861 return;
862 if (Exts.count(ImpliedExt))
863 return;
864 auto Version = findDefaultVersion(ImpliedExt);
865 addExtension(ImpliedExt, Version.value());
866 WorkList.insert(ImpliedExt);
867 });
868 }
869
870 // Add Zcf if Zce and F are enabled on RV32.
871 if (XLen == 32 && Exts.count("zce") && Exts.count("f") &&
872 !Exts.count("zcf")) {
873 auto Version = findDefaultVersion("zcf");
874 addExtension("zcf", Version.value());
875 }
876}
877
878static constexpr StringLiteral CombineIntoExts[] = {
879 {"zk"}, {"zkn"}, {"zks"}, {"zvkn"}, {"zvknc"},
880 {"zvkng"}, {"zvks"}, {"zvksc"}, {"zvksg"},
881};
882
883void RISCVISAInfo::updateCombination() {
884 bool MadeChange = false;
885 do {
886 MadeChange = false;
887 for (StringRef CombineExt : CombineIntoExts) {
888 if (hasExtension(CombineExt))
889 continue;
890
891 // Look up the extension in the ImpliesExt table to find everything it
892 // depends on.
893 auto Range = std::equal_range(std::begin(ImpliedExts),
894 std::end(ImpliedExts), CombineExt);
895 bool HasAllRequiredFeatures = std::all_of(
896 Range.first, Range.second, [&](const ImpliedExtsEntry &Implied) {
897 return hasExtension(Implied.ImpliedExt);
898 });
899 if (HasAllRequiredFeatures) {
900 auto Version = findDefaultVersion(CombineExt);
901 addExtension(CombineExt, Version.value());
902 MadeChange = true;
903 }
904 }
905 } while (MadeChange);
906}
907
908void RISCVISAInfo::updateFLen() {
909 FLen = 0;
910 // TODO: Handle q extension.
911 if (Exts.count("d"))
912 FLen = 64;
913 else if (Exts.count("f"))
914 FLen = 32;
915}
916
917void RISCVISAInfo::updateMinVLen() {
918 for (auto const &Ext : Exts) {
919 StringRef ExtName = Ext.first;
920 bool IsZvlExt = ExtName.consume_front("zvl") && ExtName.consume_back("b");
921 if (IsZvlExt) {
922 unsigned ZvlLen;
923 if (!ExtName.getAsInteger(10, ZvlLen))
924 MinVLen = std::max(MinVLen, ZvlLen);
925 }
926 }
927}
928
929void RISCVISAInfo::updateMaxELen() {
930 // handles EEW restriction by sub-extension zve
931 for (auto const &Ext : Exts) {
932 StringRef ExtName = Ext.first;
933 bool IsZveExt = ExtName.consume_front("zve");
934 if (IsZveExt) {
935 if (ExtName.back() == 'f')
936 MaxELenFp = std::max(MaxELenFp, 32u);
937 if (ExtName.back() == 'd')
938 MaxELenFp = std::max(MaxELenFp, 64u);
939 ExtName = ExtName.drop_back();
940 unsigned ZveELen;
941 ExtName.getAsInteger(10, ZveELen);
942 MaxELen = std::max(MaxELen, ZveELen);
943 }
944 }
945}
946
947std::string RISCVISAInfo::toString() const {
948 std::string Buffer;
949 raw_string_ostream Arch(Buffer);
950
951 Arch << "rv" << XLen;
952
953 ListSeparator LS("_");
954 for (auto const &Ext : Exts) {
955 StringRef ExtName = Ext.first;
956 auto ExtInfo = Ext.second;
957 Arch << LS << ExtName;
958 Arch << ExtInfo.Major << "p" << ExtInfo.Minor;
959 }
960
961 return Arch.str();
962}
963
965RISCVISAInfo::postProcessAndChecking(std::unique_ptr<RISCVISAInfo> &&ISAInfo) {
966 ISAInfo->updateImplication();
967 ISAInfo->updateCombination();
968 ISAInfo->updateFLen();
969 ISAInfo->updateMinVLen();
970 ISAInfo->updateMaxELen();
971
972 if (Error Result = ISAInfo->checkDependency())
973 return std::move(Result);
974 return std::move(ISAInfo);
975}
976
978 if (XLen == 32) {
979 if (hasExtension("e"))
980 return "ilp32e";
981 if (hasExtension("d"))
982 return "ilp32d";
983 if (hasExtension("f"))
984 return "ilp32f";
985 return "ilp32";
986 } else if (XLen == 64) {
987 if (hasExtension("e"))
988 return "lp64e";
989 if (hasExtension("d"))
990 return "lp64d";
991 if (hasExtension("f"))
992 return "lp64f";
993 return "lp64";
994 }
995 llvm_unreachable("Invalid XLEN");
996}
997
999 if (Ext.empty())
1000 return false;
1001
1002 auto Pos = findLastNonVersionCharacter(Ext) + 1;
1003 StringRef Name = Ext.substr(0, Pos);
1004 StringRef Vers = Ext.substr(Pos);
1005 if (Vers.empty())
1006 return false;
1007
1008 unsigned Major, Minor, ConsumeLength;
1009 if (auto E = getExtensionVersion(Name, Vers, Major, Minor, ConsumeLength,
1010 true, true)) {
1011 consumeError(std::move(E));
1012 return false;
1013 }
1014
1015 return true;
1016}
1017
1019 if (Ext.empty())
1020 return std::string();
1021
1022 auto Pos = findLastNonVersionCharacter(Ext) + 1;
1023 StringRef Name = Ext.substr(0, Pos);
1024
1025 if (Pos != Ext.size() && !isSupportedExtensionWithVersion(Ext))
1026 return std::string();
1027
1029 return std::string();
1030
1031 return isExperimentalExtension(Name) ? "experimental-" + Name.str()
1032 : Name.str();
1033}
std::string Name
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1291
#define _
#define I(x, y, z)
Definition: MD5.cpp:58
Load MIR Sample Profile
This file implements a map that provides insertion order iteration.
static void verifyTables()
static StringRef getExtensionTypeDesc(StringRef Ext)
static Error processSingleLetterExtension(StringRef &RawExt, MapVector< std::string, RISCVISAUtils::ExtensionVersion, std::map< std::string, unsigned > > &SeenExtMap, bool IgnoreUnknown, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck)
static std::optional< RISCVISAUtils::ExtensionVersion > findDefaultVersion(StringRef ExtName)
static size_t findLastNonVersionCharacter(StringRef Ext)
static StringRef getExtensionType(StringRef Ext)
static constexpr StringLiteral CombineIntoExts[]
static bool stripExperimentalPrefix(StringRef &Ext)
static Error processMultiLetterExtension(StringRef RawExt, MapVector< std::string, RISCVISAUtils::ExtensionVersion, std::map< std::string, unsigned > > &SeenExtMap, bool IgnoreUnknown, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck)
static std::optional< RISCVISAUtils::ExtensionVersion > isExperimentalExtension(StringRef Ext)
static void PrintExtension(StringRef Name, StringRef Version, StringRef Description)
static bool operator<(const ImpliedExtsEntry &LHS, StringRef RHS)
static Error getExtensionVersion(StringRef Ext, StringRef In, unsigned &Major, unsigned &Minor, unsigned &ConsumeLength, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck)
static const char * RISCVGImplications[]
static Error getStringErrorForInvalidExt(std::string_view ExtName)
static Error splitExtsByUnderscore(StringRef Exts, std::vector< std::string > &SplitExts)
static bool isDigit(const char C)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
This file contains some templates that are useful if you are working with the STL at all.
This file implements a set that has insertion order iteration characteristics.
This file contains some functions that are useful when dealing with strings.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:469
static void verifyTables()
Value * RHS
Value * LHS
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition: ArrayRef.h:41
iterator end() const
Definition: ArrayRef.h:154
Lightweight error class with error context and mandatory checking.
Definition: Error.h:160
static ErrorSuccess success()
Create a success value.
Definition: Error.h:334
Tagged union holding either a T or a Error.
Definition: Error.h:474
This class implements a map that also provides access to all stored values in a deterministic order.
Definition: MapVector.h:36
static bool isSupportedExtensionFeature(StringRef Ext)
static std::string getTargetFeatureForExtension(StringRef Ext)
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseNormalizedArchString(StringRef Arch)
Parse RISC-V ISA info from an arch string that is already in normalized form (as defined in the psABI...
bool hasExtension(StringRef Ext) const
std::string toString() const
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > postProcessAndChecking(std::unique_ptr< RISCVISAInfo > &&ISAInfo)
StringRef computeDefaultABI() const
static bool isSupportedExtension(StringRef Ext)
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseFeatures(unsigned XLen, const std::vector< std::string > &Features)
Parse RISC-V ISA info from feature vector.
std::vector< std::string > toFeatures(bool AddAllExtensions=false, bool IgnoreUnknown=true) const
Convert RISC-V ISA info to a feature vector.
static llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseArchString(StringRef Arch, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck=true, bool IgnoreUnknown=false)
Parse RISC-V ISA info from arch string.
static bool isSupportedExtensionWithVersion(StringRef Ext)
bool empty() const
Determine if the SetVector is empty or not.
Definition: SetVector.h:93
bool insert(const value_type &X)
Insert a new element into the SetVector.
Definition: SetVector.h:162
value_type pop_back_val()
Definition: SetVector.h:285
A SetVector that performs no allocations if smaller than a certain size.
Definition: SetVector.h:370
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1209
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:845
bool empty() const
Definition: StringMap.h:102
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:127
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:50
std::pair< StringRef, StringRef > split(char Separator) const
Split into two substrings around the first occurrence of a separator character.
Definition: StringRef.h:692
bool consume_back(StringRef Suffix)
Returns true if this StringRef has the given suffix and removes that suffix.
Definition: StringRef.h:647
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:462
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:222
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:563
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:257
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:134
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:601
char back() const
back - Get the last character in the string.
Definition: StringRef.h:146
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition: StringRef.h:676
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:137
char front() const
front - Get the first character in the string.
Definition: StringRef.h:140
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:627
StringRef take_front(size_t N=1) const
Return a StringRef equal to 'this' but with only the first N elements remaining.
Definition: StringRef.h:572
StringRef drop_back(size_t N=1) const
Return a StringRef equal to 'this' but with the last N elements dropped.
Definition: StringRef.h:608
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
The instances of the Type class are immutable: once they are created, they are never changed.
Definition: Type.h:45
raw_ostream & indent(unsigned NumSpaces)
indent - Insert 'NumSpaces' spaces.
A raw_ostream that writes to an std::string.
Definition: raw_ostream.h:660
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:678
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
const uint64_t Version
Definition: InstrProf.h:1153
constexpr StringLiteral AllStdExts
Definition: RISCVISAUtils.h:23
std::map< std::string, ExtensionVersion, ExtensionComparator > OrderedExtensionMap
OrderedExtensionMap is std::map, it's specialized to keep entries in canonical order of extension.
Definition: RISCVISAUtils.h:43
This is an optimization pass for GlobalISel generic memory operations.
Definition: AddressRanges.h:18
bool operator<(int64_t V1, const APSInt &V2)
Definition: APSInt.h:361
raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1258
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1729
bool is_sorted(R &&Range, Compare C)
Wrapper function around std::is_sorted to check if elements in a range R are sorted with respect to a...
Definition: STLExtras.h:1902
void riscvExtensionsHelp(StringMap< StringRef > DescMap)
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:146
auto lower_bound(R &&Range, T &&Value)
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1954
@ Add
Sum of integers.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1749
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1041
StringLiteral Name
bool operator<(const ImpliedExtsEntry &Other) const
const char * ImpliedExt
Description of the encoding of one expression Op.
Represents the major and version number components of a RISC-V extension.
Definition: RISCVISAUtils.h:26