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/ADT/STLExtras.h"
15 #include "llvm/ADT/SmallVector.h"
16 #include "llvm/ADT/StringExtras.h"
17 #include "llvm/ADT/StringSet.h"
18 #include "llvm/TableGen/Error.h"
19 #include "llvm/TableGen/Record.h"
20 #include "llvm/TableGen/TableGenBackend.h"
21 
22 using namespace llvm;
23 
24 namespace {
25 // Simple RAII helper for defining ifdef-undef-endif scopes.
26 class IfDefScope {
27 public:
28   IfDefScope(StringRef Name, raw_ostream &OS) : Name(Name), OS(OS) {
29     OS << "#ifdef " << Name << "\n"
30        << "#undef " << Name << "\n";
31   }
32 
33   ~IfDefScope() { OS << "\n#endif // " << Name << "\n\n"; }
34 
35 private:
36   StringRef Name;
37   raw_ostream &OS;
38 };
39 } // end anonymous namespace
40 
41 namespace llvm {
42 
43 // Wrapper class that contains DirectiveLanguage's information defined in
44 // DirectiveBase.td and provides helper methods for accessing it.
45 class DirectiveLanguage {
46 public:
47   explicit DirectiveLanguage(const llvm::Record *Def) : Def(Def) {}
48 
49   StringRef getName() const { return Def->getValueAsString("name"); }
50 
51   StringRef getCppNamespace() const {
52     return Def->getValueAsString("cppNamespace");
53   }
54 
55   StringRef getDirectivePrefix() const {
56     return Def->getValueAsString("directivePrefix");
57   }
58 
59   StringRef getClausePrefix() const {
60     return Def->getValueAsString("clausePrefix");
61   }
62 
63   StringRef getIncludeHeader() const {
64     return Def->getValueAsString("includeHeader");
65   }
66 
67   StringRef getClauseEnumSetClass() const {
68     return Def->getValueAsString("clauseEnumSetClass");
69   }
70 
71   bool hasMakeEnumAvailableInNamespace() const {
72     return Def->getValueAsBit("makeEnumAvailableInNamespace");
73   }
74 
75   bool hasEnableBitmaskEnumInNamespace() const {
76     return Def->getValueAsBit("enableBitmaskEnumInNamespace");
77   }
78 
79 private:
80   const llvm::Record *Def;
81 };
82 
83 // Base record class used for Directive and Clause class defined in
84 // DirectiveBase.td.
85 class BaseRecord {
86 public:
87   explicit BaseRecord(const llvm::Record *Def) : Def(Def) {}
88 
89   StringRef getName() const { return Def->getValueAsString("name"); }
90 
91   StringRef getAlternativeName() const {
92     return Def->getValueAsString("alternativeName");
93   }
94 
95   // Returns the name of the directive formatted for output. Whitespace are
96   // replaced with underscores.
97   std::string getFormattedName() {
98     StringRef Name = Def->getValueAsString("name");
99     std::string N = Name.str();
100     std::replace(N.begin(), N.end(), ' ', '_');
101     return N;
102   }
103 
104   bool isDefault() const { return Def->getValueAsBit("isDefault"); }
105 
106 protected:
107   const llvm::Record *Def;
108 };
109 
110 // Wrapper class that contains a Directive's information defined in
111 // DirectiveBase.td and provides helper methods for accessing it.
112 class Directive : public BaseRecord {
113 public:
114   explicit Directive(const llvm::Record *Def) : BaseRecord(Def) {}
115 
116   std::vector<Record *> getAllowedClauses() const {
117     return Def->getValueAsListOfDefs("allowedClauses");
118   }
119 
120   std::vector<Record *> getAllowedOnceClauses() const {
121     return Def->getValueAsListOfDefs("allowedOnceClauses");
122   }
123 
124   std::vector<Record *> getAllowedExclusiveClauses() const {
125     return Def->getValueAsListOfDefs("allowedExclusiveClauses");
126   }
127 
128   std::vector<Record *> getRequiredClauses() const {
129     return Def->getValueAsListOfDefs("requiredClauses");
130   }
131 };
132 
133 // Wrapper class that contains Clause's information defined in DirectiveBase.td
134 // and provides helper methods for accessing it.
135 class Clause : public BaseRecord {
136 public:
137   explicit Clause(const llvm::Record *Def) : BaseRecord(Def) {}
138 
139   // Optional field.
140   StringRef getClangClass() const {
141     return Def->getValueAsString("clangClass");
142   }
143 
144   // Optional field.
145   StringRef getFlangClass() const {
146     return Def->getValueAsString("flangClass");
147   }
148 
149   bool isImplict() const { return Def->getValueAsBit("isImplicit"); }
150 };
151 
152 // Wrapper class that contains VersionedClause's information defined in
153 // DirectiveBase.td and provides helper methods for accessing it.
154 class VersionedClause {
155 public:
156   explicit VersionedClause(const llvm::Record *Def) : Def(Def) {}
157 
158   // Return the specific clause record wrapped in the Clause class.
159   Clause getClause() const { return Clause{Def->getValueAsDef("clause")}; }
160 
161   int64_t getMinVersion() const { return Def->getValueAsInt("minVersion"); }
162 
163   int64_t getMaxVersion() const { return Def->getValueAsInt("maxVersion"); }
164 
165 private:
166   const llvm::Record *Def;
167 };
168 
169 // Generate enum class
170 void GenerateEnumClass(const std::vector<Record *> &Records, raw_ostream &OS,
171                        StringRef Enum, StringRef Prefix,
172                        DirectiveLanguage &DirLang) {
173   OS << "\n";
174   OS << "enum class " << Enum << " {\n";
175   for (const auto &R : Records) {
176     BaseRecord Rec{R};
177     OS << "  " << Prefix << Rec.getFormattedName() << ",\n";
178   }
179   OS << "};\n";
180   OS << "\n";
181   OS << "static constexpr std::size_t " << Enum
182      << "_enumSize = " << Records.size() << ";\n";
183 
184   // Make the enum values available in the defined namespace. This allows us to
185   // write something like Enum_X if we have a `using namespace <CppNamespace>`.
186   // At the same time we do not loose the strong type guarantees of the enum
187   // class, that is we cannot pass an unsigned as Directive without an explicit
188   // cast.
189   if (DirLang.hasMakeEnumAvailableInNamespace()) {
190     OS << "\n";
191     for (const auto &R : Records) {
192       BaseRecord Rec{R};
193       OS << "constexpr auto " << Prefix << Rec.getFormattedName() << " = "
194          << "llvm::" << DirLang.getCppNamespace() << "::" << Enum
195          << "::" << Prefix << Rec.getFormattedName() << ";\n";
196     }
197   }
198 }
199 
200 // Generate the declaration section for the enumeration in the directive
201 // language
202 void EmitDirectivesDecl(RecordKeeper &Records, raw_ostream &OS) {
203 
204   const auto &DirectiveLanguages =
205       Records.getAllDerivedDefinitions("DirectiveLanguage");
206 
207   if (DirectiveLanguages.size() != 1) {
208     PrintError("A single definition of DirectiveLanguage is needed.");
209     return;
210   }
211 
212   DirectiveLanguage DirLang{DirectiveLanguages[0]};
213 
214   OS << "#ifndef LLVM_" << DirLang.getName() << "_INC\n";
215   OS << "#define LLVM_" << DirLang.getName() << "_INC\n";
216 
217   if (DirLang.hasEnableBitmaskEnumInNamespace())
218     OS << "\n#include \"llvm/ADT/BitmaskEnum.h\"\n";
219 
220   OS << "\n";
221   OS << "namespace llvm {\n";
222   OS << "class StringRef;\n";
223 
224   // Open namespaces defined in the directive language
225   llvm::SmallVector<StringRef, 2> Namespaces;
226   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
227   for (auto Ns : Namespaces)
228     OS << "namespace " << Ns << " {\n";
229 
230   if (DirLang.hasEnableBitmaskEnumInNamespace())
231     OS << "\nLLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();\n";
232 
233   // Emit Directive enumeration
234   const auto &Directives = Records.getAllDerivedDefinitions("Directive");
235   GenerateEnumClass(Directives, OS, "Directive", DirLang.getDirectivePrefix(),
236                     DirLang);
237 
238   // Emit Clause enumeration
239   const auto &Clauses = Records.getAllDerivedDefinitions("Clause");
240   GenerateEnumClass(Clauses, OS, "Clause", DirLang.getClausePrefix(), DirLang);
241 
242   // Generic function signatures
243   OS << "\n";
244   OS << "// Enumeration helper functions\n";
245   OS << "Directive get" << DirLang.getName()
246      << "DirectiveKind(llvm::StringRef Str);\n";
247   OS << "\n";
248   OS << "llvm::StringRef get" << DirLang.getName()
249      << "DirectiveName(Directive D);\n";
250   OS << "\n";
251   OS << "Clause get" << DirLang.getName()
252      << "ClauseKind(llvm::StringRef Str);\n";
253   OS << "\n";
254   OS << "llvm::StringRef get" << DirLang.getName() << "ClauseName(Clause C);\n";
255   OS << "\n";
256   OS << "/// Return true if \\p C is a valid clause for \\p D in version \\p "
257      << "Version.\n";
258   OS << "bool isAllowedClauseForDirective(Directive D, "
259      << "Clause C, unsigned Version);\n";
260   OS << "\n";
261 
262   // Closing namespaces
263   for (auto Ns : llvm::reverse(Namespaces))
264     OS << "} // namespace " << Ns << "\n";
265 
266   OS << "} // namespace llvm\n";
267 
268   OS << "#endif // LLVM_" << DirLang.getName() << "_INC\n";
269 }
270 
271 // Generate function implementation for get<Enum>Name(StringRef Str)
272 void GenerateGetName(const std::vector<Record *> &Records, raw_ostream &OS,
273                      StringRef Enum, DirectiveLanguage &DirLang,
274                      StringRef Prefix) {
275   OS << "\n";
276   OS << "llvm::StringRef llvm::" << DirLang.getCppNamespace() << "::get"
277      << DirLang.getName() << Enum << "Name(" << Enum << " Kind) {\n";
278   OS << "  switch (Kind) {\n";
279   for (const auto &R : Records) {
280     BaseRecord Rec{R};
281     OS << "    case " << Prefix << Rec.getFormattedName() << ":\n";
282     OS << "      return \"";
283     if (Rec.getAlternativeName().empty())
284       OS << Rec.getName();
285     else
286       OS << Rec.getAlternativeName();
287     OS << "\";\n";
288   }
289   OS << "  }\n"; // switch
290   OS << "  llvm_unreachable(\"Invalid " << DirLang.getName() << " " << Enum
291      << " kind\");\n";
292   OS << "}\n";
293 }
294 
295 // Generate function implementation for get<Enum>Kind(StringRef Str)
296 void GenerateGetKind(const std::vector<Record *> &Records, raw_ostream &OS,
297                      StringRef Enum, DirectiveLanguage &DirLang,
298                      StringRef Prefix, bool ImplicitAsUnknown) {
299 
300   auto DefaultIt = std::find_if(Records.begin(), Records.end(), [](Record *R) {
301     return R->getValueAsBit("isDefault") == true;
302   });
303 
304   if (DefaultIt == Records.end()) {
305     PrintError("A least one " + Enum + " must be defined as default.");
306     return;
307   }
308 
309   BaseRecord DefaultRec{(*DefaultIt)};
310 
311   OS << "\n";
312   OS << Enum << " llvm::" << DirLang.getCppNamespace() << "::get"
313      << DirLang.getName() << Enum << "Kind(llvm::StringRef Str) {\n";
314   OS << "  return llvm::StringSwitch<" << Enum << ">(Str)\n";
315 
316   for (const auto &R : Records) {
317     BaseRecord Rec{R};
318     if (ImplicitAsUnknown && R->getValueAsBit("isImplicit")) {
319       OS << "    .Case(\"" << Rec.getName() << "\"," << Prefix
320          << DefaultRec.getFormattedName() << ")\n";
321     } else {
322       OS << "    .Case(\"" << Rec.getName() << "\"," << Prefix
323          << Rec.getFormattedName() << ")\n";
324     }
325   }
326   OS << "    .Default(" << Prefix << DefaultRec.getFormattedName() << ");\n";
327   OS << "}\n";
328 }
329 
330 void GenerateCaseForVersionedClauses(const std::vector<Record *> &Clauses,
331                                      raw_ostream &OS, StringRef DirectiveName,
332                                      DirectiveLanguage &DirLang,
333                                      llvm::StringSet<> &Cases) {
334   for (const auto &C : Clauses) {
335     VersionedClause VerClause{C};
336 
337     const auto ClauseFormattedName = VerClause.getClause().getFormattedName();
338 
339     if (Cases.find(ClauseFormattedName) == Cases.end()) {
340       Cases.insert(ClauseFormattedName);
341       OS << "        case " << DirLang.getClausePrefix() << ClauseFormattedName
342          << ":\n";
343       OS << "          return " << VerClause.getMinVersion()
344          << " <= Version && " << VerClause.getMaxVersion() << " >= Version;\n";
345     }
346   }
347 }
348 
349 // Generate the isAllowedClauseForDirective function implementation.
350 void GenerateIsAllowedClause(const std::vector<Record *> &Directives,
351                              raw_ostream &OS, DirectiveLanguage &DirLang) {
352   OS << "\n";
353   OS << "bool llvm::" << DirLang.getCppNamespace()
354      << "::isAllowedClauseForDirective("
355      << "Directive D, Clause C, unsigned Version) {\n";
356   OS << "  assert(unsigned(D) <= llvm::" << DirLang.getCppNamespace()
357      << "::Directive_enumSize);\n";
358   OS << "  assert(unsigned(C) <= llvm::" << DirLang.getCppNamespace()
359      << "::Clause_enumSize);\n";
360 
361   OS << "  switch (D) {\n";
362 
363   for (const auto &D : Directives) {
364     Directive Dir{D};
365 
366     OS << "    case " << DirLang.getDirectivePrefix() << Dir.getFormattedName()
367        << ":\n";
368     if (Dir.getAllowedClauses().size() == 0 &&
369         Dir.getAllowedOnceClauses().size() == 0 &&
370         Dir.getAllowedExclusiveClauses().size() == 0 &&
371         Dir.getRequiredClauses().size() == 0) {
372       OS << "      return false;\n";
373     } else {
374       OS << "      switch (C) {\n";
375 
376       llvm::StringSet<> Cases;
377 
378       GenerateCaseForVersionedClauses(Dir.getAllowedClauses(), OS,
379                                       Dir.getName(), DirLang, Cases);
380 
381       GenerateCaseForVersionedClauses(Dir.getAllowedOnceClauses(), OS,
382                                       Dir.getName(), DirLang, Cases);
383 
384       GenerateCaseForVersionedClauses(Dir.getAllowedExclusiveClauses(), OS,
385                                       Dir.getName(), DirLang, Cases);
386 
387       GenerateCaseForVersionedClauses(Dir.getRequiredClauses(), OS,
388                                       Dir.getName(), DirLang, Cases);
389 
390       OS << "        default:\n";
391       OS << "          return false;\n";
392       OS << "      }\n"; // End of clauses switch
393     }
394     OS << "      break;\n";
395   }
396 
397   OS << "  }\n"; // End of directives switch
398   OS << "  llvm_unreachable(\"Invalid " << DirLang.getName()
399      << " Directive kind\");\n";
400   OS << "}\n"; // End of function isAllowedClauseForDirective
401 }
402 
403 // Generate a simple enum set with the give clauses.
404 void GenerateClauseSet(const std::vector<Record *> &Clauses, raw_ostream &OS,
405                        StringRef ClauseSetPrefix, Directive &Dir,
406                        DirectiveLanguage &DirLang) {
407 
408   OS << "\n";
409   OS << "  static " << DirLang.getClauseEnumSetClass() << " " << ClauseSetPrefix
410      << DirLang.getDirectivePrefix() << Dir.getFormattedName() << " {\n";
411 
412   for (const auto &C : Clauses) {
413     VersionedClause VerClause{C};
414     OS << "    llvm::" << DirLang.getCppNamespace()
415        << "::Clause::" << DirLang.getClausePrefix()
416        << VerClause.getClause().getFormattedName() << ",\n";
417   }
418   OS << "  };\n";
419 }
420 
421 // Generate an enum set for the 4 kinds of clauses linked to a directive.
422 void GenerateDirectiveClauseSets(const std::vector<Record *> &Directives,
423                                  raw_ostream &OS, DirectiveLanguage &DirLang) {
424 
425   IfDefScope Scope("GEN_FLANG_DIRECTIVE_CLAUSE_SETS", OS);
426 
427   OS << "\n";
428   OS << "namespace llvm {\n";
429 
430   // Open namespaces defined in the directive language.
431   llvm::SmallVector<StringRef, 2> Namespaces;
432   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
433   for (auto Ns : Namespaces)
434     OS << "namespace " << Ns << " {\n";
435 
436   for (const auto &D : Directives) {
437     Directive Dir{D};
438 
439     OS << "\n";
440     OS << "  // Sets for " << Dir.getName() << "\n";
441 
442     GenerateClauseSet(Dir.getAllowedClauses(), OS, "allowedClauses_", Dir,
443                       DirLang);
444     GenerateClauseSet(Dir.getAllowedOnceClauses(), OS, "allowedOnceClauses_",
445                       Dir, DirLang);
446     GenerateClauseSet(Dir.getAllowedExclusiveClauses(), OS,
447                       "allowedExclusiveClauses_", Dir, DirLang);
448     GenerateClauseSet(Dir.getRequiredClauses(), OS, "requiredClauses_", Dir,
449                       DirLang);
450   }
451 
452   // Closing namespaces
453   for (auto Ns : llvm::reverse(Namespaces))
454     OS << "} // namespace " << Ns << "\n";
455 
456   OS << "} // namespace llvm\n";
457 }
458 
459 // Generate a map of directive (key) with DirectiveClauses struct as values.
460 // The struct holds the 4 sets of enumeration for the 4 kinds of clauses
461 // allowances (allowed, allowed once, allowed exclusive and required).
462 void GenerateDirectiveClauseMap(const std::vector<Record *> &Directives,
463                                 raw_ostream &OS, DirectiveLanguage &DirLang) {
464 
465   IfDefScope Scope("GEN_FLANG_DIRECTIVE_CLAUSE_MAP", OS);
466 
467   OS << "\n";
468   OS << "struct " << DirLang.getName() << "DirectiveClauses {\n";
469   OS << "  const " << DirLang.getClauseEnumSetClass() << " allowed;\n";
470   OS << "  const " << DirLang.getClauseEnumSetClass() << " allowedOnce;\n";
471   OS << "  const " << DirLang.getClauseEnumSetClass() << " allowedExclusive;\n";
472   OS << "  const " << DirLang.getClauseEnumSetClass() << " requiredOneOf;\n";
473   OS << "};\n";
474 
475   OS << "\n";
476 
477   OS << "std::unordered_map<llvm::" << DirLang.getCppNamespace()
478      << "::Directive, " << DirLang.getName() << "DirectiveClauses>\n";
479   OS << "    directiveClausesTable = {\n";
480 
481   for (const auto &D : Directives) {
482     Directive Dir{D};
483     OS << "  {llvm::" << DirLang.getCppNamespace()
484        << "::Directive::" << DirLang.getDirectivePrefix()
485        << Dir.getFormattedName() << ",\n";
486     OS << "    {\n";
487     OS << "      llvm::" << DirLang.getCppNamespace() << "::allowedClauses_"
488        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
489     OS << "      llvm::" << DirLang.getCppNamespace() << "::allowedOnceClauses_"
490        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
491     OS << "      llvm::" << DirLang.getCppNamespace()
492        << "::allowedExclusiveClauses_" << DirLang.getDirectivePrefix()
493        << Dir.getFormattedName() << ",\n";
494     OS << "      llvm::" << DirLang.getCppNamespace() << "::requiredClauses_"
495        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
496     OS << "    }\n";
497     OS << "  },\n";
498   }
499 
500   OS << "};\n";
501 }
502 
503 // Generate the implemenation section for the enumeration in the directive
504 // language
505 void EmitDirectivesFlangImpl(const std::vector<Record *> &Directives,
506                              raw_ostream &OS,
507                              DirectiveLanguage &DirectiveLanguage) {
508 
509   GenerateDirectiveClauseSets(Directives, OS, DirectiveLanguage);
510 
511   GenerateDirectiveClauseMap(Directives, OS, DirectiveLanguage);
512 }
513 
514 // Generate the implemenation section for the enumeration in the directive
515 // language.
516 void EmitDirectivesGen(RecordKeeper &Records, raw_ostream &OS) {
517 
518   const auto &DirectiveLanguages =
519       Records.getAllDerivedDefinitions("DirectiveLanguage");
520 
521   if (DirectiveLanguages.size() != 1) {
522     PrintError("A single definition of DirectiveLanguage is needed.");
523     return;
524   }
525 
526   const auto &Directives = Records.getAllDerivedDefinitions("Directive");
527   DirectiveLanguage DirectiveLanguage{DirectiveLanguages[0]};
528   EmitDirectivesFlangImpl(Directives, OS, DirectiveLanguage);
529 }
530 
531 // Generate the implemenation for the enumeration in the directive
532 // language. This code can be included in library.
533 void EmitDirectivesImpl(RecordKeeper &Records, raw_ostream &OS) {
534 
535   const auto &DirectiveLanguages =
536       Records.getAllDerivedDefinitions("DirectiveLanguage");
537 
538   if (DirectiveLanguages.size() != 1) {
539     PrintError("A single definition of DirectiveLanguage is needed.");
540     return;
541   }
542 
543   const auto &Directives = Records.getAllDerivedDefinitions("Directive");
544 
545   DirectiveLanguage DirLang = DirectiveLanguage{DirectiveLanguages[0]};
546 
547   const auto &Clauses = Records.getAllDerivedDefinitions("Clause");
548 
549   if (!DirLang.getIncludeHeader().empty())
550     OS << "#include \"" << DirLang.getIncludeHeader() << "\"\n\n";
551 
552   OS << "#include \"llvm/ADT/StringRef.h\"\n";
553   OS << "#include \"llvm/ADT/StringSwitch.h\"\n";
554   OS << "#include \"llvm/Support/ErrorHandling.h\"\n";
555   OS << "\n";
556   OS << "using namespace llvm;\n";
557   llvm::SmallVector<StringRef, 2> Namespaces;
558   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
559   for (auto Ns : Namespaces)
560     OS << "using namespace " << Ns << ";\n";
561 
562   // getDirectiveKind(StringRef Str)
563   GenerateGetKind(Directives, OS, "Directive", DirLang,
564                   DirLang.getDirectivePrefix(), /*ImplicitAsUnknown=*/false);
565 
566   // getDirectiveName(Directive Kind)
567   GenerateGetName(Directives, OS, "Directive", DirLang,
568                   DirLang.getDirectivePrefix());
569 
570   // getClauseKind(StringRef Str)
571   GenerateGetKind(Clauses, OS, "Clause", DirLang, DirLang.getClausePrefix(),
572                   /*ImplicitAsUnknown=*/true);
573 
574   // getClauseName(Clause Kind)
575   GenerateGetName(Clauses, OS, "Clause", DirLang, DirLang.getClausePrefix());
576 
577   // isAllowedClauseForDirective(Directive D, Clause C, unsigned Version)
578   GenerateIsAllowedClause(Directives, OS, DirLang);
579 }
580 
581 } // namespace llvm
582