LLVM 22.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/STLExtras.h"
12#include "llvm/ADT/StringRef.h"
13#include "llvm/Support/Errc.h"
14#include "llvm/Support/Error.h"
16
17#include <array>
18#include <atomic>
19#include <optional>
20#include <string>
21#include <vector>
22
23using namespace llvm;
24
25namespace {
26
27struct RISCVSupportedExtension {
28 const char *Name;
29 /// Supported version.
31
32 bool operator<(const RISCVSupportedExtension &RHS) const {
33 return StringRef(Name) < StringRef(RHS.Name);
34 }
35};
36
37struct RISCVProfile {
39 StringLiteral MArch;
40
41 bool operator<(const RISCVProfile &RHS) const {
42 return StringRef(Name) < StringRef(RHS.Name);
43 }
44};
45
46} // end anonymous namespace
47
48static const char *RISCVGImplications[] = {"i", "m", "a", "f", "d"};
49static const char *RISCVGImplicationsZi[] = {"zicsr", "zifencei"};
50
51#define GET_SUPPORTED_EXTENSIONS
52#include "llvm/TargetParser/RISCVTargetParserDef.inc"
53
54#define GET_SUPPORTED_PROFILES
55#include "llvm/TargetParser/RISCVTargetParserDef.inc"
56
57static void verifyTables() {
58#ifndef NDEBUG
59 static std::atomic<bool> TableChecked(false);
60 if (!TableChecked.load(std::memory_order_relaxed)) {
61 assert(llvm::is_sorted(SupportedExtensions) &&
62 "Extensions are not sorted by name");
63 assert(llvm::is_sorted(SupportedExperimentalExtensions) &&
64 "Experimental extensions are not sorted by name");
65 assert(llvm::is_sorted(SupportedProfiles) &&
66 "Profiles are not sorted by name");
67 assert(llvm::is_sorted(SupportedExperimentalProfiles) &&
68 "Experimental profiles are not sorted by name");
69 TableChecked.store(true, std::memory_order_relaxed);
70 }
71#endif
72}
73
75 StringRef Description) {
76 outs().indent(4);
77 unsigned VersionWidth = Description.empty() ? 0 : 10;
78 outs() << left_justify(Name, 21) << left_justify(Version, VersionWidth)
79 << Description << "\n";
80}
81
83 outs() << "All available -march extensions for RISC-V\n\n";
84 PrintExtension("Name", "Version", (DescMap.empty() ? "" : "Description"));
85
87 for (const auto &E : SupportedExtensions)
88 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
89 for (const auto &E : ExtMap) {
90 std::string Version =
91 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
92 PrintExtension(E.first, Version, DescMap[E.first]);
93 }
94
95 outs() << "\nExperimental extensions\n";
96 ExtMap.clear();
97 for (const auto &E : SupportedExperimentalExtensions)
98 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
99 for (const auto &E : ExtMap) {
100 std::string Version =
101 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
102 PrintExtension(E.first, Version, DescMap["experimental-" + E.first]);
103 }
104
105 outs() << "\nSupported Profiles\n";
106 for (const auto &P : SupportedProfiles)
107 outs().indent(4) << P.Name << "\n";
108
109 outs() << "\nExperimental Profiles\n";
110 for (const auto &P : SupportedExperimentalProfiles)
111 outs().indent(4) << P.Name << "\n";
112
113 outs() << "\nUse -march to specify the target's extension.\n"
114 "For example, clang -march=rv32i_v1p0\n";
115}
116
118 bool IsRV64, std::set<StringRef> &EnabledFeatureNames,
119 StringMap<StringRef> &DescMap) {
120 outs() << "Extensions enabled for the given RISC-V target\n\n";
121 PrintExtension("Name", "Version", (DescMap.empty() ? "" : "Description"));
122
125 for (const auto &E : SupportedExtensions)
126 if (EnabledFeatureNames.count(E.Name) != 0) {
127 FullExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
128 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
129 }
130 for (const auto &E : ExtMap) {
131 std::string Version =
132 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
133 PrintExtension(E.first, Version, DescMap[E.first]);
134 }
135
136 outs() << "\nExperimental extensions\n";
137 ExtMap.clear();
138 for (const auto &E : SupportedExperimentalExtensions) {
139 StringRef Name(E.Name);
140 if (EnabledFeatureNames.count("experimental-" + Name.str()) != 0) {
141 FullExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
142 ExtMap[E.Name] = {E.Version.Major, E.Version.Minor};
143 }
144 }
145 for (const auto &E : ExtMap) {
146 std::string Version =
147 std::to_string(E.second.Major) + "." + std::to_string(E.second.Minor);
148 PrintExtension(E.first, Version, DescMap["experimental-" + E.first]);
149 }
150
151 unsigned XLen = IsRV64 ? 64 : 32;
152 if (auto ISAString = RISCVISAInfo::createFromExtMap(XLen, FullExtMap))
153 outs() << "\nISA String: " << ISAString.get()->toString() << "\n";
154}
155
157 return Ext.consume_front("experimental-");
158}
159
160// This function finds the last character that doesn't belong to a version
161// (e.g. zba1p0 is extension 'zba' of version '1p0'). So the function will
162// consume [0-9]*p[0-9]* starting from the backward. An extension name will not
163// end with a digit or the letter 'p', so this function will parse correctly.
164// NOTE: This function is NOT able to take empty strings or strings that only
165// have version numbers and no extension name. It assumes the extension name
166// will be at least more than one character.
168 assert(!Ext.empty() &&
169 "Already guarded by if-statement in ::parseArchString");
170
171 int Pos = Ext.size() - 1;
172 while (Pos > 0 && isDigit(Ext[Pos]))
173 Pos--;
174 if (Pos > 0 && Ext[Pos] == 'p' && isDigit(Ext[Pos - 1])) {
175 Pos--;
176 while (Pos > 0 && isDigit(Ext[Pos]))
177 Pos--;
178 }
179 return Pos;
180}
181
182namespace {
183struct LessExtName {
184 bool operator()(const RISCVSupportedExtension &LHS, StringRef RHS) {
185 return StringRef(LHS.Name) < RHS;
186 }
187 bool operator()(StringRef LHS, const RISCVSupportedExtension &RHS) {
188 return LHS < StringRef(RHS.Name);
189 }
190};
191} // namespace
192
193static std::optional<RISCVISAUtils::ExtensionVersion>
195 // Find default version of an extension.
196 // TODO: We might set default version based on profile or ISA spec.
197 for (auto &ExtInfo : {ArrayRef(SupportedExtensions),
198 ArrayRef(SupportedExperimentalExtensions)}) {
199 auto I = llvm::lower_bound(ExtInfo, ExtName, LessExtName());
200
201 if (I == ExtInfo.end() || I->Name != ExtName)
202 continue;
203
204 return I->Version;
205 }
206 return std::nullopt;
207}
208
210 if (Ext.starts_with('s'))
211 return "standard supervisor-level extension";
212 if (Ext.starts_with('x'))
213 return "non-standard user-level extension";
214 if (Ext.starts_with('z'))
215 return "standard user-level extension";
216 return StringRef();
217}
218
220 if (Ext.starts_with('s'))
221 return "s";
222 if (Ext.starts_with('x'))
223 return "x";
224 if (Ext.starts_with('z'))
225 return "z";
226 return StringRef();
227}
228
229static std::optional<RISCVISAUtils::ExtensionVersion>
231 auto I =
232 llvm::lower_bound(SupportedExperimentalExtensions, Ext, LessExtName());
233 if (I == std::end(SupportedExperimentalExtensions) || I->Name != Ext)
234 return std::nullopt;
235
236 return I->Version;
237}
238
240 bool IsExperimental = stripExperimentalPrefix(Ext);
241
243 IsExperimental ? ArrayRef(SupportedExperimentalExtensions)
244 : ArrayRef(SupportedExtensions);
245
246 auto I = llvm::lower_bound(ExtInfo, Ext, LessExtName());
247 return I != ExtInfo.end() && I->Name == Ext;
248}
249
251 verifyTables();
252
253 for (auto ExtInfo : {ArrayRef(SupportedExtensions),
254 ArrayRef(SupportedExperimentalExtensions)}) {
255 auto I = llvm::lower_bound(ExtInfo, Ext, LessExtName());
256 if (I != ExtInfo.end() && I->Name == Ext)
257 return true;
258 }
259
260 return false;
261}
262
263bool RISCVISAInfo::isSupportedExtension(StringRef Ext, unsigned MajorVersion,
264 unsigned MinorVersion) {
265 for (auto ExtInfo : {ArrayRef(SupportedExtensions),
266 ArrayRef(SupportedExperimentalExtensions)}) {
267 auto Range =
268 std::equal_range(ExtInfo.begin(), ExtInfo.end(), Ext, LessExtName());
269 for (auto I = Range.first, E = Range.second; I != E; ++I)
270 if (I->Version.Major == MajorVersion && I->Version.Minor == MinorVersion)
271 return true;
272 }
273
274 return false;
275}
276
279
280 if (!isSupportedExtension(Ext))
281 return false;
282
283 return Exts.count(Ext.str()) != 0;
284}
285
286std::vector<std::string> RISCVISAInfo::toFeatures(bool AddAllExtensions,
287 bool IgnoreUnknown) const {
288 std::vector<std::string> Features;
289 for (const auto &[ExtName, _] : Exts) {
290 // i is a base instruction set, not an extension (see
291 // https://github.com/riscv/riscv-isa-manual/blob/main/src/naming.adoc#base-integer-isa)
292 // and is not recognized in clang -cc1
293 if (ExtName == "i")
294 continue;
295 if (IgnoreUnknown && !isSupportedExtension(ExtName))
296 continue;
297
298 if (isExperimentalExtension(ExtName)) {
299 Features.push_back((llvm::Twine("+experimental-") + ExtName).str());
300 } else {
301 Features.push_back((llvm::Twine("+") + ExtName).str());
302 }
303 }
304 if (AddAllExtensions) {
305 for (const RISCVSupportedExtension &Ext : SupportedExtensions) {
306 if (Exts.count(Ext.Name))
307 continue;
308 Features.push_back((llvm::Twine("-") + Ext.Name).str());
309 }
310
311 for (const RISCVSupportedExtension &Ext : SupportedExperimentalExtensions) {
312 if (Exts.count(Ext.Name))
313 continue;
314 Features.push_back((llvm::Twine("-experimental-") + Ext.Name).str());
315 }
316 }
317 return Features;
318}
319
320static Error getError(const Twine &Message) {
322}
323
325 if (ExtName.size() == 1) {
326 return getError("unsupported standard user-level extension '" + ExtName +
327 "'");
328 }
329 return getError("unsupported " + getExtensionTypeDesc(ExtName) + " '" +
330 ExtName + "'");
331}
332
333// Extensions may have a version number, and may be separated by
334// an underscore '_' e.g.: rv32i2_m2.
335// Version number is divided into major and minor version numbers,
336// separated by a 'p'. If the minor version is 0 then 'p0' can be
337// omitted from the version string. E.g., rv32i2p0, rv32i2, rv32i2p1.
338static Error getExtensionVersion(StringRef Ext, StringRef In, unsigned &Major,
339 unsigned &Minor, unsigned &ConsumeLength,
340 bool EnableExperimentalExtension,
341 bool ExperimentalExtensionVersionCheck) {
342 StringRef MajorStr, MinorStr;
343 Major = 0;
344 Minor = 0;
345 ConsumeLength = 0;
346 MajorStr = In.take_while(isDigit);
347 In = In.substr(MajorStr.size());
348
349 if (!MajorStr.empty() && In.consume_front("p")) {
350 MinorStr = In.take_while(isDigit);
351 In = In.substr(MajorStr.size() + MinorStr.size() - 1);
352
353 // Expected 'p' to be followed by minor version number.
354 if (MinorStr.empty()) {
355 return getError("minor version number missing after 'p' for extension '" +
356 Ext + "'");
357 }
358 }
359
360 if (!MajorStr.empty() && MajorStr.getAsInteger(10, Major))
361 return getError("Failed to parse major version number for extension '" +
362 Ext + "'");
363
364 if (!MinorStr.empty() && MinorStr.getAsInteger(10, Minor))
365 return getError("Failed to parse minor version number for extension '" +
366 Ext + "'");
367
368 ConsumeLength = MajorStr.size();
369
370 if (!MinorStr.empty())
371 ConsumeLength += MinorStr.size() + 1 /*'p'*/;
372
373 // Expected multi-character extension with version number to have no
374 // subsequent characters (i.e. must either end string or be followed by
375 // an underscore).
376 if (Ext.size() > 1 && In.size())
377 return getError(
378 "multi-character extensions must be separated by underscores");
379
380 // If experimental extension, require use of current version number
381 if (auto ExperimentalExtension = isExperimentalExtension(Ext)) {
382 if (!EnableExperimentalExtension)
383 return getError("requires '-menable-experimental-extensions' "
384 "for experimental extension '" +
385 Ext + "'");
386
387 if (ExperimentalExtensionVersionCheck &&
388 (MajorStr.empty() && MinorStr.empty()))
389 return getError(
390 "experimental extension requires explicit version number `" + Ext +
391 "`");
392
393 auto SupportedVers = *ExperimentalExtension;
394 if (ExperimentalExtensionVersionCheck &&
395 (Major != SupportedVers.Major || Minor != SupportedVers.Minor)) {
396 std::string Error = "unsupported version number " + MajorStr.str();
397 if (!MinorStr.empty())
398 Error += "." + MinorStr.str();
399 Error += " for experimental extension '" + Ext.str() +
400 "' (this compiler supports " + utostr(SupportedVers.Major) +
401 "." + utostr(SupportedVers.Minor) + ")";
402 return getError(Error);
403 }
404 return Error::success();
405 }
406
407 // Exception rule for `g`, we don't have clear version scheme for that on
408 // ISA spec.
409 if (Ext == "g")
410 return Error::success();
411
412 if (MajorStr.empty() && MinorStr.empty()) {
413 if (auto DefaultVersion = findDefaultVersion(Ext)) {
414 Major = DefaultVersion->Major;
415 Minor = DefaultVersion->Minor;
416 }
417 // No matter found or not, return success, assume other place will
418 // verify.
419 return Error::success();
420 }
421
422 if (RISCVISAInfo::isSupportedExtension(Ext, Major, Minor))
423 return Error::success();
424
426 return getErrorForInvalidExt(Ext);
427
428 std::string Error = "unsupported version number " + MajorStr.str();
429 if (!MinorStr.empty())
430 Error += "." + MinorStr.str();
431 Error += " for extension '" + Ext.str() + "'";
432 return getError(Error);
433}
434
438 assert(XLen == 32 || XLen == 64);
439 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
440
441 ISAInfo->Exts = Exts;
442
443 return RISCVISAInfo::postProcessAndChecking(std::move(ISAInfo));
444}
445
448 const std::vector<std::string> &Features) {
449 assert(XLen == 32 || XLen == 64);
450 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
451
452 for (StringRef ExtName : Features) {
453 assert(ExtName.size() > 1 && (ExtName[0] == '+' || ExtName[0] == '-'));
454 bool Add = ExtName[0] == '+';
455 ExtName = ExtName.drop_front(1); // Drop '+' or '-'
456 bool Experimental = stripExperimentalPrefix(ExtName);
457 auto ExtensionInfos = Experimental
458 ? ArrayRef(SupportedExperimentalExtensions)
459 : ArrayRef(SupportedExtensions);
460 auto ExtensionInfoIterator =
461 llvm::lower_bound(ExtensionInfos, ExtName, LessExtName());
462
463 // Not all features is related to ISA extension, like `relax` or
464 // `save-restore`, skip those feature.
465 if (ExtensionInfoIterator == ExtensionInfos.end() ||
466 ExtensionInfoIterator->Name != ExtName)
467 continue;
468
469 if (Add)
470 ISAInfo->Exts[ExtName.str()] = ExtensionInfoIterator->Version;
471 else
472 ISAInfo->Exts.erase(ExtName.str());
473 }
474
475 return RISCVISAInfo::postProcessAndChecking(std::move(ISAInfo));
476}
477
480 // RISC-V ISA strings must be [a-z0-9_]
481 if (!llvm::all_of(
482 Arch, [](char C) { return isDigit(C) || isLower(C) || C == '_'; }))
483 return getError("string may only contain [a-z0-9_]");
484
485 // Must start with a valid base ISA name.
486 unsigned XLen = 0;
487 if (Arch.consume_front("rv32"))
488 XLen = 32;
489 else if (Arch.consume_front("rv64"))
490 XLen = 64;
491
492 if (XLen == 0 || Arch.empty() || (Arch[0] != 'i' && Arch[0] != 'e'))
493 return getError("arch string must begin with valid base ISA");
494
495 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
496
497 // Each extension is of the form ${name}${major_version}p${minor_version}
498 // and separated by _. Split by _ and then extract the name and version
499 // information for each extension.
500 while (!Arch.empty()) {
501 if (Arch[0] == '_') {
502 if (Arch.size() == 1 || Arch[1] == '_')
503 return getError("extension name missing after separator '_'");
504 Arch = Arch.drop_front();
505 }
506
507 size_t Idx = Arch.find('_');
508 StringRef Ext = Arch.slice(0, Idx);
509 Arch = Arch.substr(Idx);
510
511 StringRef Prefix, MinorVersionStr;
512 std::tie(Prefix, MinorVersionStr) = Ext.rsplit('p');
513 if (MinorVersionStr.empty())
514 return getError("extension lacks version in expected format");
515 unsigned MajorVersion, MinorVersion;
516 if (MinorVersionStr.getAsInteger(10, MinorVersion))
517 return getError("failed to parse minor version number");
518
519 // Split Prefix into the extension name and the major version number
520 // (the trailing digits of Prefix).
521 size_t VersionStart = Prefix.size();
522 while (VersionStart != 0) {
523 if (!isDigit(Prefix[VersionStart - 1]))
524 break;
525 --VersionStart;
526 }
527 if (VersionStart == Prefix.size())
528 return getError("extension lacks version in expected format");
529
530 if (VersionStart == 0)
531 return getError("missing extension name");
532
533 StringRef ExtName = Prefix.slice(0, VersionStart);
534 StringRef MajorVersionStr = Prefix.substr(VersionStart);
535 if (MajorVersionStr.getAsInteger(10, MajorVersion))
536 return getError("failed to parse major version number");
537
538 if ((ExtName[0] == 'z' || ExtName[0] == 's' || ExtName[0] == 'x') &&
539 (ExtName.size() == 1 || isDigit(ExtName[1])))
540 return getError("'" + Twine(ExtName[0]) +
541 "' must be followed by a letter");
542
543 if (!ISAInfo->Exts
544 .emplace(
545 ExtName.str(),
546 RISCVISAUtils::ExtensionVersion{MajorVersion, MinorVersion})
547 .second)
548 return getError("duplicate extension '" + ExtName + "'");
549 }
550 ISAInfo->updateImpliedLengths();
551 return std::move(ISAInfo);
552}
553
555RISCVISAInfo::parseArchString(StringRef Arch, bool EnableExperimentalExtension,
556 bool ExperimentalExtensionVersionCheck) {
557 // RISC-V ISA strings must be [a-z0-9_]
558 if (!llvm::all_of(
559 Arch, [](char C) { return isDigit(C) || isLower(C) || C == '_'; }))
560 return getError("string may only contain [a-z0-9_]");
561
562 // ISA string must begin with rv32, rv64, or a profile.
563 unsigned XLen = 0;
564 if (Arch.consume_front("rv32")) {
565 XLen = 32;
566 } else if (Arch.consume_front("rv64")) {
567 XLen = 64;
568 } else {
569 // Try parsing as a profile.
570 auto ProfileCmp = [](StringRef Arch, const RISCVProfile &Profile) {
571 return Arch < Profile.Name;
572 };
573 auto I = llvm::upper_bound(SupportedProfiles, Arch, ProfileCmp);
574 bool FoundProfile = I != std::begin(SupportedProfiles) &&
575 Arch.starts_with(std::prev(I)->Name);
576 if (!FoundProfile) {
577 I = llvm::upper_bound(SupportedExperimentalProfiles, Arch, ProfileCmp);
578 FoundProfile = (I != std::begin(SupportedExperimentalProfiles) &&
579 Arch.starts_with(std::prev(I)->Name));
580 if (FoundProfile && !EnableExperimentalExtension) {
581 return getError("requires '-menable-experimental-extensions' "
582 "for profile '" +
583 std::prev(I)->Name + "'");
584 }
585 }
586 if (FoundProfile) {
587 --I;
588 std::string NewArch = I->MArch.str();
589 StringRef ArchWithoutProfile = Arch.drop_front(I->Name.size());
590 if (!ArchWithoutProfile.empty()) {
591 if (ArchWithoutProfile.front() != '_')
592 return getError("additional extensions must be after separator '_'");
593 NewArch += ArchWithoutProfile.str();
594 }
595 return parseArchString(NewArch, EnableExperimentalExtension,
596 ExperimentalExtensionVersionCheck);
597 }
598 }
599
600 if (XLen == 0 || Arch.empty())
601 return getError(
602 "string must begin with rv32{i,e,g}, rv64{i,e,g}, or a supported "
603 "profile name");
604
605 std::unique_ptr<RISCVISAInfo> ISAInfo(new RISCVISAInfo(XLen));
606
607 // The canonical order specified in ISA manual.
608 // Ref: Table 22.1 in RISC-V User-Level ISA V2.2
609 char Baseline = Arch.front();
610 // Skip the baseline.
611 Arch = Arch.drop_front();
612
613 unsigned Major, Minor, ConsumeLength;
614
615 // First letter should be 'e', 'i' or 'g'.
616 switch (Baseline) {
617 default:
618 return getError("first letter after \'rv" + Twine(XLen) +
619 "\' should be 'e', 'i' or 'g'");
620 case 'e':
621 case 'i':
622 // Baseline is `i` or `e`
623 if (auto E = getExtensionVersion(
624 StringRef(&Baseline, 1), Arch, Major, Minor, ConsumeLength,
625 EnableExperimentalExtension, ExperimentalExtensionVersionCheck))
626 return std::move(E);
627
628 ISAInfo->Exts[std::string(1, Baseline)] = {Major, Minor};
629 break;
630 case 'g':
631 // g expands to extensions in RISCVGImplications.
632 if (!Arch.empty() && isDigit(Arch.front()))
633 return getError("version not supported for 'g'");
634
635 // Versions for g are disallowed, and this was checked for previously.
636 ConsumeLength = 0;
637
638 // No matter which version is given to `g`, we always set imafd to default
639 // version since the we don't have clear version scheme for that on
640 // ISA spec.
641 for (const char *Ext : RISCVGImplications) {
642 auto Version = findDefaultVersion(Ext);
643 assert(Version && "Default extension version not found?");
644 ISAInfo->Exts[std::string(Ext)] = {Version->Major, Version->Minor};
645 }
646 break;
647 }
648
649 // Consume the base ISA version number and any '_' between rvxxx and the
650 // first extension
651 Arch = Arch.drop_front(ConsumeLength);
652
653 while (!Arch.empty()) {
654 if (Arch.front() == '_') {
655 if (Arch.size() == 1 || Arch[1] == '_')
656 return getError("extension name missing after separator '_'");
657 Arch = Arch.drop_front();
658 }
659
660 size_t Idx = Arch.find('_');
661 StringRef Ext = Arch.slice(0, Idx);
662 Arch = Arch.substr(Idx);
663
664 do {
665 StringRef Name, Vers, Desc;
666 if (RISCVISAUtils::AllStdExts.contains(Ext.front())) {
667 Name = Ext.take_front(1);
668 Ext = Ext.drop_front();
669 Vers = Ext;
670 Desc = "standard user-level extension";
671 } else if (Ext.front() == 'z' || Ext.front() == 's' ||
672 Ext.front() == 'x') {
673 // Handle other types of extensions other than the standard
674 // general purpose and standard user-level extensions.
675 // Parse the ISA string containing non-standard user-level
676 // extensions, standard supervisor-level extensions and
677 // non-standard supervisor-level extensions.
678 // These extensions start with 'z', 's', 'x' prefixes, might have a
679 // version number (major, minor) and are separated by a single
680 // underscore '_'. We do not enforce a canonical order for them.
683 auto Pos = findLastNonVersionCharacter(Ext) + 1;
684 Name = Ext.substr(0, Pos);
685 Vers = Ext.substr(Pos);
686 Ext = StringRef();
687
688 assert(!Type.empty() && "Empty type?");
689 if (Name.size() == Type.size())
690 return getError(Desc + " name missing after '" + Type + "'");
691 } else {
692 return getError("invalid standard user-level extension '" +
693 Twine(Ext.front()) + "'");
694 }
695
696 unsigned Major, Minor, ConsumeLength;
697 if (auto E = getExtensionVersion(Name, Vers, Major, Minor, ConsumeLength,
698 EnableExperimentalExtension,
699 ExperimentalExtensionVersionCheck))
700 return E;
701
702 if (Name.size() == 1)
703 Ext = Ext.substr(ConsumeLength);
704
707
708 // Insert and error for duplicates.
709 if (!ISAInfo->Exts
710 .emplace(Name.str(),
712 .second)
713 return getError("duplicated " + Desc + " '" + Name + "'");
714
715 } while (!Ext.empty());
716 }
717
718 // We add Zicsr/Zifenci as final to allow duplicated "zicsr"/"zifencei" like
719 // "rv64g_zicsr_zifencei".
720 if (Baseline == 'g') {
721 for (const char *Ext : RISCVGImplicationsZi) {
722 if (ISAInfo->Exts.count(Ext))
723 continue;
724
725 auto Version = findDefaultVersion(Ext);
726 assert(Version && "Default extension version not found?");
727 ISAInfo->Exts[std::string(Ext)] = {Version->Major, Version->Minor};
728 }
729 }
730
731 return RISCVISAInfo::postProcessAndChecking(std::move(ISAInfo));
732}
733
735 return getError("'" + Ext1 + "' and '" + Ext2 +
736 "' extensions are incompatible");
737}
738
740 return getError("'" + Ext + "' requires '" + ReqExt +
741 "' extension to also be specified");
742}
743
744Error RISCVISAInfo::checkDependency() {
745 bool HasE = Exts.count("e") != 0;
746 bool HasI = Exts.count("i") != 0;
747 bool HasC = Exts.count("c") != 0;
748 bool HasF = Exts.count("f") != 0;
749 bool HasD = Exts.count("d") != 0;
750 bool HasZfinx = Exts.count("zfinx") != 0;
751 bool HasVector = Exts.count("zve32x") != 0;
752 bool HasZvl = MinVLen != 0;
753 bool HasZcmp = Exts.count("zcmp") != 0;
754 bool HasXqccmp = Exts.count("xqccmp") != 0;
755
756 static constexpr StringLiteral XqciExts[] = {
757 {"xqcia"}, {"xqciac"}, {"xqcibi"}, {"xqcibm"}, {"xqcicli"},
758 {"xqcicm"}, {"xqcics"}, {"xqcicsr"}, {"xqciint"}, {"xqciio"},
759 {"xqcilb"}, {"xqcili"}, {"xqcilia"}, {"xqcilo"}, {"xqcilsm"},
760 {"xqcisim"}, {"xqcisls"}, {"xqcisync"}};
761 static constexpr StringLiteral ZcdOverlaps[] = {
762 {"zcmt"}, {"zcmp"}, {"xqccmp"}, {"xqciac"}, {"xqcicm"}};
763
764 if (HasI && HasE)
765 return getIncompatibleError("i", "e");
766
767 if (HasF && HasZfinx)
768 return getIncompatibleError("f", "zfinx");
769
770 if (HasZvl && !HasVector)
771 return getExtensionRequiresError("zvl*b", "v' or 'zve*");
772
773 if (HasD && (HasC || Exts.count("zcd")))
774 for (auto Ext : ZcdOverlaps)
775 if (Exts.count(Ext.str()))
776 return getError(
777 Twine("'") + Ext + "' extension is incompatible with '" +
778 (HasC ? "c" : "zcd") + "' extension when 'd' extension is enabled");
779
780 if (XLen != 32 && Exts.count("zcf"))
781 return getError("'zcf' is only supported for 'rv32'");
782
783 if (Exts.count("xwchc") != 0) {
784 if (XLen != 32)
785 return getError("'xwchc' is only supported for 'rv32'");
786
787 if (HasD)
788 return getIncompatibleError("d", "xwchc");
789
790 if (Exts.count("zcb") != 0)
791 return getIncompatibleError("xwchc", "zcb");
792 }
793
794 if (Exts.count("zclsd") != 0) {
795 if (XLen != 32)
796 return getError("'zclsd' is only supported for 'rv32'");
797
798 if (Exts.count("zcf") != 0)
799 return getIncompatibleError("zclsd", "zcf");
800 }
801
802 if (XLen != 32 && Exts.count("zilsd") != 0)
803 return getError("'zilsd' is only supported for 'rv32'");
804
805 for (auto Ext : XqciExts)
806 if (Exts.count(Ext.str()) && (XLen != 32))
807 return getError("'" + Twine(Ext) + "'" + " is only supported for 'rv32'");
808
809 if (HasZcmp && HasXqccmp)
810 return getIncompatibleError("zcmp", "xqccmp");
811
812 return Error::success();
813}
814
817 const char *ImpliedExt;
818
819 bool operator<(const ImpliedExtsEntry &Other) const {
820 return Name < Other.Name;
821 }
822};
823
824static bool operator<(const ImpliedExtsEntry &LHS, StringRef RHS) {
825 return LHS.Name < RHS;
826}
827
828static bool operator<(StringRef LHS, const ImpliedExtsEntry &RHS) {
829 return LHS < RHS.Name;
830}
831
832#define GET_IMPLIED_EXTENSIONS
833#include "llvm/TargetParser/RISCVTargetParserDef.inc"
834
835void RISCVISAInfo::updateImplication() {
836 assert(llvm::is_sorted(ImpliedExts) && "Table not sorted by Name");
837
838 // This loop may execute over 1 iteration since implication can be layered
839 // Exits loop if no more implication is applied
841 for (auto const &Ext : Exts)
842 WorkList.push_back(Ext.first);
843
844 while (!WorkList.empty()) {
845 StringRef ExtName = WorkList.pop_back_val();
846 auto Range = std::equal_range(std::begin(ImpliedExts),
847 std::end(ImpliedExts), ExtName);
848 for (const ImpliedExtsEntry &Implied : llvm::make_range(Range)) {
849 const char *ImpliedExt = Implied.ImpliedExt;
850 auto [It, Inserted] = Exts.try_emplace(ImpliedExt);
851 if (!Inserted)
852 continue;
853 auto Version = findDefaultVersion(ImpliedExt);
854 It->second = *Version;
855 WorkList.push_back(ImpliedExt);
856 }
857 }
858
859 // Add Zcd if C and D are enabled.
860 if (Exts.count("c") && Exts.count("d") && !Exts.count("zcd")) {
861 auto Version = findDefaultVersion("zcd");
862 Exts["zcd"] = *Version;
863 }
864
865 // Add Zcf if C and F are enabled on RV32.
866 if (XLen == 32 && Exts.count("c") && Exts.count("f") && !Exts.count("zcf")) {
867 auto Version = findDefaultVersion("zcf");
868 Exts["zcf"] = *Version;
869 }
870
871 // Add Zcf if Zce and F are enabled on RV32.
872 if (XLen == 32 && Exts.count("zce") && Exts.count("f") &&
873 !Exts.count("zcf")) {
874 auto Version = findDefaultVersion("zcf");
875 Exts["zcf"] = *Version;
876 }
877
878 // Handle I/E after implications have been resolved, in case either
879 // of them was implied by another extension.
880 bool HasE = Exts.count("e") != 0;
881 bool HasI = Exts.count("i") != 0;
882
883 // If not in e extension and i extension does not exist, i extension is
884 // implied
885 if (!HasE && !HasI) {
886 auto Version = findDefaultVersion("i");
887 Exts["i"] = *Version;
888 }
889
890 if (HasE && HasI)
891 Exts.erase("i");
892}
893
894static constexpr StringLiteral CombineIntoExts[] = {
895 {"b"}, {"zk"}, {"zkn"}, {"zks"}, {"zvkn"},
896 {"zvknc"}, {"zvkng"}, {"zvks"}, {"zvksc"}, {"zvksg"},
897};
898
899void RISCVISAInfo::updateCombination() {
900 bool MadeChange = false;
901 do {
902 MadeChange = false;
903 for (StringRef CombineExt : CombineIntoExts) {
904 if (Exts.count(CombineExt.str()))
905 continue;
906
907 // Look up the extension in the ImpliesExt table to find everything it
908 // depends on.
909 auto Range = std::equal_range(std::begin(ImpliedExts),
910 std::end(ImpliedExts), CombineExt);
911 bool HasAllRequiredFeatures = std::all_of(
912 Range.first, Range.second, [&](const ImpliedExtsEntry &Implied) {
913 return Exts.count(Implied.ImpliedExt);
914 });
915 if (HasAllRequiredFeatures) {
916 auto Version = findDefaultVersion(CombineExt);
917 Exts[CombineExt.str()] = *Version;
918 MadeChange = true;
919 }
920 }
921 } while (MadeChange);
922}
923
924void RISCVISAInfo::updateImpliedLengths() {
925 assert(FLen == 0 && MaxELenFp == 0 && MaxELen == 0 && MinVLen == 0 &&
926 "Expected lengths to be initialied to zero");
927
928 if (Exts.count("q"))
929 FLen = 128;
930 else if (Exts.count("d"))
931 FLen = 64;
932 else if (Exts.count("f"))
933 FLen = 32;
934
935 if (Exts.count("v")) {
936 MaxELenFp = std::max(MaxELenFp, 64u);
937 MaxELen = std::max(MaxELen, 64u);
938 }
939
940 for (auto const &Ext : Exts) {
941 StringRef ExtName = Ext.first;
942 // Infer MaxELen and MaxELenFp from Zve(32/64)(x/f/d)
943 if (ExtName.consume_front("zve")) {
944 unsigned ZveELen;
945 if (ExtName.consumeInteger(10, ZveELen))
946 continue;
947
948 if (ExtName == "f")
949 MaxELenFp = std::max(MaxELenFp, 32u);
950 else if (ExtName == "d")
951 MaxELenFp = std::max(MaxELenFp, 64u);
952 else if (ExtName != "x")
953 continue;
954
955 MaxELen = std::max(MaxELen, ZveELen);
956 continue;
957 }
958
959 // Infer MinVLen from zvl*b.
960 if (ExtName.consume_front("zvl")) {
961 unsigned ZvlLen;
962 if (ExtName.consumeInteger(10, ZvlLen))
963 continue;
964
965 if (ExtName != "b")
966 continue;
967
968 MinVLen = std::max(MinVLen, ZvlLen);
969 continue;
970 }
971 }
972}
973
974std::string RISCVISAInfo::toString() const {
975 std::string Buffer;
976 raw_string_ostream Arch(Buffer);
977
978 Arch << "rv" << XLen;
979
980 ListSeparator LS("_");
981 for (auto const &Ext : Exts) {
982 StringRef ExtName = Ext.first;
983 auto ExtInfo = Ext.second;
984 Arch << LS << ExtName;
985 Arch << ExtInfo.Major << "p" << ExtInfo.Minor;
986 }
987
988 return Arch.str();
989}
990
992RISCVISAInfo::postProcessAndChecking(std::unique_ptr<RISCVISAInfo> &&ISAInfo) {
993 ISAInfo->updateImplication();
994 ISAInfo->updateCombination();
995 ISAInfo->updateImpliedLengths();
996
997 if (Error Result = ISAInfo->checkDependency())
998 return std::move(Result);
999 return std::move(ISAInfo);
1000}
1001
1003 if (XLen == 32) {
1004 if (Exts.count("e"))
1005 return "ilp32e";
1006 if (Exts.count("d"))
1007 return "ilp32d";
1008 if (Exts.count("f"))
1009 return "ilp32f";
1010 return "ilp32";
1011 } else if (XLen == 64) {
1012 if (Exts.count("e"))
1013 return "lp64e";
1014 if (Exts.count("d"))
1015 return "lp64d";
1016 if (Exts.count("f"))
1017 return "lp64f";
1018 return "lp64";
1019 }
1020 llvm_unreachable("Invalid XLEN");
1021}
1022
1024 if (Ext.empty())
1025 return false;
1026
1027 auto Pos = findLastNonVersionCharacter(Ext) + 1;
1028 StringRef Name = Ext.substr(0, Pos);
1029 StringRef Vers = Ext.substr(Pos);
1030 if (Vers.empty())
1031 return false;
1032
1033 unsigned Major, Minor, ConsumeLength;
1034 if (auto E = getExtensionVersion(Name, Vers, Major, Minor, ConsumeLength,
1035 true, true)) {
1036 consumeError(std::move(E));
1037 return false;
1038 }
1039
1040 return true;
1041}
1042
1044 if (Ext.empty())
1045 return std::string();
1046
1047 auto Pos = findLastNonVersionCharacter(Ext) + 1;
1048 StringRef Name = Ext.substr(0, Pos);
1049
1050 if (Pos != Ext.size() && !isSupportedExtensionWithVersion(Ext))
1051 return std::string();
1052
1054 return std::string();
1055
1056 return isExperimentalExtension(Name) ? "experimental-" + Name.str()
1057 : Name.str();
1058}
1059
1064};
1065
1067 const char *Name;
1068 unsigned GroupID;
1069 unsigned BitPosition;
1070};
1071
1072#define GET_RISCVExtensionBitmaskTable_IMPL
1073#include "llvm/TargetParser/RISCVTargetParserDef.inc"
1074
1076 // Note that this code currently accepts mixed case extension names, but
1077 // does not handle extension versions at all. That's probably fine because
1078 // there's only one extension version in the __riscv_feature_bits vector.
1079 for (auto E : ExtensionBitmask)
1080 if (Ext.equals_insensitive(E.Name))
1081 return std::make_pair(E.GroupID, E.BitPosition);
1082 return std::make_pair(-1, -1);
1083}
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
Returns the sub type a function will return at a given Idx Should correspond to the result type of an ExtractValue instruction executed with just that one unsigned Idx
std::string Name
std::optional< std::vector< StOtherPiece > > Other
Definition: ELFYAML.cpp:1328
#define _
#define I(x, y, z)
Definition: MD5.cpp:58
Load MIR Sample Profile
ConstantRange Range(APInt(BitWidth, Low), APInt(BitWidth, High))
#define P(N)
static void verifyTables()
static StringRef getExtensionTypeDesc(StringRef Ext)
static const char * RISCVGImplicationsZi[]
static std::optional< RISCVISAUtils::ExtensionVersion > findDefaultVersion(StringRef ExtName)
static size_t findLastNonVersionCharacter(StringRef Ext)
static Error getExtensionRequiresError(StringRef Ext, StringRef ReqExt)
static StringRef getExtensionType(StringRef Ext)
static Error getErrorForInvalidExt(StringRef ExtName)
static constexpr StringLiteral CombineIntoExts[]
static bool stripExperimentalPrefix(StringRef &Ext)
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 Error getIncompatibleError(StringRef Ext1, StringRef Ext2)
static Error getError(const Twine &Message)
static const char * RISCVGImplications[]
static bool isDigit(const char C)
static bool isLower(const char C)
This file contains some templates that are useful if you are working with the STL at all.
static bool contains(SmallPtrSetImpl< ConstantExpr * > &Cache, ConstantExpr *Expr, Constant *C)
Definition: Value.cpp:480
This file contains some functions that are useful when dealing with strings.
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:136
Lightweight error class with error context and mandatory checking.
Definition: Error.h:159
static ErrorSuccess success()
Create a success value.
Definition: Error.h:336
Tagged union holding either a T or a Error.
Definition: Error.h:485
static LLVM_ABI bool isSupportedExtensionFeature(StringRef Ext)
static LLVM_ABI std::string getTargetFeatureForExtension(StringRef Ext)
static LLVM_ABI 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...
LLVM_ABI bool hasExtension(StringRef Ext) const
LLVM_ABI std::string toString() const
LLVM_ABI StringRef computeDefaultABI() const
static LLVM_ABI llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseArchString(StringRef Arch, bool EnableExperimentalExtension, bool ExperimentalExtensionVersionCheck=true)
Parse RISC-V ISA info from arch string.
static LLVM_ABI bool isSupportedExtension(StringRef Ext)
static LLVM_ABI void printEnabledExtensions(bool IsRV64, std::set< StringRef > &EnabledFeatureNames, StringMap< StringRef > &DescMap)
static LLVM_ABI void printSupportedExtensions(StringMap< StringRef > &DescMap)
static LLVM_ABI llvm::Expected< std::unique_ptr< RISCVISAInfo > > parseFeatures(unsigned XLen, const std::vector< std::string > &Features)
Parse RISC-V ISA info from feature vector.
static LLVM_ABI std::pair< int, int > getRISCVFeaturesBitsInfo(StringRef Ext)
Return the group id and bit position of __riscv_feature_bits.
static LLVM_ABI llvm::Expected< std::unique_ptr< RISCVISAInfo > > createFromExtMap(unsigned XLen, const RISCVISAUtils::OrderedExtensionMap &Exts)
LLVM_ABI std::vector< std::string > toFeatures(bool AddAllExtensions=false, bool IgnoreUnknown=true) const
Convert RISC-V ISA info to a feature vector.
static LLVM_ABI bool isSupportedExtensionWithVersion(StringRef Ext)
bool empty() const
Definition: SmallVector.h:82
void push_back(const T &Elt)
Definition: SmallVector.h:414
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Definition: SmallVector.h:1197
A wrapper around a string literal that serves as a proxy for constructing global tables of StringRefs...
Definition: StringRef.h:862
bool empty() const
Definition: StringMap.h:108
StringMap - This is an unconventional map that is specialized for handling keys that are "strings",...
Definition: StringMap.h:133
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:55
bool consumeInteger(unsigned Radix, T &Result)
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:509
bool getAsInteger(unsigned Radix, T &Result) const
Parse the current string as an integer of the specified radix.
Definition: StringRef.h:480
std::string str() const
str - Get the contents as an std::string.
Definition: StringRef.h:233
constexpr StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:581
bool starts_with(StringRef Prefix) const
Check if this string starts with the given Prefix.
Definition: StringRef.h:269
constexpr bool empty() const
empty - Check if the string is empty.
Definition: StringRef.h:151
StringRef drop_front(size_t N=1) const
Return a StringRef equal to 'this' but with the first N elements dropped.
Definition: StringRef.h:619
StringRef slice(size_t Start, size_t End) const
Return a reference to the substring from [Start, End).
Definition: StringRef.h:694
constexpr size_t size() const
size - Get the string size.
Definition: StringRef.h:154
char front() const
front - Get the first character in the string.
Definition: StringRef.h:157
bool consume_front(StringRef Prefix)
Returns true if this StringRef has the given prefix and removes that prefix.
Definition: StringRef.h:645
size_t find(char C, size_t From=0) const
Search for the first character C in the string.
Definition: StringRef.h:301
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:82
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:662
std::string & str()
Returns the string's reference.
Definition: raw_ostream.h:680
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
@ C
The default llvm calling convention, compatible with C.
Definition: CallingConv.h:34
constexpr StringLiteral AllStdExts
Definition: RISCVISAUtils.h:24
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:44
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:362
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly.
Definition: STLExtras.h:1744
LLVM_ABI raw_fd_ostream & outs()
This returns a reference to a raw_fd_ostream for standard output.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
auto upper_bound(R &&Range, T &&Value)
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:2026
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1305
Op::Description Desc
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:1939
FormattedString left_justify(StringRef Str, unsigned Width)
left_justify - append spaces after string so total output is Width characters.
Definition: Format.h:147
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:2013
@ Add
Sum of integers.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:1083
StringLiteral Name
bool operator<(const ImpliedExtsEntry &Other) const
const char * ImpliedExt
const StringLiteral ext
Description of the encoding of one expression Op.
Represents the major and version number components of a RISC-V extension.
Definition: RISCVISAUtils.h:27