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 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallVector.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:
IfDefScope(StringRef Name,raw_ostream & OS)28   IfDefScope(StringRef Name, raw_ostream &OS) : Name(Name), OS(OS) {
29     OS << "#ifdef " << Name << "\n"
30        << "#undef " << Name << "\n";
31   }
32 
~IfDefScope()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 // Generate enum class
GenerateEnumClass(const std::vector<Record * > & Records,raw_ostream & OS,StringRef Enum,StringRef Prefix,const DirectiveLanguage & DirLang)44 void GenerateEnumClass(const std::vector<Record *> &Records, raw_ostream &OS,
45                        StringRef Enum, StringRef Prefix,
46                        const DirectiveLanguage &DirLang) {
47   OS << "\n";
48   OS << "enum class " << Enum << " {\n";
49   for (const auto &R : Records) {
50     BaseRecord Rec{R};
51     OS << "  " << Prefix << Rec.getFormattedName() << ",\n";
52   }
53   OS << "};\n";
54   OS << "\n";
55   OS << "static constexpr std::size_t " << Enum
56      << "_enumSize = " << Records.size() << ";\n";
57 
58   // Make the enum values available in the defined namespace. This allows us to
59   // write something like Enum_X if we have a `using namespace <CppNamespace>`.
60   // At the same time we do not loose the strong type guarantees of the enum
61   // class, that is we cannot pass an unsigned as Directive without an explicit
62   // cast.
63   if (DirLang.hasMakeEnumAvailableInNamespace()) {
64     OS << "\n";
65     for (const auto &R : Records) {
66       BaseRecord Rec{R};
67       OS << "constexpr auto " << Prefix << Rec.getFormattedName() << " = "
68          << "llvm::" << DirLang.getCppNamespace() << "::" << Enum
69          << "::" << Prefix << Rec.getFormattedName() << ";\n";
70     }
71   }
72 }
73 
74 // Generate enums for values that clauses can take.
75 // Also generate function declarations for get<Enum>Name(StringRef Str).
GenerateEnumClauseVal(const std::vector<Record * > & Records,raw_ostream & OS,const DirectiveLanguage & DirLang,std::string & EnumHelperFuncs)76 void GenerateEnumClauseVal(const std::vector<Record *> &Records,
77                            raw_ostream &OS, const DirectiveLanguage &DirLang,
78                            std::string &EnumHelperFuncs) {
79   for (const auto &R : Records) {
80     Clause C{R};
81     const auto &ClauseVals = C.getClauseVals();
82     if (ClauseVals.size() <= 0)
83       continue;
84 
85     const auto &EnumName = C.getEnumName();
86     if (EnumName.size() == 0) {
87       PrintError("enumClauseValue field not set in Clause" +
88                  C.getFormattedName() + ".");
89       return;
90     }
91 
92     OS << "\n";
93     OS << "enum class " << EnumName << " {\n";
94     for (const auto &CV : ClauseVals) {
95       ClauseVal CVal{CV};
96       OS << "  " << CV->getName() << "=" << CVal.getValue() << ",\n";
97     }
98     OS << "};\n";
99 
100     if (DirLang.hasMakeEnumAvailableInNamespace()) {
101       OS << "\n";
102       for (const auto &CV : ClauseVals) {
103         OS << "constexpr auto " << CV->getName() << " = "
104            << "llvm::" << DirLang.getCppNamespace() << "::" << EnumName
105            << "::" << CV->getName() << ";\n";
106       }
107       EnumHelperFuncs += (llvm::Twine(EnumName) + llvm::Twine(" get") +
108                           llvm::Twine(EnumName) + llvm::Twine("(StringRef);\n"))
109                              .str();
110     }
111   }
112 }
113 
HasDuplicateClauses(const std::vector<Record * > & Clauses,const Directive & Directive,llvm::StringSet<> & CrtClauses)114 bool HasDuplicateClauses(const std::vector<Record *> &Clauses,
115                          const Directive &Directive,
116                          llvm::StringSet<> &CrtClauses) {
117   bool HasError = false;
118   for (const auto &C : Clauses) {
119     VersionedClause VerClause{C};
120     const auto insRes = CrtClauses.insert(VerClause.getClause().getName());
121     if (!insRes.second) {
122       PrintError("Clause " + VerClause.getClause().getRecordName() +
123                  " already defined on directive " + Directive.getRecordName());
124       HasError = true;
125     }
126   }
127   return HasError;
128 }
129 
130 // Check for duplicate clauses in lists. Clauses cannot appear twice in the
131 // three allowed list. Also, since required implies allowed, clauses cannot
132 // appear in both the allowedClauses and requiredClauses lists.
HasDuplicateClausesInDirectives(const std::vector<Record * > & Directives)133 bool HasDuplicateClausesInDirectives(const std::vector<Record *> &Directives) {
134   bool HasDuplicate = false;
135   for (const auto &D : Directives) {
136     Directive Dir{D};
137     llvm::StringSet<> Clauses;
138     // Check for duplicates in the three allowed lists.
139     if (HasDuplicateClauses(Dir.getAllowedClauses(), Dir, Clauses) ||
140         HasDuplicateClauses(Dir.getAllowedOnceClauses(), Dir, Clauses) ||
141         HasDuplicateClauses(Dir.getAllowedExclusiveClauses(), Dir, Clauses)) {
142       HasDuplicate = true;
143     }
144     // Check for duplicate between allowedClauses and required
145     Clauses.clear();
146     if (HasDuplicateClauses(Dir.getAllowedClauses(), Dir, Clauses) ||
147         HasDuplicateClauses(Dir.getRequiredClauses(), Dir, Clauses)) {
148       HasDuplicate = true;
149     }
150     if (HasDuplicate)
151       PrintFatalError("One or more clauses are defined multiple times on"
152                       " directive " +
153                       Dir.getRecordName());
154   }
155 
156   return HasDuplicate;
157 }
158 
159 // Check consitency of records. Return true if an error has been detected.
160 // Return false if the records are valid.
HasValidityErrors() const161 bool DirectiveLanguage::HasValidityErrors() const {
162   if (getDirectiveLanguages().size() != 1) {
163     PrintFatalError("A single definition of DirectiveLanguage is needed.");
164     return true;
165   }
166 
167   return HasDuplicateClausesInDirectives(getDirectives());
168 }
169 
170 // Generate the declaration section for the enumeration in the directive
171 // language
EmitDirectivesDecl(RecordKeeper & Records,raw_ostream & OS)172 void EmitDirectivesDecl(RecordKeeper &Records, raw_ostream &OS) {
173   const auto DirLang = DirectiveLanguage{Records};
174   if (DirLang.HasValidityErrors())
175     return;
176 
177   OS << "#ifndef LLVM_" << DirLang.getName() << "_INC\n";
178   OS << "#define LLVM_" << DirLang.getName() << "_INC\n";
179 
180   if (DirLang.hasEnableBitmaskEnumInNamespace())
181     OS << "\n#include \"llvm/ADT/BitmaskEnum.h\"\n";
182 
183   OS << "\n";
184   OS << "namespace llvm {\n";
185   OS << "class StringRef;\n";
186 
187   // Open namespaces defined in the directive language
188   llvm::SmallVector<StringRef, 2> Namespaces;
189   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
190   for (auto Ns : Namespaces)
191     OS << "namespace " << Ns << " {\n";
192 
193   if (DirLang.hasEnableBitmaskEnumInNamespace())
194     OS << "\nLLVM_ENABLE_BITMASK_ENUMS_IN_NAMESPACE();\n";
195 
196   // Emit Directive enumeration
197   GenerateEnumClass(DirLang.getDirectives(), OS, "Directive",
198                     DirLang.getDirectivePrefix(), DirLang);
199 
200   // Emit Clause enumeration
201   GenerateEnumClass(DirLang.getClauses(), OS, "Clause",
202                     DirLang.getClausePrefix(), DirLang);
203 
204   // Emit ClauseVal enumeration
205   std::string EnumHelperFuncs;
206   GenerateEnumClauseVal(DirLang.getClauses(), OS, DirLang, EnumHelperFuncs);
207 
208   // Generic function signatures
209   OS << "\n";
210   OS << "// Enumeration helper functions\n";
211   OS << "Directive get" << DirLang.getName()
212      << "DirectiveKind(llvm::StringRef Str);\n";
213   OS << "\n";
214   OS << "llvm::StringRef get" << DirLang.getName()
215      << "DirectiveName(Directive D);\n";
216   OS << "\n";
217   OS << "Clause get" << DirLang.getName()
218      << "ClauseKind(llvm::StringRef Str);\n";
219   OS << "\n";
220   OS << "llvm::StringRef get" << DirLang.getName() << "ClauseName(Clause C);\n";
221   OS << "\n";
222   OS << "/// Return true if \\p C is a valid clause for \\p D in version \\p "
223      << "Version.\n";
224   OS << "bool isAllowedClauseForDirective(Directive D, "
225      << "Clause C, unsigned Version);\n";
226   OS << "\n";
227   if (EnumHelperFuncs.length() > 0) {
228     OS << EnumHelperFuncs;
229     OS << "\n";
230   }
231 
232   // Closing namespaces
233   for (auto Ns : llvm::reverse(Namespaces))
234     OS << "} // namespace " << Ns << "\n";
235 
236   OS << "} // namespace llvm\n";
237 
238   OS << "#endif // LLVM_" << DirLang.getName() << "_INC\n";
239 }
240 
241 // Generate function implementation for get<Enum>Name(StringRef Str)
GenerateGetName(const std::vector<Record * > & Records,raw_ostream & OS,StringRef Enum,const DirectiveLanguage & DirLang,StringRef Prefix)242 void GenerateGetName(const std::vector<Record *> &Records, raw_ostream &OS,
243                      StringRef Enum, const DirectiveLanguage &DirLang,
244                      StringRef Prefix) {
245   OS << "\n";
246   OS << "llvm::StringRef llvm::" << DirLang.getCppNamespace() << "::get"
247      << DirLang.getName() << Enum << "Name(" << Enum << " Kind) {\n";
248   OS << "  switch (Kind) {\n";
249   for (const auto &R : Records) {
250     BaseRecord Rec{R};
251     OS << "    case " << Prefix << Rec.getFormattedName() << ":\n";
252     OS << "      return \"";
253     if (Rec.getAlternativeName().empty())
254       OS << Rec.getName();
255     else
256       OS << Rec.getAlternativeName();
257     OS << "\";\n";
258   }
259   OS << "  }\n"; // switch
260   OS << "  llvm_unreachable(\"Invalid " << DirLang.getName() << " " << Enum
261      << " kind\");\n";
262   OS << "}\n";
263 }
264 
265 // Generate function implementation for get<Enum>Kind(StringRef Str)
GenerateGetKind(const std::vector<Record * > & Records,raw_ostream & OS,StringRef Enum,const DirectiveLanguage & DirLang,StringRef Prefix,bool ImplicitAsUnknown)266 void GenerateGetKind(const std::vector<Record *> &Records, raw_ostream &OS,
267                      StringRef Enum, const DirectiveLanguage &DirLang,
268                      StringRef Prefix, bool ImplicitAsUnknown) {
269 
270   auto DefaultIt = std::find_if(Records.begin(), Records.end(), [](Record *R) {
271     return R->getValueAsBit("isDefault") == true;
272   });
273 
274   if (DefaultIt == Records.end()) {
275     PrintError("At least one " + Enum + " must be defined as default.");
276     return;
277   }
278 
279   BaseRecord DefaultRec{(*DefaultIt)};
280 
281   OS << "\n";
282   OS << Enum << " llvm::" << DirLang.getCppNamespace() << "::get"
283      << DirLang.getName() << Enum << "Kind(llvm::StringRef Str) {\n";
284   OS << "  return llvm::StringSwitch<" << Enum << ">(Str)\n";
285 
286   for (const auto &R : Records) {
287     BaseRecord Rec{R};
288     if (ImplicitAsUnknown && R->getValueAsBit("isImplicit")) {
289       OS << "    .Case(\"" << Rec.getName() << "\"," << Prefix
290          << DefaultRec.getFormattedName() << ")\n";
291     } else {
292       OS << "    .Case(\"" << Rec.getName() << "\"," << Prefix
293          << Rec.getFormattedName() << ")\n";
294     }
295   }
296   OS << "    .Default(" << Prefix << DefaultRec.getFormattedName() << ");\n";
297   OS << "}\n";
298 }
299 
300 // Generate function implementation for get<ClauseVal>Kind(StringRef Str)
GenerateGetKindClauseVal(const DirectiveLanguage & DirLang,raw_ostream & OS)301 void GenerateGetKindClauseVal(const DirectiveLanguage &DirLang,
302                               raw_ostream &OS) {
303   for (const auto &R : DirLang.getClauses()) {
304     Clause C{R};
305     const auto &ClauseVals = C.getClauseVals();
306     if (ClauseVals.size() <= 0)
307       continue;
308 
309     auto DefaultIt =
310         std::find_if(ClauseVals.begin(), ClauseVals.end(), [](Record *CV) {
311           return CV->getValueAsBit("isDefault") == true;
312         });
313 
314     if (DefaultIt == ClauseVals.end()) {
315       PrintError("At least one val in Clause " + C.getFormattedName() +
316                  " must be defined as default.");
317       return;
318     }
319     const auto DefaultName = (*DefaultIt)->getName();
320 
321     const auto &EnumName = C.getEnumName();
322     if (EnumName.size() == 0) {
323       PrintError("enumClauseValue field not set in Clause" +
324                  C.getFormattedName() + ".");
325       return;
326     }
327 
328     OS << "\n";
329     OS << EnumName << " llvm::" << DirLang.getCppNamespace() << "::get"
330        << EnumName << "(llvm::StringRef Str) {\n";
331     OS << "  return llvm::StringSwitch<" << EnumName << ">(Str)\n";
332     for (const auto &CV : ClauseVals) {
333       ClauseVal CVal{CV};
334       OS << "    .Case(\"" << CVal.getFormattedName() << "\"," << CV->getName()
335          << ")\n";
336     }
337     OS << "    .Default(" << DefaultName << ");\n";
338     OS << "}\n";
339   }
340 }
341 
GenerateCaseForVersionedClauses(const std::vector<Record * > & Clauses,raw_ostream & OS,StringRef DirectiveName,const DirectiveLanguage & DirLang,llvm::StringSet<> & Cases)342 void GenerateCaseForVersionedClauses(const std::vector<Record *> &Clauses,
343                                      raw_ostream &OS, StringRef DirectiveName,
344                                      const DirectiveLanguage &DirLang,
345                                      llvm::StringSet<> &Cases) {
346   for (const auto &C : Clauses) {
347     VersionedClause VerClause{C};
348 
349     const auto ClauseFormattedName = VerClause.getClause().getFormattedName();
350 
351     if (Cases.find(ClauseFormattedName) == Cases.end()) {
352       Cases.insert(ClauseFormattedName);
353       OS << "        case " << DirLang.getClausePrefix() << ClauseFormattedName
354          << ":\n";
355       OS << "          return " << VerClause.getMinVersion()
356          << " <= Version && " << VerClause.getMaxVersion() << " >= Version;\n";
357     }
358   }
359 }
360 
361 // Generate the isAllowedClauseForDirective function implementation.
GenerateIsAllowedClause(const DirectiveLanguage & DirLang,raw_ostream & OS)362 void GenerateIsAllowedClause(const DirectiveLanguage &DirLang,
363                              raw_ostream &OS) {
364   OS << "\n";
365   OS << "bool llvm::" << DirLang.getCppNamespace()
366      << "::isAllowedClauseForDirective("
367      << "Directive D, Clause C, unsigned Version) {\n";
368   OS << "  assert(unsigned(D) <= llvm::" << DirLang.getCppNamespace()
369      << "::Directive_enumSize);\n";
370   OS << "  assert(unsigned(C) <= llvm::" << DirLang.getCppNamespace()
371      << "::Clause_enumSize);\n";
372 
373   OS << "  switch (D) {\n";
374 
375   for (const auto &D : DirLang.getDirectives()) {
376     Directive Dir{D};
377 
378     OS << "    case " << DirLang.getDirectivePrefix() << Dir.getFormattedName()
379        << ":\n";
380     if (Dir.getAllowedClauses().size() == 0 &&
381         Dir.getAllowedOnceClauses().size() == 0 &&
382         Dir.getAllowedExclusiveClauses().size() == 0 &&
383         Dir.getRequiredClauses().size() == 0) {
384       OS << "      return false;\n";
385     } else {
386       OS << "      switch (C) {\n";
387 
388       llvm::StringSet<> Cases;
389 
390       GenerateCaseForVersionedClauses(Dir.getAllowedClauses(), OS,
391                                       Dir.getName(), DirLang, Cases);
392 
393       GenerateCaseForVersionedClauses(Dir.getAllowedOnceClauses(), OS,
394                                       Dir.getName(), DirLang, Cases);
395 
396       GenerateCaseForVersionedClauses(Dir.getAllowedExclusiveClauses(), OS,
397                                       Dir.getName(), DirLang, Cases);
398 
399       GenerateCaseForVersionedClauses(Dir.getRequiredClauses(), OS,
400                                       Dir.getName(), DirLang, Cases);
401 
402       OS << "        default:\n";
403       OS << "          return false;\n";
404       OS << "      }\n"; // End of clauses switch
405     }
406     OS << "      break;\n";
407   }
408 
409   OS << "  }\n"; // End of directives switch
410   OS << "  llvm_unreachable(\"Invalid " << DirLang.getName()
411      << " Directive kind\");\n";
412   OS << "}\n"; // End of function isAllowedClauseForDirective
413 }
414 
415 // Generate a simple enum set with the give clauses.
GenerateClauseSet(const std::vector<Record * > & Clauses,raw_ostream & OS,StringRef ClauseSetPrefix,Directive & Dir,const DirectiveLanguage & DirLang)416 void GenerateClauseSet(const std::vector<Record *> &Clauses, raw_ostream &OS,
417                        StringRef ClauseSetPrefix, Directive &Dir,
418                        const DirectiveLanguage &DirLang) {
419 
420   OS << "\n";
421   OS << "  static " << DirLang.getClauseEnumSetClass() << " " << ClauseSetPrefix
422      << DirLang.getDirectivePrefix() << Dir.getFormattedName() << " {\n";
423 
424   for (const auto &C : Clauses) {
425     VersionedClause VerClause{C};
426     OS << "    llvm::" << DirLang.getCppNamespace()
427        << "::Clause::" << DirLang.getClausePrefix()
428        << VerClause.getClause().getFormattedName() << ",\n";
429   }
430   OS << "  };\n";
431 }
432 
433 // Generate an enum set for the 4 kinds of clauses linked to a directive.
GenerateDirectiveClauseSets(const DirectiveLanguage & DirLang,raw_ostream & OS)434 void GenerateDirectiveClauseSets(const DirectiveLanguage &DirLang,
435                                  raw_ostream &OS) {
436 
437   IfDefScope Scope("GEN_FLANG_DIRECTIVE_CLAUSE_SETS", OS);
438 
439   OS << "\n";
440   OS << "namespace llvm {\n";
441 
442   // Open namespaces defined in the directive language.
443   llvm::SmallVector<StringRef, 2> Namespaces;
444   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
445   for (auto Ns : Namespaces)
446     OS << "namespace " << Ns << " {\n";
447 
448   for (const auto &D : DirLang.getDirectives()) {
449     Directive Dir{D};
450 
451     OS << "\n";
452     OS << "  // Sets for " << Dir.getName() << "\n";
453 
454     GenerateClauseSet(Dir.getAllowedClauses(), OS, "allowedClauses_", Dir,
455                       DirLang);
456     GenerateClauseSet(Dir.getAllowedOnceClauses(), OS, "allowedOnceClauses_",
457                       Dir, DirLang);
458     GenerateClauseSet(Dir.getAllowedExclusiveClauses(), OS,
459                       "allowedExclusiveClauses_", Dir, DirLang);
460     GenerateClauseSet(Dir.getRequiredClauses(), OS, "requiredClauses_", Dir,
461                       DirLang);
462   }
463 
464   // Closing namespaces
465   for (auto Ns : llvm::reverse(Namespaces))
466     OS << "} // namespace " << Ns << "\n";
467 
468   OS << "} // namespace llvm\n";
469 }
470 
471 // Generate a map of directive (key) with DirectiveClauses struct as values.
472 // The struct holds the 4 sets of enumeration for the 4 kinds of clauses
473 // allowances (allowed, allowed once, allowed exclusive and required).
GenerateDirectiveClauseMap(const DirectiveLanguage & DirLang,raw_ostream & OS)474 void GenerateDirectiveClauseMap(const DirectiveLanguage &DirLang,
475                                 raw_ostream &OS) {
476 
477   IfDefScope Scope("GEN_FLANG_DIRECTIVE_CLAUSE_MAP", OS);
478 
479   OS << "\n";
480   OS << "{\n";
481 
482   for (const auto &D : DirLang.getDirectives()) {
483     Directive Dir{D};
484     OS << "  {llvm::" << DirLang.getCppNamespace()
485        << "::Directive::" << DirLang.getDirectivePrefix()
486        << Dir.getFormattedName() << ",\n";
487     OS << "    {\n";
488     OS << "      llvm::" << DirLang.getCppNamespace() << "::allowedClauses_"
489        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
490     OS << "      llvm::" << DirLang.getCppNamespace() << "::allowedOnceClauses_"
491        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
492     OS << "      llvm::" << DirLang.getCppNamespace()
493        << "::allowedExclusiveClauses_" << DirLang.getDirectivePrefix()
494        << Dir.getFormattedName() << ",\n";
495     OS << "      llvm::" << DirLang.getCppNamespace() << "::requiredClauses_"
496        << DirLang.getDirectivePrefix() << Dir.getFormattedName() << ",\n";
497     OS << "    }\n";
498     OS << "  },\n";
499   }
500 
501   OS << "}\n";
502 }
503 
504 // Generate classes entry for Flang clauses in the Flang parse-tree
505 // If the clause as a non-generic class, no entry is generated.
506 // If the clause does not hold a value, an EMPTY_CLASS is used.
507 // If the clause class is generic then a WRAPPER_CLASS is used. When the value
508 // is optional, the value class is wrapped into a std::optional.
GenerateFlangClauseParserClass(const DirectiveLanguage & DirLang,raw_ostream & OS)509 void GenerateFlangClauseParserClass(const DirectiveLanguage &DirLang,
510                                     raw_ostream &OS) {
511 
512   IfDefScope Scope("GEN_FLANG_CLAUSE_PARSER_CLASSES", OS);
513 
514   OS << "\n";
515 
516   for (const auto &C : DirLang.getClauses()) {
517     Clause Clause{C};
518     // Clause has a non generic class.
519     if (!Clause.getFlangClass().empty())
520       continue;
521     if (!Clause.getFlangClassValue().empty()) {
522       OS << "WRAPPER_CLASS(" << Clause.getFormattedParserClassName() << ", ";
523       if (Clause.isValueOptional() && Clause.isValueList()) {
524         OS << "std::optional<std::list<" << Clause.getFlangClassValue()
525            << ">>";
526       } else if (Clause.isValueOptional()) {
527         OS << "std::optional<" << Clause.getFlangClassValue() << ">";
528       } else if (Clause.isValueList()) {
529         OS << "std::list<" << Clause.getFlangClassValue() << ">";
530       } else {
531         OS << Clause.getFlangClassValue();
532       }
533     } else {
534       OS << "EMPTY_CLASS(" << Clause.getFormattedParserClassName();
535     }
536     OS << ");\n";
537   }
538 }
539 
540 // Generate a list of the different clause classes for Flang.
GenerateFlangClauseParserClassList(const DirectiveLanguage & DirLang,raw_ostream & OS)541 void GenerateFlangClauseParserClassList(const DirectiveLanguage &DirLang,
542                                         raw_ostream &OS) {
543 
544   IfDefScope Scope("GEN_FLANG_CLAUSE_PARSER_CLASSES_LIST", OS);
545 
546   OS << "\n";
547   llvm::interleaveComma(DirLang.getClauses(), OS, [&](Record *C) {
548     Clause Clause{C};
549     if (Clause.getFlangClass().empty())
550       OS << Clause.getFormattedParserClassName() << "\n";
551     else
552       OS << Clause.getFlangClass() << "\n";
553   });
554 }
555 
556 // Generate dump node list for the clauses holding a generic class name.
GenerateFlangClauseDump(const DirectiveLanguage & DirLang,raw_ostream & OS)557 void GenerateFlangClauseDump(const DirectiveLanguage &DirLang,
558                              raw_ostream &OS) {
559 
560   IfDefScope Scope("GEN_FLANG_DUMP_PARSE_TREE_CLAUSES", OS);
561 
562   OS << "\n";
563   for (const auto &C : DirLang.getClauses()) {
564     Clause Clause{C};
565     // Clause has a non generic class.
566     if (!Clause.getFlangClass().empty())
567       continue;
568 
569     OS << "NODE(" << DirLang.getFlangClauseBaseClass() << ", "
570        << Clause.getFormattedParserClassName() << ")\n";
571   }
572 }
573 
574 // Generate Unparse functions for clauses classes in the Flang parse-tree
575 // If the clause is a non-generic class, no entry is generated.
GenerateFlangClauseUnparse(const DirectiveLanguage & DirLang,raw_ostream & OS)576 void GenerateFlangClauseUnparse(const DirectiveLanguage &DirLang,
577                                 raw_ostream &OS) {
578 
579   IfDefScope Scope("GEN_FLANG_CLAUSE_UNPARSE", OS);
580 
581   OS << "\n";
582 
583   for (const auto &C : DirLang.getClauses()) {
584     Clause Clause{C};
585     // Clause has a non generic class.
586     if (!Clause.getFlangClass().empty())
587       continue;
588     if (!Clause.getFlangClassValue().empty()) {
589       if (Clause.isValueOptional() && Clause.getDefaultValue().empty()) {
590         OS << "void Unparse(const " << DirLang.getFlangClauseBaseClass()
591            << "::" << Clause.getFormattedParserClassName() << " &x) {\n";
592         OS << "  Word(\"" << Clause.getName().upper() << "\");\n";
593 
594         OS << "  Walk(\"(\", x.v, \")\");\n";
595         OS << "}\n";
596       } else if (Clause.isValueOptional()) {
597         OS << "void Unparse(const " << DirLang.getFlangClauseBaseClass()
598            << "::" << Clause.getFormattedParserClassName() << " &x) {\n";
599         OS << "  Word(\"" << Clause.getName().upper() << "\");\n";
600         OS << "  Put(\"(\");\n";
601         OS << "  if (x.v.has_value())\n";
602         if (Clause.isValueList())
603           OS << "    Walk(x.v, \",\");\n";
604         else
605           OS << "    Walk(x.v);\n";
606         OS << "  else\n";
607         OS << "    Put(\"" << Clause.getDefaultValue() << "\");\n";
608         OS << "  Put(\")\");\n";
609         OS << "}\n";
610       } else {
611         OS << "void Unparse(const " << DirLang.getFlangClauseBaseClass()
612            << "::" << Clause.getFormattedParserClassName() << " &x) {\n";
613         OS << "  Word(\"" << Clause.getName().upper() << "\");\n";
614         OS << "  Put(\"(\");\n";
615         if (Clause.isValueList())
616           OS << "  Walk(x.v, \",\");\n";
617         else
618           OS << "  Walk(x.v);\n";
619         OS << "  Put(\")\");\n";
620         OS << "}\n";
621       }
622     } else {
623       OS << "void Before(const " << DirLang.getFlangClauseBaseClass()
624          << "::" << Clause.getFormattedParserClassName() << " &) { Word(\""
625          << Clause.getName().upper() << "\"); }\n";
626     }
627   }
628 }
629 
630 // Generate the implemenation section for the enumeration in the directive
631 // language
EmitDirectivesFlangImpl(const DirectiveLanguage & DirLang,raw_ostream & OS)632 void EmitDirectivesFlangImpl(const DirectiveLanguage &DirLang,
633                              raw_ostream &OS) {
634 
635   GenerateDirectiveClauseSets(DirLang, OS);
636 
637   GenerateDirectiveClauseMap(DirLang, OS);
638 
639   GenerateFlangClauseParserClass(DirLang, OS);
640 
641   GenerateFlangClauseParserClassList(DirLang, OS);
642 
643   GenerateFlangClauseDump(DirLang, OS);
644 
645   GenerateFlangClauseUnparse(DirLang, OS);
646 }
647 
648 // Generate the implemenation section for the enumeration in the directive
649 // language.
EmitDirectivesGen(RecordKeeper & Records,raw_ostream & OS)650 void EmitDirectivesGen(RecordKeeper &Records, raw_ostream &OS) {
651   const auto DirLang = DirectiveLanguage{Records};
652   if (DirLang.HasValidityErrors())
653     return;
654 
655   EmitDirectivesFlangImpl(DirLang, OS);
656 }
657 
658 // Generate the implemenation for the enumeration in the directive
659 // language. This code can be included in library.
EmitDirectivesImpl(RecordKeeper & Records,raw_ostream & OS)660 void EmitDirectivesImpl(RecordKeeper &Records, raw_ostream &OS) {
661   const auto DirLang = DirectiveLanguage{Records};
662   if (DirLang.HasValidityErrors())
663     return;
664 
665   if (!DirLang.getIncludeHeader().empty())
666     OS << "#include \"" << DirLang.getIncludeHeader() << "\"\n\n";
667 
668   OS << "#include \"llvm/ADT/StringRef.h\"\n";
669   OS << "#include \"llvm/ADT/StringSwitch.h\"\n";
670   OS << "#include \"llvm/Support/ErrorHandling.h\"\n";
671   OS << "\n";
672   OS << "using namespace llvm;\n";
673   llvm::SmallVector<StringRef, 2> Namespaces;
674   llvm::SplitString(DirLang.getCppNamespace(), Namespaces, "::");
675   for (auto Ns : Namespaces)
676     OS << "using namespace " << Ns << ";\n";
677 
678   // getDirectiveKind(StringRef Str)
679   GenerateGetKind(DirLang.getDirectives(), OS, "Directive", DirLang,
680                   DirLang.getDirectivePrefix(), /*ImplicitAsUnknown=*/false);
681 
682   // getDirectiveName(Directive Kind)
683   GenerateGetName(DirLang.getDirectives(), OS, "Directive", DirLang,
684                   DirLang.getDirectivePrefix());
685 
686   // getClauseKind(StringRef Str)
687   GenerateGetKind(DirLang.getClauses(), OS, "Clause", DirLang,
688                   DirLang.getClausePrefix(),
689                   /*ImplicitAsUnknown=*/true);
690 
691   // getClauseName(Clause Kind)
692   GenerateGetName(DirLang.getClauses(), OS, "Clause", DirLang,
693                   DirLang.getClausePrefix());
694 
695   // get<ClauseVal>Kind(StringRef Str)
696   GenerateGetKindClauseVal(DirLang, OS);
697 
698   // isAllowedClauseForDirective(Directive D, Clause C, unsigned Version)
699   GenerateIsAllowedClause(DirLang, OS);
700 }
701 
702 } // namespace llvm
703