1//===- DirectiveEmitter.cpp - Directive Language Emitter ------------------===//
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// DirectiveEmitter uses the descriptions of directives and clauses to construct
10// common code declarations to be used in Frontends.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/TableGen/DirectiveEmitter.h"
15
16#include "llvm/ADT/DenseMap.h"
17#include "llvm/ADT/DenseSet.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallVector.h"
20#include "llvm/ADT/StringSet.h"
21#include "llvm/ADT/StringSwitch.h"
22#include "llvm/TableGen/CodeGenHelpers.h"
23#include "llvm/TableGen/Error.h"
24#include "llvm/TableGen/Record.h"
25#include "llvm/TableGen/TableGenBackend.h"
26
27#include <numeric>
28#include <string>
29#include <vector>
30
31using namespace llvm;
32
33namespace {
34enum class Frontend { LLVM, Flang, Clang };
35} // namespace
36
37static void emitDirectivesConstexprImpl(const DirectiveLanguage &DirLang,
38 raw_ostream &OS);
39
40static StringRef getVersionType(const DirectiveLanguage &DirLang,
41 bool FullQual = false) {
42 return FullQual ? "llvm::directive::Version" : "directive::Version";
43}
44
45static StringRef getFESpelling(Frontend FE) {
46 switch (FE) {
47 case Frontend::LLVM:
48 return "llvm";
49 case Frontend::Flang:
50 return "flang";
51 case Frontend::Clang:
52 return "clang";
53 }
54 llvm_unreachable("unknown FE kind");
55}
56
57// Get the full namespace qualifier for the directive language.
58static std::string getQualifier(const DirectiveLanguage &DirLang,
59 Frontend FE = Frontend::LLVM) {
60 return (Twine(getFESpelling(FE)) + "::" + DirLang.getCppNamespace().str() +
61 "::")
62 .str();
63}
64
65// Get prefixed formatted name, e.g. for "target data", get "OMPD_target_data".
66// This should work for any Record as long as BaseRecord::getFormattedName
67// works.
68static std::string getIdentifierName(const Record *Rec, StringRef Prefix) {
69 return Prefix.str() + BaseRecord(Rec).getFormattedName();
70}
71
72using RecordWithSpelling = std::pair<const Record *, Spelling::Value>;
73
74static std::vector<RecordWithSpelling>
75getSpellings(ArrayRef<const Record *> Records) {
76 std::vector<RecordWithSpelling> List;
77 for (const Record *R : Records) {
78 BaseRecord Rec(R);
79 llvm::transform(Range: Rec.getSpellings(), d_first: std::back_inserter(x&: List),
80 F: [R](Spelling::Value V) { return std::make_pair(x: R, y&: V); });
81 }
82 return List;
83}
84
85static void generateEnumExports(ArrayRef<const Record *> Records,
86 raw_ostream &OS, StringRef Enum,
87 StringRef Prefix) {
88 for (const Record *R : Records) {
89 std::string N = getIdentifierName(Rec: R, Prefix);
90 OS << "constexpr auto " << N << " = " << Enum << "::" << N << ";\n";
91 }
92 OS << "\n";
93}
94
95// Generate enum class. Entries are emitted in the order in which they appear
96// in the `Records` vector.
97static void generateEnumClass(ArrayRef<const Record *> Records, raw_ostream &OS,
98 StringRef Enum, StringRef Prefix,
99 bool ExportEnums) {
100 OS << "enum class " << Enum << " {\n";
101 if (!Records.empty()) {
102 std::string N;
103 for (auto [I, R] : llvm::enumerate(First&: Records)) {
104 N = getIdentifierName(Rec: R, Prefix);
105 OS << " " << N << ",\n";
106 // Make the sentinel names less likely to conflict with actual names...
107 if (I == 0)
108 OS << " First_ = " << N << ",\n";
109 }
110 OS << " Last_ = " << N << ",\n";
111 }
112 OS << "};\n";
113 OS << "\n";
114 OS << "static constexpr std::size_t " << Enum
115 << "_enumSize = " << Records.size() << ";\n\n";
116
117 // Make the enum values available in the defined namespace. This allows us to
118 // write something like Enum_X if we have a `using namespace <CppNamespace>`.
119 // At the same time we do not loose the strong type guarantees of the enum
120 // class, that is we cannot pass an unsigned as Directive without an explicit
121 // cast.
122 if (ExportEnums)
123 generateEnumExports(Records, OS, Enum, Prefix);
124}
125
126// Generate enum class with values corresponding to different bit positions.
127// Entries are emitted in the order in which they appear in the `Records`
128// vector.
129static void generateEnumBitmask(ArrayRef<const Record *> Records,
130 raw_ostream &OS, StringRef Enum,
131 StringRef Prefix, bool ExportEnums) {
132 assert(Records.size() <= 64 && "Too many values for a bitmask");
133 StringRef Type = Records.size() <= 32 ? "uint32_t" : "uint64_t";
134 StringRef TypeSuffix = Records.size() <= 32 ? "U" : "ULL";
135
136 OS << "enum class " << Enum << " : " << Type << " {\n";
137 std::string LastName;
138 for (auto [I, R] : llvm::enumerate(First&: Records)) {
139 LastName = getIdentifierName(Rec: R, Prefix);
140 OS << " " << LastName << " = " << (1ull << I) << TypeSuffix << ",\n";
141 }
142 OS << " LLVM_MARK_AS_BITMASK_ENUM(/*LargestValue=*/" << LastName << ")\n";
143 OS << "};\n";
144 OS << "\n";
145 OS << "static constexpr std::size_t " << Enum
146 << "_enumSize = " << Records.size() << ";\n\n";
147
148 // Make the enum values available in the defined namespace. This allows us to
149 // write something like Enum_X if we have a `using namespace <CppNamespace>`.
150 // At the same time we do not loose the strong type guarantees of the enum
151 // class, that is we cannot pass an unsigned as Directive without an explicit
152 // cast.
153 if (ExportEnums)
154 generateEnumExports(Records, OS, Enum, Prefix);
155}
156
157// Generate enums for values that clauses can take.
158// Also generate function declarations for get<Enum>Name(StringRef Str).
159static void generateClauseEnumVal(ArrayRef<const Record *> Records,
160 raw_ostream &OS,
161 const DirectiveLanguage &DirLang,
162 std::string &EnumHelperFuncs) {
163 for (const Record *R : Records) {
164 Clause C(R);
165 const auto &ClauseVals = C.getClauseVals();
166 if (ClauseVals.size() <= 0)
167 continue;
168
169 StringRef Enum = C.getEnumName();
170 if (Enum.empty()) {
171 PrintError(Msg: "enumClauseValue field not set in Clause" +
172 C.getFormattedName() + ".");
173 return;
174 }
175
176 OS << "enum class " << Enum << " {\n";
177 for (const EnumVal Val : ClauseVals)
178 OS << " " << Val.getRecordName() << "=" << Val.getValue() << ",\n";
179 OS << "};\n";
180
181 if (DirLang.hasMakeEnumAvailableInNamespace()) {
182 OS << "\n";
183 for (const auto &CV : ClauseVals) {
184 OS << "constexpr auto " << CV->getName() << " = " << Enum
185 << "::" << CV->getName() << ";\n";
186 }
187 OS << "\n";
188 EnumHelperFuncs += (Twine("LLVM_ABI ") + Twine(Enum) + Twine(" get") +
189 Twine(Enum) + Twine("(StringRef Str);\n"))
190 .str();
191
192 EnumHelperFuncs +=
193 (Twine("LLVM_ABI StringRef get") + Twine(DirLang.getName()) +
194 Twine(Enum) + Twine("Name(") + Twine(Enum) + Twine(" x);\n"))
195 .str();
196 }
197 }
198}
199
200static bool hasDuplicateClauses(ArrayRef<const Record *> Clauses,
201 const Directive &Directive,
202 StringSet<> &CrtClauses) {
203 bool HasError = false;
204 for (const VersionedClause VerClause : Clauses) {
205 StringRef Name = VerClause.getClause().getRecordName();
206 const auto InsRes = CrtClauses.insert(key: Name);
207 if (!InsRes.second) {
208 PrintError(Msg: "Clause " + Name + " already defined on directive " +
209 Directive.getRecordName());
210 HasError = true;
211 }
212 }
213 return HasError;
214}
215
216// Check for duplicate clauses in lists. Clauses cannot appear twice in the
217// three allowed list. Also, since required implies allowed, clauses cannot
218// appear in both the allowedClauses and requiredClauses lists.
219static bool
220hasDuplicateClausesInDirectives(ArrayRef<const Record *> Directives) {
221 bool HasDuplicate = false;
222 for (const Directive Dir : Directives) {
223 StringSet<> Clauses;
224 // Check for duplicates in the three allowed lists.
225 if (hasDuplicateClauses(Clauses: Dir.getAllowedClauses(), Directive: Dir, CrtClauses&: Clauses) ||
226 hasDuplicateClauses(Clauses: Dir.getAllowedOnceClauses(), Directive: Dir, CrtClauses&: Clauses) ||
227 hasDuplicateClauses(Clauses: Dir.getAllowedExclusiveClauses(), Directive: Dir, CrtClauses&: Clauses)) {
228 HasDuplicate = true;
229 }
230 // Check for duplicate between allowedClauses and required
231 Clauses.clear();
232 if (hasDuplicateClauses(Clauses: Dir.getAllowedClauses(), Directive: Dir, CrtClauses&: Clauses) ||
233 hasDuplicateClauses(Clauses: Dir.getRequiredClauses(), Directive: Dir, CrtClauses&: Clauses)) {
234 HasDuplicate = true;
235 }
236 if (HasDuplicate)
237 PrintFatalError(Msg: "One or more clauses are defined multiple times on"
238 " directive " +
239 Dir.getRecordName());
240 }
241
242 return HasDuplicate;
243}
244
245// Check consitency of records. Return true if an error has been detected.
246// Return false if the records are valid.
247bool DirectiveLanguage::HasValidityErrors() const {
248 if (getDirectiveLanguages().size() != 1) {
249 PrintFatalError(Msg: "A single definition of DirectiveLanguage is needed.");
250 return true;
251 }
252
253 return hasDuplicateClausesInDirectives(Directives: getDirectives());
254}
255
256// Count the maximum number of leaf constituents per construct.
257static size_t getMaxLeafCount(const DirectiveLanguage &DirLang) {
258 size_t MaxCount = 0;
259 for (const Directive D : DirLang.getDirectives())
260 MaxCount = std::max(a: MaxCount, b: D.getLeafConstructs().size());
261 return MaxCount;
262}
263
264// Generate the declaration section for the enumeration in the directive
265// language.
266static void emitDirectivesDecl(const RecordKeeper &Records, raw_ostream &OS) {
267 const auto DirLang = DirectiveLanguage(Records);
268 if (DirLang.HasValidityErrors())
269 return;
270
271 StringRef Lang = DirLang.getName();
272 IncludeGuardEmitter IncGuard(OS, (Twine("LLVM_") + Lang + "_INC").str());
273
274 OS << "#include \"llvm/ADT/ArrayRef.h\"\n";
275
276 if (DirLang.hasEnableBitmaskEnumInNamespace())
277 OS << "#include \"llvm/ADT/BitmaskEnum.h\"\n";
278
279 OS << "#include \"llvm/ADT/Sequence.h\"\n";
280 OS << "#include \"llvm/ADT/STLExtras.h\"\n";
281 OS << "#include \"llvm/ADT/StringRef.h\"\n";
282 OS << "#include \"llvm/Frontend/Directive/Spelling.h\"\n";
283 OS << "#include \"llvm/Frontend/Directive/Version.h\"\n";
284 OS << "#include \"llvm/Support/Compiler.h\"\n";
285 OS << "#include <cstddef>\n"; // for size_t
286 OS << "#include <utility>\n"; // for std::pair
287 OS << "\n";
288 NamespaceEmitter LlvmNS(OS, "llvm");
289 {
290 NamespaceEmitter DirLangNS(OS, DirLang.getCppNamespace());
291
292 if (DirLang.hasEnableBitmaskEnumInNamespace())
293 OS << "LLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();\n\n";
294
295 // Emit Directive associations
296 std::vector<const Record *> Associations;
297 copy_if(
298 Range: DirLang.getAssociations(), Out: std::back_inserter(x&: Associations),
299 // Skip the "special" value
300 P: [](const Record *Def) { return Def->getName() != "AS_FromLeaves"; });
301 generateEnumClass(Records: Associations, OS, Enum: "Association",
302 /*Prefix=*/"", /*ExportEnums=*/false);
303
304 generateEnumClass(Records: DirLang.getCategories(), OS, Enum: "Category", /*Prefix=*/"",
305 /*ExportEnums=*/false);
306
307 generateEnumBitmask(Records: DirLang.getSourceLanguages(), OS, Enum: "SourceLanguage",
308 /*Prefix=*/"", /*ExportEnums=*/false);
309
310 // Emit Directive enumeration
311 generateEnumClass(Records: DirLang.getDirectives(), OS, Enum: "Directive",
312 Prefix: DirLang.getDirectivePrefix(),
313 ExportEnums: DirLang.hasMakeEnumAvailableInNamespace());
314
315 // Emit Clause enumeration
316 generateEnumClass(Records: DirLang.getClauses(), OS, Enum: "Clause",
317 Prefix: DirLang.getClausePrefix(),
318 ExportEnums: DirLang.hasMakeEnumAvailableInNamespace());
319
320 // Emit LoopModifier
321 generateEnumClass(Records: DirLang.getLoopModifiers(), OS, Enum: "LoopModifier",
322 Prefix: DirLang.getLoopModifierPrefix(),
323 ExportEnums: DirLang.hasMakeEnumAvailableInNamespace());
324
325 // Emit ClauseVals enumeration
326 std::string EnumHelperFuncs;
327 generateClauseEnumVal(Records: DirLang.getClauses(), OS, DirLang, EnumHelperFuncs);
328
329 // Emit constexpr functions.
330 emitDirectivesConstexprImpl(DirLang, OS);
331
332 // Generic function signatures
333 StringRef VersionType = getVersionType(DirLang);
334
335 OS << "\n";
336 OS << "// Enumeration helper functions\n";
337
338 OS << "LLVM_ABI std::pair<Directive, directive::VersionRange> get" << Lang
339 << "DirectiveKindAndVersions(StringRef Str);\n";
340
341 OS << "inline Directive get" << Lang << "DirectiveKind(StringRef Str) {\n";
342 OS << " return get" << Lang << "DirectiveKindAndVersions(Str).first;\n";
343 OS << "}\n";
344 OS << "\n";
345
346 OS << "LLVM_ABI StringRef get" << Lang << "DirectiveName(Directive D, "
347 << VersionType << " V = " << VersionType << "(0));\n";
348 OS << "\n";
349
350 OS << "LLVM_ABI std::pair<Clause, directive::VersionRange> get" << Lang
351 << "ClauseKindAndVersions(StringRef Str);\n";
352 OS << "\n";
353
354 OS << "inline Clause get" << Lang << "ClauseKind(StringRef Str) {\n";
355 OS << " return get" << Lang << "ClauseKindAndVersions(Str).first;\n";
356 OS << "}\n";
357 OS << "\n";
358
359 OS << "LLVM_ABI StringRef get" << Lang << "ClauseName(Clause C, "
360 << VersionType << " V = " << VersionType << "(0));\n";
361 OS << "\n";
362
363 OS << "/// Return true if \\p C is a valid clause for \\p D in version \\p "
364 << "V.\n";
365 OS << "LLVM_ABI bool isAllowedClauseForDirective(Directive D, "
366 << "Clause C, " << VersionType << " V);\n";
367 OS << "\n";
368 OS << "constexpr std::size_t getMaxLeafCount() { return "
369 << getMaxLeafCount(DirLang) << "; }\n";
370 OS << "LLVM_ABI bool isAllowedLoopModifier(Directive D, LoopModifier "
371 "LM);\n";
372 OS << "LLVM_ABI StringRef getLoopModifierName(LoopModifier LM, "
373 << VersionType << " V = " << VersionType << "(0));\n";
374 OS << EnumHelperFuncs;
375 } // close DirLangNS
376
377 // These specializations need to be in ::llvm.
378 for (StringRef Enum :
379 {"Association", "Category", "Directive", "Clause", "LoopModifier"}) {
380 OS << "\n";
381 OS << "template <> struct enum_iteration_traits<"
382 << DirLang.getCppNamespace() << "::" << Enum << "> {\n";
383 OS << " static constexpr bool is_iterable = true;\n";
384 OS << "};\n";
385 }
386}
387
388// Given a list of spellings (for a given clause/directive), order them
389// in a way that allows the use of binary search to locate a spelling
390// for a specified version.
391static std::vector<Spelling::Value>
392orderSpellings(ArrayRef<Spelling::Value> Spellings) {
393 std::vector<Spelling::Value> List(Spellings.begin(), Spellings.end());
394
395 llvm::stable_sort(Range&: List,
396 C: [](const Spelling::Value &A, const Spelling::Value &B) {
397 return A.Versions < B.Versions;
398 });
399 return List;
400}
401
402// Generate function implementation for get<Enum>Name(StringRef Str)
403static void generateGetName(ArrayRef<const Record *> Records, raw_ostream &OS,
404 StringRef Enum, const DirectiveLanguage &DirLang,
405 StringRef LangName, StringRef Prefix) {
406 StringRef VersionType = getVersionType(DirLang);
407 std::string Qual = getQualifier(DirLang);
408 OS << "\n";
409 OS << "llvm::StringRef " << Qual << "get" << LangName << Enum << "Name("
410 << Qual << Enum << " Kind, " << getVersionType(DirLang, /*FullQual=*/true)
411 << " V) {\n";
412 OS << " switch (Kind) {\n";
413 for (const Record *R : Records) {
414 BaseRecord Rec(R);
415 std::string Ident = getIdentifierName(Rec: R, Prefix);
416 OS << " case " << Ident << ":";
417 std::vector<Spelling::Value> Spellings(orderSpellings(Spellings: Rec.getSpellings()));
418 assert(Spellings.size() != 0 && "No spellings for this item");
419 if (Spellings.size() == 1) {
420 OS << "\n";
421 OS << " return \"" << Spellings.front().Name << "\";\n";
422 } else {
423 OS << " {\n";
424 std::string SpellingsName = Ident + "_spellings";
425 OS << " static constexpr llvm::directive::Spelling " << SpellingsName
426 << "[] = {\n";
427 for (auto &S : Spellings) {
428 OS << " {\"" << S.Name << "\", {" << VersionType << "("
429 << S.Versions.Min.value() << "), " << VersionType << "("
430 << S.Versions.Max.value() << ")}},\n";
431 }
432 OS << " };\n";
433 OS << " return llvm::directive::FindName(" << SpellingsName << ", V"
434 << ");\n";
435 OS << " }\n";
436 }
437 }
438 OS << " }\n"; // switch
439 OS << " llvm_unreachable(\"Invalid " << LangName << " " << Enum
440 << " kind\");\n";
441 OS << "}\n";
442}
443
444// Generate function implementation for get<Enum>KindAndVersions(StringRef Str)
445static void generateGetKind(ArrayRef<const Record *> Records, raw_ostream &OS,
446 StringRef Enum, const DirectiveLanguage &DirLang,
447 StringRef Prefix, bool ImplicitAsUnknown) {
448
449 const auto *DefaultIt = find_if(
450 Range&: Records, P: [](const Record *R) { return R->getValueAsBit(FieldName: "isDefault"); });
451
452 if (DefaultIt == Records.end()) {
453 PrintError(Msg: "At least one " + Enum + " must be defined as default.");
454 return;
455 }
456
457 BaseRecord DefaultRec(*DefaultIt);
458 std::string Qual = getQualifier(DirLang);
459 std::string DefaultName = getIdentifierName(Rec: *DefaultIt, Prefix);
460
461 // std::pair<<Enum>, VersionRange>
462 // get<DirLang><Enum>KindAndVersions(StringRef Str);
463 OS << "\n";
464 OS << "std::pair<" << Qual << Enum << ", llvm::directive::VersionRange> "
465 << Qual << "get" << DirLang.getName() << Enum
466 << "KindAndVersions(llvm::StringRef Str) {\n";
467 OS << " directive::VersionRange All; // Default-initialized to \"all "
468 "versions\"\n";
469 OS << " return StringSwitch<std::pair<" << Enum << ", "
470 << "directive::VersionRange>>(Str)\n";
471
472 directive::VersionRange All;
473 StringRef VersionType = getVersionType(DirLang);
474
475 // When a given spelling maps to more than one enum kind, this function
476 // will return one of them, but it's unspecified which one.
477 // This can happen whem a directive/clause uses the same spelling as
478 // another directive/clause, e.g. when it varies depending on the version:
479 // OMPC_foo : {"foo", v1.0}, {"bar", v2.0}
480 // OMPC_bar : {"bar", v1.0}, {"baz", v2.0}
481 // or when the same spelling can be used to mean different things:
482 // OMPC_do_one_thing : {"doit"}
483 // OMPC_do_something_else : {"doit"}
484 for (const Record *R : Records) {
485 BaseRecord Rec(R);
486 std::string Ident = ImplicitAsUnknown && R->getValueAsBit(FieldName: "isImplicit")
487 ? DefaultName
488 : getIdentifierName(Rec: R, Prefix);
489
490 for (auto &[Name, Versions] : Rec.getSpellings()) {
491 OS << " .Case(\"" << Name << "\", {" << Ident << ", ";
492 if (Versions.Min == All.Min && Versions.Max == All.Max)
493 OS << "All})\n";
494 else
495 OS << "{" << VersionType << "(" << Versions.Min.value() << "), "
496 << VersionType << "(" << Versions.Max.value() << ")}})\n";
497 }
498 }
499 OS << " .Default({" << DefaultName << ", All});\n";
500 OS << "}\n";
501}
502
503// Generate function implementations for
504// <enumClauseValue> get<enumClauseValue>(StringRef Str) and
505// StringRef get<enumClauseValue>Name(<enumClauseValue>)
506static void generateGetClauseVal(const DirectiveLanguage &DirLang,
507 raw_ostream &OS) {
508 StringRef Lang = DirLang.getName();
509 std::string Qual = getQualifier(DirLang);
510
511 for (const Clause C : DirLang.getClauses()) {
512 const auto &ClauseVals = C.getClauseVals();
513 if (ClauseVals.size() <= 0)
514 continue;
515
516 auto DefaultIt = find_if(Range: ClauseVals, P: [](const Record *CV) {
517 return CV->getValueAsBit(FieldName: "isDefault");
518 });
519
520 if (DefaultIt == ClauseVals.end()) {
521 PrintError(Msg: "At least one val in Clause " + C.getRecordName() +
522 " must be defined as default.");
523 return;
524 }
525 const auto DefaultName = (*DefaultIt)->getName();
526
527 StringRef Enum = C.getEnumName();
528 if (Enum.empty()) {
529 PrintError(Msg: "enumClauseValue field not set in Clause" + C.getRecordName() +
530 ".");
531 return;
532 }
533
534 OS << "\n";
535 OS << Qual << Enum << " " << Qual << "get" << Enum
536 << "(llvm::StringRef Str) {\n";
537 OS << " return StringSwitch<" << Enum << ">(Str)\n";
538 for (const EnumVal Val : ClauseVals) {
539 OS << " .Case(\"" << Val.getFormattedName() << "\","
540 << Val.getRecordName() << ")\n";
541 }
542 OS << " .Default(" << DefaultName << ");\n";
543 OS << "}\n";
544
545 OS << "\n";
546 OS << "llvm::StringRef " << Qual << "get" << Lang << Enum << "Name(" << Qual
547 << Enum << " x) {\n";
548 OS << " switch (x) {\n";
549 for (const EnumVal Val : ClauseVals) {
550 OS << " case " << Val.getRecordName() << ":\n";
551 OS << " return \"" << Val.getFormattedName() << "\";\n";
552 }
553 OS << " }\n"; // switch
554 OS << " llvm_unreachable(\"Invalid " << Lang << " " << Enum
555 << " kind\");\n";
556 OS << "}\n";
557 }
558}
559
560static void generateCaseForVersionedClauses(ArrayRef<const Record *> VerClauses,
561 raw_ostream &OS,
562 const DirectiveLanguage &DirLang,
563 StringSet<> &Cases) {
564 StringRef Prefix = DirLang.getClausePrefix();
565 for (const Record *R : VerClauses) {
566 VersionedClause VerClause(R);
567 std::string Name =
568 getIdentifierName(Rec: VerClause.getClause().getRecord(), Prefix);
569 if (Cases.insert(key: Name).second) {
570 OS << " case " << Name << ":\n";
571 OS << " return V >= " << VerClause.getMinVersion()
572 << " && V <= " << VerClause.getMaxVersion() << ";\n";
573 }
574 }
575}
576
577// Generate the isAllowedClauseForDirective function implementation.
578static void generateIsAllowedClause(const DirectiveLanguage &DirLang,
579 raw_ostream &OS) {
580 std::string Qual = getQualifier(DirLang);
581
582 OS << "\n";
583 OS << "bool " << Qual << "isAllowedClauseForDirective(" << Qual
584 << "Directive D, " << Qual << "Clause C, "
585 << getVersionType(DirLang, /*FullQual=*/true) << " V) {\n";
586 OS << " assert(unsigned(D) <= Directive_enumSize);\n";
587 OS << " assert(unsigned(C) <= Clause_enumSize);\n";
588
589 OS << " switch (D) {\n";
590
591 StringRef Prefix = DirLang.getDirectivePrefix();
592 for (const Record *R : DirLang.getDirectives()) {
593 Directive Dir(R);
594 OS << " case " << getIdentifierName(Rec: R, Prefix) << ":\n";
595 if (Dir.getAllowedClauses().empty() &&
596 Dir.getAllowedOnceClauses().empty() &&
597 Dir.getAllowedExclusiveClauses().empty() &&
598 Dir.getRequiredClauses().empty()) {
599 OS << " return false;\n";
600 } else {
601 OS << " switch (C) {\n";
602
603 StringSet<> Cases;
604
605 generateCaseForVersionedClauses(VerClauses: Dir.getAllowedClauses(), OS, DirLang,
606 Cases);
607
608 generateCaseForVersionedClauses(VerClauses: Dir.getAllowedOnceClauses(), OS, DirLang,
609 Cases);
610
611 generateCaseForVersionedClauses(VerClauses: Dir.getAllowedExclusiveClauses(), OS,
612 DirLang, Cases);
613
614 generateCaseForVersionedClauses(VerClauses: Dir.getRequiredClauses(), OS, DirLang,
615 Cases);
616
617 OS << " default:\n";
618 OS << " return false;\n";
619 OS << " }\n"; // End of clauses switch
620 }
621 OS << " break;\n";
622 }
623
624 OS << " }\n"; // End of directives switch
625 OS << " llvm_unreachable(\"Invalid " << DirLang.getName()
626 << " Directive kind\");\n";
627 OS << "}\n"; // End of function isAllowedClauseForDirective
628}
629
630static void emitLeafTable(const DirectiveLanguage &DirLang, raw_ostream &OS,
631 StringRef TableName) {
632 // The leaf constructs are emitted in a form of a 2D table, where each
633 // row corresponds to a directive (and there is a row for each directive).
634 //
635 // Each row consists of
636 // - the id of the directive itself,
637 // - number of leaf constructs that will follow (0 for leafs),
638 // - ids of the leaf constructs (none if the directive is itself a leaf).
639 // The total number of these entries is at most MaxLeafCount+2. If this
640 // number is less than that, it is padded to occupy exactly MaxLeafCount+2
641 // entries in memory.
642 //
643 // The rows are stored in the table in the lexicographical order. This
644 // is intended to enable binary search when mapping a sequence of leafs
645 // back to the compound directive.
646 // The consequence of that is that in order to find a row corresponding
647 // to the given directive, we'd need to scan the first element of each
648 // row. To avoid this, an auxiliary ordering table is created, such that
649 // row for Dir_A = table[auxiliary[Dir_A]].
650
651 ArrayRef<const Record *> Directives = DirLang.getDirectives();
652 DenseMap<const Record *, int> DirId; // Record * -> llvm::omp::Directive
653
654 for (auto [Idx, Rec] : enumerate(First&: Directives))
655 DirId.try_emplace(Key: Rec, Args&: Idx);
656
657 using LeafList = std::vector<int>;
658 int MaxLeafCount = getMaxLeafCount(DirLang);
659
660 // The initial leaf table, rows order is same as directive order.
661 std::vector<LeafList> LeafTable(Directives.size());
662 for (auto [Idx, Rec] : enumerate(First&: Directives)) {
663 Directive Dir(Rec);
664 std::vector<const Record *> Leaves = Dir.getLeafConstructs();
665
666 auto &List = LeafTable[Idx];
667 List.resize(new_size: MaxLeafCount + 2);
668 List[0] = Idx; // The id of the directive itself.
669 List[1] = Leaves.size(); // The number of leaves to follow.
670
671 for (int I = 0; I != MaxLeafCount; ++I)
672 List[I + 2] =
673 static_cast<size_t>(I) < Leaves.size() ? DirId.at(Val: Leaves[I]) : -1;
674 }
675
676 // Some Fortran directives are delimited, i.e. they have the form of
677 // "directive"---"end directive". If "directive" is a compound construct,
678 // then the set of leaf constituents will be nonempty and the same for
679 // both directives. Given this set of leafs, looking up the corresponding
680 // compound directive should return "directive", and not "end directive".
681 // To avoid this problem, gather all "end directives" at the end of the
682 // leaf table, and only do the search on the initial segment of the table
683 // that excludes the "end directives".
684 // It's safe to find all directives whose names begin with "end ". The
685 // problem only exists for compound directives, like "end do simd".
686 // All existing directives with names starting with "end " are either
687 // "end directives" for an existing "directive", or leaf directives
688 // (such as "end declare target").
689 DenseSet<int> EndDirectives;
690 for (auto [Rec, Id] : DirId) {
691 // FIXME: This will need to recognize different spellings for different
692 // versions.
693 StringRef Name = Directive(Rec).getSpellingForIdentifier();
694 if (Name.starts_with_insensitive(Prefix: "end "))
695 EndDirectives.insert(V: Id);
696 }
697
698 // Avoid sorting the vector<vector> array, instead sort an index array.
699 // It will also be useful later to create the auxiliary indexing array.
700 std::vector<int> Ordering(Directives.size());
701 std::iota(first: Ordering.begin(), last: Ordering.end(), value: 0);
702
703 llvm::sort(C&: Ordering, Comp: [&](int A, int B) {
704 auto &LeavesA = LeafTable[A];
705 auto &LeavesB = LeafTable[B];
706 int DirA = LeavesA[0], DirB = LeavesB[0];
707 // First of all, end directives compare greater than non-end directives.
708 bool IsEndA = EndDirectives.contains(V: DirA);
709 bool IsEndB = EndDirectives.contains(V: DirB);
710 if (IsEndA != IsEndB)
711 return IsEndA < IsEndB;
712 if (LeavesA[1] == 0 && LeavesB[1] == 0)
713 return DirA < DirB;
714 return std::lexicographical_compare(first1: &LeavesA[2], last1: &LeavesA[2] + LeavesA[1],
715 first2: &LeavesB[2], last2: &LeavesB[2] + LeavesB[1]);
716 });
717
718 // Emit the table
719
720 // The directives are emitted into a scoped enum, for which the underlying
721 // type is `int` (by default). The code above uses `int` to store directive
722 // ids, so make sure that we catch it when something changes in the
723 // underlying type.
724 StringRef Prefix = DirLang.getDirectivePrefix();
725 std::string Qual = getQualifier(DirLang);
726 std::string DirectiveType = Qual + "Directive";
727 OS << "\nstatic_assert(sizeof(" << DirectiveType << ") == sizeof(int));\n";
728
729 OS << "[[maybe_unused]] static const " << DirectiveType << ' ' << TableName
730 << "[][" << MaxLeafCount + 2 << "] = {\n";
731 for (size_t I = 0, E = Directives.size(); I != E; ++I) {
732 auto &Leaves = LeafTable[Ordering[I]];
733 OS << " {" << Qual << getIdentifierName(Rec: Directives[Leaves[0]], Prefix);
734 OS << ", static_cast<" << DirectiveType << ">(" << Leaves[1] << "),";
735 for (size_t I = 2, E = Leaves.size(); I != E; ++I) {
736 int Idx = Leaves[I];
737 if (Idx >= 0)
738 OS << ' ' << Qual << getIdentifierName(Rec: Directives[Leaves[I]], Prefix)
739 << ',';
740 else
741 OS << " static_cast<" << DirectiveType << ">(-1),";
742 }
743 OS << "},\n";
744 }
745 OS << "};\n\n";
746
747 // Emit a marker where the first "end directive" is.
748 auto FirstE = find_if(Range&: Ordering, P: [&](int RowIdx) {
749 return EndDirectives.contains(V: LeafTable[RowIdx][0]);
750 });
751 OS << "[[maybe_unused]] static auto " << TableName
752 << "EndDirective = " << TableName << " + "
753 << std::distance(first: Ordering.begin(), last: FirstE) << ";\n\n";
754
755 // Emit the auxiliary index table: it's the inverse of the `Ordering`
756 // table above.
757 OS << "[[maybe_unused]] static const int " << TableName << "Ordering[] = {\n";
758 OS << " ";
759 std::vector<int> Reverse(Ordering.size());
760 for (int I = 0, E = Ordering.size(); I != E; ++I)
761 Reverse[Ordering[I]] = I;
762 for (int Idx : Reverse)
763 OS << ' ' << Idx << ',';
764 OS << "\n};\n";
765}
766
767static void generateGetDirectiveAssociation(const DirectiveLanguage &DirLang,
768 raw_ostream &OS) {
769 enum struct Association {
770 None = 0, // None should be the smallest value.
771 Block, // If the order of the rest of these changes, update the
772 Declaration, // 'Reduce' function below.
773 Delimited,
774 Explicit,
775 LoopNest,
776 LoopSequence,
777 Separating,
778 FromLeaves,
779 Invalid,
780 };
781
782 ArrayRef<const Record *> Associations = DirLang.getAssociations();
783
784 auto GetAssocValue = [](StringRef Name) -> Association {
785 return StringSwitch<Association>(Name)
786 .Case(S: "AS_Block", Value: Association::Block)
787 .Case(S: "AS_Declaration", Value: Association::Declaration)
788 .Case(S: "AS_Delimited", Value: Association::Delimited)
789 .Case(S: "AS_Explicit", Value: Association::Explicit)
790 .Case(S: "AS_LoopNest", Value: Association::LoopNest)
791 .Case(S: "AS_LoopSeq", Value: Association::LoopSequence)
792 .Case(S: "AS_None", Value: Association::None)
793 .Case(S: "AS_Separating", Value: Association::Separating)
794 .Case(S: "AS_FromLeaves", Value: Association::FromLeaves)
795 .Default(Value: Association::Invalid);
796 };
797
798 auto GetAssocName = [&](Association A) -> StringRef {
799 if (A != Association::Invalid && A != Association::FromLeaves) {
800 const auto *F = find_if(Range&: Associations, P: [&](const Record *R) {
801 return GetAssocValue(R->getName()) == A;
802 });
803 if (F != Associations.end())
804 return (*F)->getValueAsString(FieldName: "name"); // enum name
805 }
806 llvm_unreachable("Unexpected association value");
807 };
808
809 auto ErrorPrefixFor = [&](Directive D) -> std::string {
810 return (Twine("Directive '") + D.getRecordName() + "' in namespace '" +
811 DirLang.getCppNamespace() + "' ")
812 .str();
813 };
814
815 auto Reduce = [&](Association A, Association B) -> Association {
816 if (A > B)
817 std::swap(a&: A, b&: B);
818
819 // Calculate the result using the following rules:
820 // x + x = x
821 // AS_None + x = x
822 // AS_Block + AS_Loop{Nest|Seq} = AS_Loop{Nest|Seq}
823 if (A == Association::None || A == B)
824 return B;
825 if (A == Association::Block &&
826 (B == Association::LoopNest || B == Association::LoopSequence))
827 return B;
828 return Association::Invalid;
829 };
830
831 DenseMap<const Record *, Association> AsMap;
832
833 auto CompAssocImpl = [&](const Record *R, auto &&Self) -> Association {
834 if (auto F = AsMap.find(Val: R); F != AsMap.end())
835 return F->second;
836
837 Directive D(R);
838 Association AS = GetAssocValue(D.getAssociation()->getName());
839 if (AS == Association::Invalid) {
840 PrintFatalError(Msg: ErrorPrefixFor(D) +
841 "has an unrecognized value for association: '" +
842 D.getAssociation()->getName() + "'");
843 }
844 if (AS != Association::FromLeaves) {
845 AsMap.try_emplace(Key: R, Args&: AS);
846 return AS;
847 }
848 // Compute the association from leaf constructs.
849 std::vector<const Record *> Leaves = D.getLeafConstructs();
850 if (Leaves.empty()) {
851 PrintFatalError(Msg: ErrorPrefixFor(D) +
852 "requests association to be computed from leaves, "
853 "but it has no leaves");
854 }
855
856 Association Result = Self(Leaves[0], Self);
857 for (int I = 1, E = Leaves.size(); I < E; ++I) {
858 Association A = Self(Leaves[I], Self);
859 Association R = Reduce(Result, A);
860 if (R == Association::Invalid) {
861 PrintFatalError(Msg: ErrorPrefixFor(D) +
862 "has leaves with incompatible association values: " +
863 GetAssocName(A) + " and " + GetAssocName(R));
864 }
865 Result = R;
866 }
867
868 assert(Result != Association::Invalid);
869 assert(Result != Association::FromLeaves);
870 AsMap.try_emplace(Key: R, Args&: Result);
871 return Result;
872 };
873
874 for (const Record *R : DirLang.getDirectives())
875 CompAssocImpl(R, CompAssocImpl); // Updates AsMap.
876
877 StringRef Prefix = DirLang.getDirectivePrefix();
878
879 OS << "constexpr Association getDirectiveAssociation(Directive Dir) {\n";
880 OS << " switch (Dir) {\n";
881 for (const Record *R : DirLang.getDirectives()) {
882 if (auto F = AsMap.find(Val: R); F != AsMap.end()) {
883 OS << " case " << getIdentifierName(Rec: R, Prefix) << ":\n";
884 OS << " return Association::" << GetAssocName(F->second) << ";\n";
885 }
886 }
887 OS << " } // switch (Dir)\n";
888 OS << "#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 9\n";
889 OS << " abort();\n";
890 OS << "#else\n";
891 OS << " llvm_unreachable(\"Unexpected directive\");\n";
892 OS << "#endif\n";
893 OS << "}\n";
894}
895
896static void generateGetDirectiveCategory(const DirectiveLanguage &DirLang,
897 raw_ostream &OS) {
898 OS << "constexpr Category getDirectiveCategory(Directive Dir) {\n";
899 OS << " switch (Dir) {\n";
900
901 StringRef Prefix = DirLang.getDirectivePrefix();
902
903 for (const Record *R : DirLang.getDirectives()) {
904 Directive D(R);
905 OS << " case " << getIdentifierName(Rec: R, Prefix) << ":\n";
906 OS << " return Category::" << D.getCategory()->getValueAsString(FieldName: "name")
907 << ";\n";
908 }
909 OS << " } // switch (Dir)\n";
910 OS << "#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 9\n";
911 OS << " abort();\n";
912 OS << "#else\n";
913 OS << " llvm_unreachable(\"Unexpected directive\");\n";
914 OS << "#endif\n";
915 OS << "}\n";
916}
917
918// Must match the sentinel in DirectiveBase.td and in
919// OmpStructureChecker::CheckDirectiveInPureProcedure.
920// Note: This is at global scope instead of file scope becasue MSVC 19.29
921// rejects the use of a constexpr local in a captureless lambda (C3493),
922namespace {
923constexpr int NeverPure = 0x7FFFFFFF;
924} // namespace
925static void generateGetDirectivePureSince(const DirectiveLanguage &DirLang,
926 raw_ostream &OS) {
927 StringRef VersionType = getVersionType(DirLang);
928
929 bool AnyPure = any_of(Range: DirLang.getDirectives(), P: [](const Record *R) {
930 Directive D(R);
931 return D.getPureSince() != NeverPure;
932 });
933
934 OS << "constexpr " << VersionType << " getDirectivePureSince(Directive"
935 << (AnyPure ? " Dir" : "") << ") {\n";
936
937 // Only print the switch if we have any pure directives, as the switch with
938 // only a default is a warning on MSVC (C4065).
939 if (AnyPure) {
940 OS << " switch (Dir) {\n";
941 StringRef Prefix = DirLang.getDirectivePrefix();
942
943 for (const Record *R : DirLang.getDirectives()) {
944 Directive D(R);
945 int PureSince = D.getPureSince();
946 if (PureSince == NeverPure)
947 continue;
948 OS << " case " << getIdentifierName(Rec: R, Prefix) << ":\n";
949 OS << " return " << VersionType << "(" << PureSince << ");\n";
950 }
951 OS << " default:\n";
952 OS << " return " << VersionType << "(" << NeverPure << ");\n";
953 OS << " } // switch (Dir)\n";
954 } else {
955 OS << " return " << VersionType << "(" << NeverPure << ");\n";
956 }
957 OS << "}\n";
958}
959
960static void generateGetDirectiveLanguages(const DirectiveLanguage &DirLang,
961 raw_ostream &OS) {
962 OS << "constexpr SourceLanguage getDirectiveLanguages(Directive D) {\n";
963 OS << " switch (D) {\n";
964
965 StringRef Prefix = DirLang.getDirectivePrefix();
966
967 for (const Record *R : DirLang.getDirectives()) {
968 Directive D(R);
969 OS << " case " << getIdentifierName(Rec: R, Prefix) << ":\n";
970 OS << " return ";
971 llvm::interleave(
972 c: D.getSourceLanguages(), os&: OS,
973 each_fn: [&](const Record *L) {
974 StringRef N = L->getValueAsString(FieldName: "name");
975 OS << "SourceLanguage::" << BaseRecord::getSnakeName(Name: N);
976 },
977 separator: " | ");
978 OS << ";\n";
979 }
980 OS << " } // switch(D)\n";
981 OS << "#if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 9\n";
982 OS << " abort();\n";
983 OS << "#else\n";
984 OS << " llvm_unreachable(\"Unexpected directive\");\n";
985 OS << "#endif\n";
986 OS << "}\n";
987}
988
989// Generate the isAllowedLoopModifier function implementation.
990static void generateIsAllowedLoopModifier(const DirectiveLanguage &DirLang,
991 raw_ostream &OS) {
992 std::string Qual = getQualifier(DirLang);
993
994 OS << "\n";
995 OS << "bool " << Qual << "isAllowedLoopModifier(" << Qual << "Directive D, "
996 << Qual << "LoopModifier LM) {\n";
997 OS << " assert(unsigned(D) <= Directive_enumSize);\n";
998
999 OS << " switch (D) {\n";
1000
1001 StringRef DPrefix = DirLang.getDirectivePrefix();
1002 StringRef LMPrefix = DirLang.getLoopModifierPrefix();
1003 for (const Record *R : DirLang.getDirectives()) {
1004 Directive Dir(R);
1005 OS << " case " << getIdentifierName(Rec: R, Prefix: DPrefix) << ":\n";
1006 if (Dir.getAllowedLoopModifiers().empty()) {
1007 OS << " return false;\n";
1008 } else {
1009 OS << " switch (LM) {\n";
1010
1011 for (const Record *LMR : Dir.getAllowedLoopModifiers()) {
1012 std::string Name = getIdentifierName(Rec: LMR, Prefix: LMPrefix);
1013 OS << " case LoopModifier::" << Name << ":\n";
1014 OS << " return true;\n";
1015 }
1016
1017 OS << " default:\n";
1018 OS << " return false;\n";
1019 OS << " }\n"; // End of modifier switch
1020 }
1021 OS << " break;\n";
1022 }
1023
1024 OS << " }\n"; // End of directives switch
1025 OS << " llvm_unreachable(\"Invalid " << DirLang.getName()
1026 << " Directive kind\");\n";
1027 OS << "}\n"; // End of function isAllowedLoopModifier
1028}
1029
1030// Generate a simple enum set with the give clauses.
1031static void generateClauseSet(ArrayRef<const Record *> VerClauses,
1032 raw_ostream &OS, StringRef ClauseSetPrefix,
1033 const Directive &Dir,
1034 const DirectiveLanguage &DirLang, Frontend FE) {
1035
1036 OS << "\n";
1037 OS << "static " << DirLang.getClauseEnumSetClass() << " " << ClauseSetPrefix
1038 << DirLang.getDirectivePrefix() << Dir.getFormattedName() << " {\n";
1039
1040 StringRef Prefix = DirLang.getClausePrefix();
1041
1042 for (const VersionedClause VerClause : VerClauses) {
1043 Clause C = VerClause.getClause();
1044 if (FE == Frontend::Flang) {
1045 OS << " Clause::" << getIdentifierName(Rec: C.getRecord(), Prefix) << ",\n";
1046 } else {
1047 assert(FE == Frontend::Clang);
1048 assert(DirLang.getName() == "OpenACC");
1049 OS << " OpenACCClauseKind::" << C.getClangAccSpelling() << ",\n";
1050 }
1051 }
1052 OS << "};\n";
1053}
1054
1055// Generate an enum set for the 4 kinds of clauses linked to a directive.
1056static void generateDirectiveClauseSets(const DirectiveLanguage &DirLang,
1057 Frontend FE, raw_ostream &OS) {
1058 IfDefEmitter Scope(OS, "GEN_" + getFESpelling(FE).upper() +
1059 "_DIRECTIVE_CLAUSE_SETS");
1060
1061 std::string Namespace =
1062 getFESpelling(FE: FE == Frontend::Flang ? Frontend::LLVM : FE).str();
1063 // The namespace has to be different for clang vs flang, as 2 structs with the
1064 // same name but different layout is UB. So just put the 'clang' on in the
1065 // clang namespace.
1066 // Additionally, open namespaces defined in the directive language.
1067 if (!DirLang.getCppNamespace().empty())
1068 Namespace += "::" + DirLang.getCppNamespace().str();
1069 NamespaceEmitter NS(OS, Namespace);
1070
1071 for (const Directive Dir : DirLang.getDirectives()) {
1072 OS << "// Sets for " << Dir.getSpellingForIdentifier() << "\n";
1073
1074 generateClauseSet(VerClauses: Dir.getAllowedClauses(), OS, ClauseSetPrefix: "allowedClauses_", Dir,
1075 DirLang, FE);
1076 generateClauseSet(VerClauses: Dir.getAllowedOnceClauses(), OS, ClauseSetPrefix: "allowedOnceClauses_",
1077 Dir, DirLang, FE);
1078 generateClauseSet(VerClauses: Dir.getAllowedExclusiveClauses(), OS,
1079 ClauseSetPrefix: "allowedExclusiveClauses_", Dir, DirLang, FE);
1080 generateClauseSet(VerClauses: Dir.getRequiredClauses(), OS, ClauseSetPrefix: "requiredClauses_", Dir,
1081 DirLang, FE);
1082 }
1083}
1084
1085// Generate a map of directive (key) with DirectiveClauses struct as values.
1086// The struct holds the 4 sets of enumeration for the 4 kinds of clauses
1087// allowances (allowed, allowed once, allowed exclusive and required).
1088static void generateDirectiveClauseMap(const DirectiveLanguage &DirLang,
1089 Frontend FE, raw_ostream &OS) {
1090 IfDefEmitter Scope(OS, "GEN_" + getFESpelling(FE).upper() +
1091 "_DIRECTIVE_CLAUSE_MAP");
1092
1093 OS << "{\n";
1094
1095 // The namespace has to be different for clang vs flang, as 2 structs with the
1096 // same name but different layout is UB. So just put the 'clang' on in the
1097 // clang namespace.
1098 std::string Qual =
1099 getQualifier(DirLang, FE: FE == Frontend::Flang ? Frontend::LLVM : FE);
1100 StringRef Prefix = DirLang.getDirectivePrefix();
1101
1102 for (const Record *R : DirLang.getDirectives()) {
1103 Directive Dir(R);
1104 std::string Name = getIdentifierName(Rec: R, Prefix);
1105
1106 OS << " {";
1107 if (FE == Frontend::Flang) {
1108 OS << Qual << "Directive::" << Name << ",\n";
1109 } else {
1110 assert(FE == Frontend::Clang);
1111 assert(DirLang.getName() == "OpenACC");
1112 OS << "clang::OpenACCDirectiveKind::" << Dir.getClangAccSpelling()
1113 << ",\n";
1114 }
1115
1116 OS << " {\n";
1117 OS << " " << Qual << "allowedClauses_" << Name << ",\n";
1118 OS << " " << Qual << "allowedOnceClauses_" << Name << ",\n";
1119 OS << " " << Qual << "allowedExclusiveClauses_" << Name << ",\n";
1120 OS << " " << Qual << "requiredClauses_" << Name << ",\n";
1121 OS << " }\n";
1122 OS << " },\n";
1123 }
1124
1125 OS << "}\n";
1126}
1127
1128// Generate classes entry for Flang clauses in the Flang parse-tree
1129// If the clause as a non-generic class, no entry is generated.
1130// If the clause does not hold a value, an EMPTY_CLASS is used.
1131// If the clause class is generic then a WRAPPER_CLASS is used. When the value
1132// is optional, the value class is wrapped into a std::optional.
1133static void generateFlangClauseParserClass(const DirectiveLanguage &DirLang,
1134 raw_ostream &OS) {
1135
1136 IfDefEmitter Scope(OS, "GEN_FLANG_CLAUSE_PARSER_CLASSES");
1137
1138 for (const Clause Clause : DirLang.getClauses()) {
1139 if (!Clause.getFlangClass().empty()) {
1140 OS << "WRAPPER_CLASS(" << Clause.getFormattedParserClassName() << ", ";
1141 if (Clause.isValueOptional() && Clause.isValueList()) {
1142 OS << "std::optional<std::list<" << Clause.getFlangClass() << ">>";
1143 } else if (Clause.isValueOptional()) {
1144 OS << "std::optional<" << Clause.getFlangClass() << ">";
1145 } else if (Clause.isValueList()) {
1146 OS << "std::list<" << Clause.getFlangClass() << ">";
1147 } else {
1148 OS << Clause.getFlangClass();
1149 }
1150 } else {
1151 OS << "EMPTY_CLASS(" << Clause.getFormattedParserClassName();
1152 }
1153 OS << ");\n";
1154 }
1155}
1156
1157// Generate a list of the different clause classes for Flang.
1158static void generateFlangClauseParserClassList(const DirectiveLanguage &DirLang,
1159 raw_ostream &OS) {
1160
1161 IfDefEmitter Scope(OS, "GEN_FLANG_CLAUSE_PARSER_CLASSES_LIST");
1162
1163 interleaveComma(c: DirLang.getClauses(), os&: OS, each_fn: [&](const Record *C) {
1164 Clause Clause(C);
1165 OS << Clause.getFormattedParserClassName() << "\n";
1166 });
1167}
1168
1169// Generate dump node list for the clauses holding a generic class name.
1170static void generateFlangClauseDump(const DirectiveLanguage &DirLang,
1171 raw_ostream &OS) {
1172
1173 IfDefEmitter Scope(OS, "GEN_FLANG_DUMP_PARSE_TREE_CLAUSES");
1174
1175 for (const Clause Clause : DirLang.getClauses()) {
1176 OS << "NODE(" << DirLang.getFlangClauseBaseClass() << ", "
1177 << Clause.getFormattedParserClassName() << ")\n";
1178 }
1179}
1180
1181// Generate Unparse functions for clauses classes in the Flang parse-tree
1182// If the clause is a non-generic class, no entry is generated.
1183static void generateFlangClauseUnparse(const DirectiveLanguage &DirLang,
1184 raw_ostream &OS) {
1185
1186 IfDefEmitter Scope(OS, "GEN_FLANG_CLAUSE_UNPARSE");
1187
1188 StringRef Base = DirLang.getFlangClauseBaseClass();
1189
1190 for (const Clause Clause : DirLang.getClauses()) {
1191 if (Clause.skipFlangUnparser())
1192 continue;
1193 // The unparser doesn't know the effective version, so just pick some
1194 // spelling.
1195 StringRef SomeSpelling = Clause.getSpellingForIdentifier();
1196 std::string Parser = Clause.getFormattedParserClassName();
1197 std::string Upper = SomeSpelling.upper();
1198
1199 if (!Clause.getFlangClass().empty()) {
1200 if (Clause.isValueOptional() && Clause.getDefaultValue().empty()) {
1201 OS << "void Unparse(const " << Base << "::" << Parser << " &x) {\n";
1202 OS << " Word(\"" << Upper << "\");\n";
1203
1204 OS << " Walk(\"(\", x.v, \")\");\n";
1205 OS << "}\n";
1206 } else if (Clause.isValueOptional()) {
1207 OS << "void Unparse(const " << Base << "::" << Parser << " &x) {\n";
1208 OS << " Word(\"" << Upper << "\");\n";
1209 OS << " Put(\"(\");\n";
1210 OS << " if (x.v.has_value())\n";
1211 if (Clause.isValueList())
1212 OS << " Walk(x.v, \",\");\n";
1213 else
1214 OS << " Walk(x.v);\n";
1215 OS << " else\n";
1216 OS << " Put(\"" << Clause.getDefaultValue() << "\");\n";
1217 OS << " Put(\")\");\n";
1218 OS << "}\n";
1219 } else {
1220 OS << "void Unparse(const " << Base << "::" << Parser << " &x) {\n";
1221 OS << " Word(\"" << Upper << "\");\n";
1222 OS << " Put(\"(\");\n";
1223 if (Clause.isValueList())
1224 OS << " Walk(x.v, \",\");\n";
1225 else
1226 OS << " Walk(x.v);\n";
1227 OS << " Put(\")\");\n";
1228 OS << "}\n";
1229 }
1230 } else {
1231 OS << "void Before(const " << Base << "::" << Parser << " &) { Word(\""
1232 << Upper << "\"); }\n";
1233 }
1234 }
1235}
1236
1237// Generate check in the Enter functions for clauses classes.
1238static void generateFlangClauseCheckPrototypes(const DirectiveLanguage &DirLang,
1239 raw_ostream &OS) {
1240
1241 IfDefEmitter Scope(OS, "GEN_FLANG_CLAUSE_CHECK_ENTER");
1242
1243 for (const Clause Clause : DirLang.getClauses()) {
1244 OS << "void Enter(const parser::" << DirLang.getFlangClauseBaseClass()
1245 << "::" << Clause.getFormattedParserClassName() << " &);\n";
1246 }
1247}
1248
1249// Generate the mapping for clauses between the parser class and the
1250// corresponding clause Kind
1251static void generateFlangClauseParserKindMap(const DirectiveLanguage &DirLang,
1252 raw_ostream &OS) {
1253
1254 IfDefEmitter Scope(OS, "GEN_FLANG_CLAUSE_PARSER_KIND_MAP");
1255
1256 StringRef Prefix = DirLang.getClausePrefix();
1257 std::string Qual = getQualifier(DirLang);
1258
1259 for (const Record *R : DirLang.getClauses()) {
1260 Clause C(R);
1261 OS << "if constexpr (std::is_same_v<A, parser::"
1262 << DirLang.getFlangClauseBaseClass()
1263 << "::" << C.getFormattedParserClassName();
1264 OS << ">)\n";
1265 OS << " return " << Qual << "Clause::" << getIdentifierName(Rec: R, Prefix)
1266 << ";\n";
1267 }
1268
1269 OS << "llvm_unreachable(\"Invalid " << DirLang.getName()
1270 << " Parser clause\");\n";
1271}
1272
1273// Generate the parser for the clauses.
1274static void generateFlangClausesParser(const DirectiveLanguage &DirLang,
1275 raw_ostream &OS) {
1276 std::vector<const Record *> Clauses = DirLang.getClauses();
1277 // Sort clauses in the reverse alphabetical order with respect to their
1278 // names and aliases, so that longer names are tried before shorter ones.
1279 std::vector<RecordWithSpelling> Names = getSpellings(Records: Clauses);
1280 llvm::sort(C&: Names, Comp: [](const auto &A, const auto &B) {
1281 return A.second.Name > B.second.Name;
1282 });
1283 IfDefEmitter Scope(OS, "GEN_FLANG_CLAUSES_PARSER");
1284 StringRef Base = DirLang.getFlangClauseBaseClass();
1285
1286 unsigned LastIndex = Names.size() - 1;
1287 OS << "TYPE_PARSER(\n";
1288 for (auto [Index, RecSp] : llvm::enumerate(First&: Names)) {
1289 auto [R, S] = RecSp;
1290 Clause C(R);
1291
1292 StringRef FlangClass = C.getFlangClass();
1293 OS << " \"" << S.Name << "\" >> construct<" << Base << ">(construct<"
1294 << Base << "::" << C.getFormattedParserClassName() << ">(";
1295 if (FlangClass.empty()) {
1296 OS << "))";
1297 if (Index != LastIndex)
1298 OS << " ||";
1299 OS << "\n";
1300 continue;
1301 }
1302
1303 if (C.isValueOptional())
1304 OS << "maybe(";
1305 OS << "parenthesized(";
1306 if (C.isValueList())
1307 OS << "nonemptyList(";
1308
1309 if (!C.getPrefix().empty())
1310 OS << "\"" << C.getPrefix() << " :\" >> ";
1311
1312 // The common Flang parser are used directly. Their name is identical to
1313 // the Flang class with first letter as lowercase. If the Flang class is
1314 // not a common class, we assume there is a specific Parser<>{} with the
1315 // Flang class name provided.
1316 SmallString<128> Scratch;
1317 StringRef Parser =
1318 StringSwitch<StringRef>(FlangClass)
1319 .Case(S: "Name", Value: "name")
1320 .Case(S: "ScalarIntConstantExpr", Value: "scalarIntConstantExpr")
1321 .Case(S: "ScalarIntExpr", Value: "scalarIntExpr")
1322 .Case(S: "ScalarExpr", Value: "scalarExpr")
1323 .Case(S: "ScalarLogicalExpr", Value: "scalarLogicalExpr")
1324 .Default(Value: ("Parser<" + FlangClass + ">{}").toStringRef(Out&: Scratch));
1325 OS << Parser;
1326 if (!C.getPrefix().empty() && C.isPrefixOptional())
1327 OS << " || " << Parser;
1328 if (C.isValueList()) // close nonemptyList(.
1329 OS << ")";
1330 OS << ")"; // close parenthesized(.
1331
1332 if (C.isValueOptional()) // close maybe(.
1333 OS << ")";
1334 OS << "))";
1335 if (Index != LastIndex)
1336 OS << " ||";
1337 OS << "\n";
1338 }
1339 OS << ")\n";
1340}
1341
1342// Generate the implementation section for the enumeration in the directive
1343// language
1344static void emitDirectivesClangImpl(const DirectiveLanguage &DirLang,
1345 raw_ostream &OS) {
1346 // Currently we only have work to do for OpenACC, so skip otherwise.
1347 if (DirLang.getName() != "OpenACC")
1348 return;
1349
1350 generateDirectiveClauseSets(DirLang, FE: Frontend::Clang, OS);
1351 generateDirectiveClauseMap(DirLang, FE: Frontend::Clang, OS);
1352}
1353// Generate the implementation section for the enumeration in the directive
1354// language
1355static void emitDirectivesFlangImpl(const DirectiveLanguage &DirLang,
1356 raw_ostream &OS) {
1357 generateDirectiveClauseSets(DirLang, FE: Frontend::Flang, OS);
1358
1359 generateDirectiveClauseMap(DirLang, FE: Frontend::Flang, OS);
1360
1361 generateFlangClauseParserClass(DirLang, OS);
1362
1363 generateFlangClauseParserClassList(DirLang, OS);
1364
1365 generateFlangClauseDump(DirLang, OS);
1366
1367 generateFlangClauseUnparse(DirLang, OS);
1368
1369 generateFlangClauseCheckPrototypes(DirLang, OS);
1370
1371 generateFlangClauseParserKindMap(DirLang, OS);
1372
1373 generateFlangClausesParser(DirLang, OS);
1374}
1375
1376static void generateClauseClassMacro(const DirectiveLanguage &DirLang,
1377 raw_ostream &OS) {
1378 // Generate macros style information for legacy code in clang
1379 IfDefEmitter Scope(OS, "GEN_CLANG_CLAUSE_CLASS");
1380
1381 StringRef Prefix = DirLang.getClausePrefix();
1382
1383 OS << "#ifndef CLAUSE\n";
1384 OS << "#define CLAUSE(Enum, Str, Implicit)\n";
1385 OS << "#endif\n";
1386 OS << "#ifndef CLAUSE_CLASS\n";
1387 OS << "#define CLAUSE_CLASS(Enum, Str, Class)\n";
1388 OS << "#endif\n";
1389 OS << "#ifndef CLAUSE_NO_CLASS\n";
1390 OS << "#define CLAUSE_NO_CLASS(Enum, Str)\n";
1391 OS << "#endif\n";
1392 OS << "\n";
1393 OS << "#define __CLAUSE(Name, Class) \\\n";
1394 OS << " CLAUSE(" << Prefix << "##Name, #Name, /* Implicit */ false) \\\n";
1395 OS << " CLAUSE_CLASS(" << Prefix << "##Name, #Name, Class)\n";
1396 OS << "#define __CLAUSE_NO_CLASS(Name) \\\n";
1397 OS << " CLAUSE(" << Prefix << "##Name, #Name, /* Implicit */ false) \\\n";
1398 OS << " CLAUSE_NO_CLASS(" << Prefix << "##Name, #Name)\n";
1399 OS << "#define __IMPLICIT_CLAUSE_CLASS(Name, Str, Class) \\\n";
1400 OS << " CLAUSE(" << Prefix << "##Name, Str, /* Implicit */ true) \\\n";
1401 OS << " CLAUSE_CLASS(" << Prefix << "##Name, Str, Class)\n";
1402 OS << "#define __IMPLICIT_CLAUSE_NO_CLASS(Name, Str) \\\n";
1403 OS << " CLAUSE(" << Prefix << "##Name, Str, /* Implicit */ true) \\\n";
1404 OS << " CLAUSE_NO_CLASS(" << Prefix << "##Name, Str)\n";
1405 OS << "\n";
1406
1407 for (const Clause C : DirLang.getClauses()) {
1408 std::string Name = C.getFormattedName();
1409 if (C.getClangClass().empty()) { // NO_CLASS
1410 if (C.isImplicit()) {
1411 OS << "__IMPLICIT_CLAUSE_NO_CLASS(" << Name << ", \"" << Name
1412 << "\")\n";
1413 } else {
1414 OS << "__CLAUSE_NO_CLASS(" << Name << ")\n";
1415 }
1416 } else { // CLASS
1417 if (C.isImplicit()) {
1418 OS << "__IMPLICIT_CLAUSE_CLASS(" << Name << ", \"" << Name << "\", "
1419 << C.getClangClass() << ")\n";
1420 } else {
1421 OS << "__CLAUSE(" << Name << ", " << C.getClangClass() << ")\n";
1422 }
1423 }
1424 }
1425
1426 OS << "\n";
1427 OS << "#undef __IMPLICIT_CLAUSE_NO_CLASS\n";
1428 OS << "#undef __IMPLICIT_CLAUSE_CLASS\n";
1429 OS << "#undef __CLAUSE_NO_CLASS\n";
1430 OS << "#undef __CLAUSE\n";
1431 OS << "#undef CLAUSE_NO_CLASS\n";
1432 OS << "#undef CLAUSE_CLASS\n";
1433 OS << "#undef CLAUSE\n";
1434}
1435
1436static void emitDirectivesConstexprImpl(const DirectiveLanguage &DirLang,
1437 raw_ostream &OS) {
1438 OS << "// Constexpr functions.\n";
1439 OS << "\n";
1440 generateGetDirectiveAssociation(DirLang, OS);
1441 OS << "\n";
1442 generateGetDirectiveCategory(DirLang, OS);
1443 OS << "\n";
1444 generateGetDirectivePureSince(DirLang, OS);
1445 OS << "\n";
1446 generateGetDirectiveLanguages(DirLang, OS);
1447}
1448
1449// Generate the implemenation for the enumeration in the directive
1450// language. This code can be included in library.
1451void emitDirectivesBasicImpl(const DirectiveLanguage &DirLang,
1452 raw_ostream &OS) {
1453 IfDefEmitter Scope(OS, "GEN_DIRECTIVES_IMPL");
1454
1455 StringRef DPrefix = DirLang.getDirectivePrefix();
1456 StringRef CPrefix = DirLang.getClausePrefix();
1457
1458 OS << "#include \"llvm/Frontend/Directive/Spelling.h\"\n";
1459 OS << "#include \"llvm/Frontend/Directive/Version.h\"\n";
1460 OS << "#include \"llvm/Support/ErrorHandling.h\"\n";
1461 OS << "#include <utility>\n";
1462
1463 // getDirectiveKind(StringRef Str)
1464 generateGetKind(Records: DirLang.getDirectives(), OS, Enum: "Directive", DirLang, Prefix: DPrefix,
1465 /*ImplicitAsUnknown=*/false);
1466
1467 // getDirectiveName(Directive Kind)
1468 generateGetName(Records: DirLang.getDirectives(), OS, Enum: "Directive", DirLang,
1469 LangName: DirLang.getName(), Prefix: DPrefix);
1470
1471 // getClauseKind(StringRef Str)
1472 generateGetKind(Records: DirLang.getClauses(), OS, Enum: "Clause", DirLang, Prefix: CPrefix,
1473 /*ImplicitAsUnknown=*/true);
1474
1475 // getClauseName(Clause Kind)
1476 generateGetName(Records: DirLang.getClauses(), OS, Enum: "Clause", DirLang,
1477 LangName: DirLang.getName(), Prefix: CPrefix);
1478
1479 // <enumClauseValue> get<enumClauseValue>(StringRef Str) ; string -> value
1480 // StringRef get<enumClauseValue>Name(<enumClauseValue>) ; value -> string
1481 generateGetClauseVal(DirLang, OS);
1482
1483 // isAllowedClauseForDirective(Directive D, Clause C, Version V)
1484 generateIsAllowedClause(DirLang, OS);
1485
1486 // isAllowedLoopModifier(Directive D, LoopModifier LM)
1487 generateIsAllowedLoopModifier(DirLang, OS);
1488
1489 // getLoopModifierName(LoopModifier Kind)
1490 generateGetName(Records: DirLang.getLoopModifiers(), OS, Enum: "LoopModifier", DirLang, LangName: "",
1491 Prefix: DirLang.getLoopModifierPrefix());
1492
1493 // Leaf table for getLeafConstructs, etc.
1494 emitLeafTable(DirLang, OS, TableName: "LeafConstructTable");
1495}
1496
1497// Generate the implemenation section for the enumeration in the directive
1498// language.
1499static void emitDirectivesImpl(const RecordKeeper &Records, raw_ostream &OS) {
1500 const auto DirLang = DirectiveLanguage(Records);
1501 if (DirLang.HasValidityErrors())
1502 return;
1503
1504 emitDirectivesFlangImpl(DirLang, OS);
1505
1506 emitDirectivesClangImpl(DirLang, OS);
1507
1508 generateClauseClassMacro(DirLang, OS);
1509
1510 emitDirectivesBasicImpl(DirLang, OS);
1511}
1512
1513static TableGen::Emitter::Opt
1514 X("gen-directive-decl", emitDirectivesDecl,
1515 "Generate directive related declaration code (header file)");
1516
1517static TableGen::Emitter::Opt
1518 Y("gen-directive-impl", emitDirectivesImpl,
1519 "Generate directive related implementation code");
1520