xref: /freebsd/contrib/llvm-project/clang/utils/TableGen/ClangAttrEmitter.cpp (revision 1db9f3b21e39176dd5b67cf8ac378633b172463e)
1 //===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
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 // These tablegen backends emit Clang attribute processing code
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TableGenBackends.h"
14 #include "ASTTableGen.h"
15 
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSet.h"
25 #include "llvm/ADT/StringSwitch.h"
26 #include "llvm/ADT/iterator_range.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include "llvm/TableGen/Error.h"
30 #include "llvm/TableGen/Record.h"
31 #include "llvm/TableGen/StringMatcher.h"
32 #include "llvm/TableGen/TableGenBackend.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <cctype>
36 #include <cstddef>
37 #include <cstdint>
38 #include <map>
39 #include <memory>
40 #include <optional>
41 #include <set>
42 #include <sstream>
43 #include <string>
44 #include <utility>
45 #include <vector>
46 
47 using namespace llvm;
48 
49 namespace {
50 
51 class FlattenedSpelling {
52   std::string V, N, NS;
53   bool K = false;
54   const Record &OriginalSpelling;
55 
56 public:
57   FlattenedSpelling(const std::string &Variety, const std::string &Name,
58                     const std::string &Namespace, bool KnownToGCC,
59                     const Record &OriginalSpelling)
60       : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
61         OriginalSpelling(OriginalSpelling) {}
62   explicit FlattenedSpelling(const Record &Spelling)
63       : V(std::string(Spelling.getValueAsString("Variety"))),
64         N(std::string(Spelling.getValueAsString("Name"))),
65         OriginalSpelling(Spelling) {
66     assert(V != "GCC" && V != "Clang" &&
67            "Given a GCC spelling, which means this hasn't been flattened!");
68     if (V == "CXX11" || V == "C23" || V == "Pragma")
69       NS = std::string(Spelling.getValueAsString("Namespace"));
70   }
71 
72   const std::string &variety() const { return V; }
73   const std::string &name() const { return N; }
74   const std::string &nameSpace() const { return NS; }
75   bool knownToGCC() const { return K; }
76   const Record &getSpellingRecord() const { return OriginalSpelling; }
77 };
78 
79 } // end anonymous namespace
80 
81 static std::vector<FlattenedSpelling>
82 GetFlattenedSpellings(const Record &Attr) {
83   std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
84   std::vector<FlattenedSpelling> Ret;
85 
86   for (const auto &Spelling : Spellings) {
87     StringRef Variety = Spelling->getValueAsString("Variety");
88     StringRef Name = Spelling->getValueAsString("Name");
89     if (Variety == "GCC") {
90       Ret.emplace_back("GNU", std::string(Name), "", true, *Spelling);
91       Ret.emplace_back("CXX11", std::string(Name), "gnu", true, *Spelling);
92       if (Spelling->getValueAsBit("AllowInC"))
93         Ret.emplace_back("C23", std::string(Name), "gnu", true, *Spelling);
94     } else if (Variety == "Clang") {
95       Ret.emplace_back("GNU", std::string(Name), "", false, *Spelling);
96       Ret.emplace_back("CXX11", std::string(Name), "clang", false, *Spelling);
97       if (Spelling->getValueAsBit("AllowInC"))
98         Ret.emplace_back("C23", std::string(Name), "clang", false, *Spelling);
99     } else
100       Ret.push_back(FlattenedSpelling(*Spelling));
101   }
102 
103   return Ret;
104 }
105 
106 static std::string ReadPCHRecord(StringRef type) {
107   return StringSwitch<std::string>(type)
108       .EndsWith("Decl *", "Record.GetLocalDeclAs<" +
109                               std::string(type.data(), 0, type.size() - 1) +
110                               ">(Record.readInt())")
111       .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
112       .Case("Expr *", "Record.readExpr()")
113       .Case("IdentifierInfo *", "Record.readIdentifier()")
114       .Case("StringRef", "Record.readString()")
115       .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
116       .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
117       .Default("Record.readInt()");
118 }
119 
120 // Get a type that is suitable for storing an object of the specified type.
121 static StringRef getStorageType(StringRef type) {
122   return StringSwitch<StringRef>(type)
123     .Case("StringRef", "std::string")
124     .Default(type);
125 }
126 
127 // Assumes that the way to get the value is SA->getname()
128 static std::string WritePCHRecord(StringRef type, StringRef name) {
129   return "Record." +
130          StringSwitch<std::string>(type)
131              .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
132              .Case("TypeSourceInfo *",
133                    "AddTypeSourceInfo(" + std::string(name) + ");\n")
134              .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
135              .Case("IdentifierInfo *",
136                    "AddIdentifierRef(" + std::string(name) + ");\n")
137              .Case("StringRef", "AddString(" + std::string(name) + ");\n")
138              .Case("ParamIdx",
139                    "push_back(" + std::string(name) + ".serialize());\n")
140              .Case("OMPTraitInfo *",
141                    "writeOMPTraitInfo(" + std::string(name) + ");\n")
142              .Default("push_back(" + std::string(name) + ");\n");
143 }
144 
145 // Normalize attribute name by removing leading and trailing
146 // underscores. For example, __foo, foo__, __foo__ would
147 // become foo.
148 static StringRef NormalizeAttrName(StringRef AttrName) {
149   AttrName.consume_front("__");
150   AttrName.consume_back("__");
151   return AttrName;
152 }
153 
154 // Normalize the name by removing any and all leading and trailing underscores.
155 // This is different from NormalizeAttrName in that it also handles names like
156 // _pascal and __pascal.
157 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
158   return Name.trim("_");
159 }
160 
161 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
162 // removing "__" if it appears at the beginning and end of the attribute's name.
163 static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
164   if (AttrSpelling.starts_with("__") && AttrSpelling.ends_with("__")) {
165     AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
166   }
167 
168   return AttrSpelling;
169 }
170 
171 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
172 
173 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
174                                        ParsedAttrMap *Dupes = nullptr) {
175   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
176   std::set<std::string> Seen;
177   ParsedAttrMap R;
178   for (const auto *Attr : Attrs) {
179     if (Attr->getValueAsBit("SemaHandler")) {
180       std::string AN;
181       if (Attr->isSubClassOf("TargetSpecificAttr") &&
182           !Attr->isValueUnset("ParseKind")) {
183         AN = std::string(Attr->getValueAsString("ParseKind"));
184 
185         // If this attribute has already been handled, it does not need to be
186         // handled again.
187         if (Seen.find(AN) != Seen.end()) {
188           if (Dupes)
189             Dupes->push_back(std::make_pair(AN, Attr));
190           continue;
191         }
192         Seen.insert(AN);
193       } else
194         AN = NormalizeAttrName(Attr->getName()).str();
195 
196       R.push_back(std::make_pair(AN, Attr));
197     }
198   }
199   return R;
200 }
201 
202 namespace {
203 
204   class Argument {
205     std::string lowerName, upperName;
206     StringRef attrName;
207     bool isOpt;
208     bool Fake;
209 
210   public:
211     Argument(StringRef Arg, StringRef Attr)
212         : lowerName(std::string(Arg)), upperName(lowerName), attrName(Attr),
213           isOpt(false), Fake(false) {
214       if (!lowerName.empty()) {
215         lowerName[0] = std::tolower(lowerName[0]);
216         upperName[0] = std::toupper(upperName[0]);
217       }
218       // Work around MinGW's macro definition of 'interface' to 'struct'. We
219       // have an attribute argument called 'Interface', so only the lower case
220       // name conflicts with the macro definition.
221       if (lowerName == "interface")
222         lowerName = "interface_";
223     }
224     Argument(const Record &Arg, StringRef Attr)
225         : Argument(Arg.getValueAsString("Name"), Attr) {}
226     virtual ~Argument() = default;
227 
228     StringRef getLowerName() const { return lowerName; }
229     StringRef getUpperName() const { return upperName; }
230     StringRef getAttrName() const { return attrName; }
231 
232     bool isOptional() const { return isOpt; }
233     void setOptional(bool set) { isOpt = set; }
234 
235     bool isFake() const { return Fake; }
236     void setFake(bool fake) { Fake = fake; }
237 
238     // These functions print the argument contents formatted in different ways.
239     virtual void writeAccessors(raw_ostream &OS) const = 0;
240     virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
241     virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
242     virtual void writeCloneArgs(raw_ostream &OS) const = 0;
243     virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
244     virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
245     virtual void writeCtorBody(raw_ostream &OS) const {}
246     virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
247     virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
248     virtual void writeCtorParameters(raw_ostream &OS) const = 0;
249     virtual void writeDeclarations(raw_ostream &OS) const = 0;
250     virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
251     virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
252     virtual void writePCHWrite(raw_ostream &OS) const = 0;
253     virtual std::string getIsOmitted() const { return "false"; }
254     virtual void writeValue(raw_ostream &OS) const = 0;
255     virtual void writeDump(raw_ostream &OS) const = 0;
256     virtual void writeDumpChildren(raw_ostream &OS) const {}
257     virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
258 
259     virtual bool isEnumArg() const { return false; }
260     virtual bool isVariadicEnumArg() const { return false; }
261     virtual bool isVariadic() const { return false; }
262 
263     virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
264       OS << getUpperName();
265     }
266   };
267 
268   class SimpleArgument : public Argument {
269     std::string type;
270 
271   public:
272     SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
273         : Argument(Arg, Attr), type(std::move(T)) {}
274 
275     std::string getType() const { return type; }
276 
277     void writeAccessors(raw_ostream &OS) const override {
278       OS << "  " << type << " get" << getUpperName() << "() const {\n";
279       OS << "    return " << getLowerName() << ";\n";
280       OS << "  }";
281     }
282 
283     void writeCloneArgs(raw_ostream &OS) const override {
284       OS << getLowerName();
285     }
286 
287     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
288       OS << "A->get" << getUpperName() << "()";
289     }
290 
291     void writeCtorInitializers(raw_ostream &OS) const override {
292       OS << getLowerName() << "(" << getUpperName() << ")";
293     }
294 
295     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
296       OS << getLowerName() << "()";
297     }
298 
299     void writeCtorParameters(raw_ostream &OS) const override {
300       OS << type << " " << getUpperName();
301     }
302 
303     void writeDeclarations(raw_ostream &OS) const override {
304       OS << type << " " << getLowerName() << ";";
305     }
306 
307     void writePCHReadDecls(raw_ostream &OS) const override {
308       std::string read = ReadPCHRecord(type);
309       OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
310     }
311 
312     void writePCHReadArgs(raw_ostream &OS) const override {
313       OS << getLowerName();
314     }
315 
316     void writePCHWrite(raw_ostream &OS) const override {
317       OS << "    "
318          << WritePCHRecord(type,
319                            "SA->get" + std::string(getUpperName()) + "()");
320     }
321 
322     std::string getIsOmitted() const override {
323       auto IsOneOf = [](StringRef subject, auto... list) {
324         return ((subject == list) || ...);
325       };
326 
327       if (IsOneOf(type, "IdentifierInfo *", "Expr *"))
328         return "!get" + getUpperName().str() + "()";
329       if (IsOneOf(type, "TypeSourceInfo *"))
330         return "!get" + getUpperName().str() + "Loc()";
331       if (IsOneOf(type, "ParamIdx"))
332         return "!get" + getUpperName().str() + "().isValid()";
333 
334       assert(IsOneOf(type, "unsigned", "int", "bool", "FunctionDecl *",
335                      "VarDecl *"));
336       return "false";
337     }
338 
339     void writeValue(raw_ostream &OS) const override {
340       if (type == "FunctionDecl *")
341         OS << "\" << get" << getUpperName()
342            << "()->getNameInfo().getAsString() << \"";
343       else if (type == "IdentifierInfo *")
344         // Some non-optional (comma required) identifier arguments can be the
345         // empty string but are then recorded as a nullptr.
346         OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
347            << "()->getName() : \"\") << \"";
348       else if (type == "VarDecl *")
349         OS << "\" << get" << getUpperName() << "()->getName() << \"";
350       else if (type == "TypeSourceInfo *")
351         OS << "\" << get" << getUpperName() << "().getAsString() << \"";
352       else if (type == "ParamIdx")
353         OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
354       else
355         OS << "\" << get" << getUpperName() << "() << \"";
356     }
357 
358     void writeDump(raw_ostream &OS) const override {
359       if (StringRef(type).ends_with("Decl *")) {
360         OS << "    OS << \" \";\n";
361         OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
362       } else if (type == "IdentifierInfo *") {
363         // Some non-optional (comma required) identifier arguments can be the
364         // empty string but are then recorded as a nullptr.
365         OS << "    if (SA->get" << getUpperName() << "())\n"
366            << "      OS << \" \" << SA->get" << getUpperName()
367            << "()->getName();\n";
368       } else if (type == "TypeSourceInfo *") {
369         if (isOptional())
370           OS << "    if (SA->get" << getUpperName() << "Loc())";
371         OS << "    OS << \" \" << SA->get" << getUpperName()
372            << "().getAsString();\n";
373       } else if (type == "bool") {
374         OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
375            << getUpperName() << "\";\n";
376       } else if (type == "int" || type == "unsigned") {
377         OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
378       } else if (type == "ParamIdx") {
379         if (isOptional())
380           OS << "    if (SA->get" << getUpperName() << "().isValid())\n  ";
381         OS << "    OS << \" \" << SA->get" << getUpperName()
382            << "().getSourceIndex();\n";
383       } else if (type == "OMPTraitInfo *") {
384         OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
385       } else {
386         llvm_unreachable("Unknown SimpleArgument type!");
387       }
388     }
389   };
390 
391   class DefaultSimpleArgument : public SimpleArgument {
392     int64_t Default;
393 
394   public:
395     DefaultSimpleArgument(const Record &Arg, StringRef Attr,
396                           std::string T, int64_t Default)
397       : SimpleArgument(Arg, Attr, T), Default(Default) {}
398 
399     void writeAccessors(raw_ostream &OS) const override {
400       SimpleArgument::writeAccessors(OS);
401 
402       OS << "\n\n  static const " << getType() << " Default" << getUpperName()
403          << " = ";
404       if (getType() == "bool")
405         OS << (Default != 0 ? "true" : "false");
406       else
407         OS << Default;
408       OS << ";";
409     }
410   };
411 
412   class StringArgument : public Argument {
413   public:
414     StringArgument(const Record &Arg, StringRef Attr)
415       : Argument(Arg, Attr)
416     {}
417 
418     void writeAccessors(raw_ostream &OS) const override {
419       OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
420       OS << "    return llvm::StringRef(" << getLowerName() << ", "
421          << getLowerName() << "Length);\n";
422       OS << "  }\n";
423       OS << "  unsigned get" << getUpperName() << "Length() const {\n";
424       OS << "    return " << getLowerName() << "Length;\n";
425       OS << "  }\n";
426       OS << "  void set" << getUpperName()
427          << "(ASTContext &C, llvm::StringRef S) {\n";
428       OS << "    " << getLowerName() << "Length = S.size();\n";
429       OS << "    this->" << getLowerName() << " = new (C, 1) char ["
430          << getLowerName() << "Length];\n";
431       OS << "    if (!S.empty())\n";
432       OS << "      std::memcpy(this->" << getLowerName() << ", S.data(), "
433          << getLowerName() << "Length);\n";
434       OS << "  }";
435     }
436 
437     void writeCloneArgs(raw_ostream &OS) const override {
438       OS << "get" << getUpperName() << "()";
439     }
440 
441     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
442       OS << "A->get" << getUpperName() << "()";
443     }
444 
445     void writeCtorBody(raw_ostream &OS) const override {
446       OS << "    if (!" << getUpperName() << ".empty())\n";
447       OS << "      std::memcpy(" << getLowerName() << ", " << getUpperName()
448          << ".data(), " << getLowerName() << "Length);\n";
449     }
450 
451     void writeCtorInitializers(raw_ostream &OS) const override {
452       OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
453          << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
454          << "Length])";
455     }
456 
457     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
458       OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
459     }
460 
461     void writeCtorParameters(raw_ostream &OS) const override {
462       OS << "llvm::StringRef " << getUpperName();
463     }
464 
465     void writeDeclarations(raw_ostream &OS) const override {
466       OS << "unsigned " << getLowerName() << "Length;\n";
467       OS << "char *" << getLowerName() << ";";
468     }
469 
470     void writePCHReadDecls(raw_ostream &OS) const override {
471       OS << "    std::string " << getLowerName()
472          << "= Record.readString();\n";
473     }
474 
475     void writePCHReadArgs(raw_ostream &OS) const override {
476       OS << getLowerName();
477     }
478 
479     void writePCHWrite(raw_ostream &OS) const override {
480       OS << "    Record.AddString(SA->get" << getUpperName() << "());\n";
481     }
482 
483     void writeValue(raw_ostream &OS) const override {
484       OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
485     }
486 
487     void writeDump(raw_ostream &OS) const override {
488       OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
489          << "() << \"\\\"\";\n";
490     }
491   };
492 
493   class AlignedArgument : public Argument {
494   public:
495     AlignedArgument(const Record &Arg, StringRef Attr)
496       : Argument(Arg, Attr)
497     {}
498 
499     void writeAccessors(raw_ostream &OS) const override {
500       OS << "  bool is" << getUpperName() << "Dependent() const;\n";
501       OS << "  bool is" << getUpperName() << "ErrorDependent() const;\n";
502 
503       OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
504 
505       OS << "  bool is" << getUpperName() << "Expr() const {\n";
506       OS << "    return is" << getLowerName() << "Expr;\n";
507       OS << "  }\n";
508 
509       OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
510       OS << "    assert(is" << getLowerName() << "Expr);\n";
511       OS << "    return " << getLowerName() << "Expr;\n";
512       OS << "  }\n";
513 
514       OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
515       OS << "    assert(!is" << getLowerName() << "Expr);\n";
516       OS << "    return " << getLowerName() << "Type;\n";
517       OS << "  }";
518 
519       OS << "  std::optional<unsigned> getCached" << getUpperName()
520          << "Value() const {\n";
521       OS << "    return " << getLowerName() << "Cache;\n";
522       OS << "  }";
523 
524       OS << "  void setCached" << getUpperName()
525          << "Value(unsigned AlignVal) {\n";
526       OS << "    " << getLowerName() << "Cache = AlignVal;\n";
527       OS << "  }";
528     }
529 
530     void writeAccessorDefinitions(raw_ostream &OS) const override {
531       OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
532          << "Dependent() const {\n";
533       OS << "  if (is" << getLowerName() << "Expr)\n";
534       OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
535          << "Expr->isValueDependent() || " << getLowerName()
536          << "Expr->isTypeDependent());\n";
537       OS << "  else\n";
538       OS << "    return " << getLowerName()
539          << "Type->getType()->isDependentType();\n";
540       OS << "}\n";
541 
542       OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
543          << "ErrorDependent() const {\n";
544       OS << "  if (is" << getLowerName() << "Expr)\n";
545       OS << "    return " << getLowerName() << "Expr && " << getLowerName()
546          << "Expr->containsErrors();\n";
547       OS << "  return " << getLowerName()
548          << "Type->getType()->containsErrors();\n";
549       OS << "}\n";
550     }
551 
552     void writeASTVisitorTraversal(raw_ostream &OS) const override {
553       StringRef Name = getUpperName();
554       OS << "  if (A->is" << Name << "Expr()) {\n"
555          << "    if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
556          << "      return false;\n"
557          << "  } else if (auto *TSI = A->get" << Name << "Type()) {\n"
558          << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
559          << "      return false;\n"
560          << "  }\n";
561     }
562 
563     void writeCloneArgs(raw_ostream &OS) const override {
564       OS << "is" << getLowerName() << "Expr, is" << getLowerName()
565          << "Expr ? static_cast<void*>(" << getLowerName()
566          << "Expr) : " << getLowerName()
567          << "Type";
568     }
569 
570     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
571       // FIXME: move the definition in Sema::InstantiateAttrs to here.
572       // In the meantime, aligned attributes are cloned.
573     }
574 
575     void writeCtorBody(raw_ostream &OS) const override {
576       OS << "    if (is" << getLowerName() << "Expr)\n";
577       OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
578          << getUpperName() << ");\n";
579       OS << "    else\n";
580       OS << "       " << getLowerName()
581          << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
582          << ");\n";
583     }
584 
585     void writeCtorInitializers(raw_ostream &OS) const override {
586       OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
587     }
588 
589     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
590       OS << "is" << getLowerName() << "Expr(false)";
591     }
592 
593     void writeCtorParameters(raw_ostream &OS) const override {
594       OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
595     }
596 
597     void writeImplicitCtorArgs(raw_ostream &OS) const override {
598       OS << "Is" << getUpperName() << "Expr, " << getUpperName();
599     }
600 
601     void writeDeclarations(raw_ostream &OS) const override {
602       OS << "bool is" << getLowerName() << "Expr;\n";
603       OS << "union {\n";
604       OS << "Expr *" << getLowerName() << "Expr;\n";
605       OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
606       OS << "};\n";
607       OS << "std::optional<unsigned> " << getLowerName() << "Cache;\n";
608     }
609 
610     void writePCHReadArgs(raw_ostream &OS) const override {
611       OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
612     }
613 
614     void writePCHReadDecls(raw_ostream &OS) const override {
615       OS << "    bool is" << getLowerName() << "Expr = Record.readInt();\n";
616       OS << "    void *" << getLowerName() << "Ptr;\n";
617       OS << "    if (is" << getLowerName() << "Expr)\n";
618       OS << "      " << getLowerName() << "Ptr = Record.readExpr();\n";
619       OS << "    else\n";
620       OS << "      " << getLowerName()
621          << "Ptr = Record.readTypeSourceInfo();\n";
622     }
623 
624     void writePCHWrite(raw_ostream &OS) const override {
625       OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
626       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
627       OS << "      Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
628       OS << "    else\n";
629       OS << "      Record.AddTypeSourceInfo(SA->get" << getUpperName()
630          << "Type());\n";
631     }
632 
633     std::string getIsOmitted() const override {
634       return "!((is" + getLowerName().str() + "Expr && " +
635              getLowerName().str() + "Expr) || (!is" + getLowerName().str() +
636              "Expr && " + getLowerName().str() + "Type))";
637     }
638 
639     void writeValue(raw_ostream &OS) const override {
640       OS << "\";\n";
641       OS << "    if (is" << getLowerName() << "Expr && " << getLowerName()
642          << "Expr)";
643       OS << "      " << getLowerName()
644          << "Expr->printPretty(OS, nullptr, Policy);\n";
645       OS << "    if (!is" << getLowerName() << "Expr && " << getLowerName()
646          << "Type)";
647       OS << "      " << getLowerName()
648          << "Type->getType().print(OS, Policy);\n";
649       OS << "    OS << \"";
650     }
651 
652     void writeDump(raw_ostream &OS) const override {
653       OS << "    if (!SA->is" << getUpperName() << "Expr())\n";
654       OS << "      dumpType(SA->get" << getUpperName()
655          << "Type()->getType());\n";
656     }
657 
658     void writeDumpChildren(raw_ostream &OS) const override {
659       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
660       OS << "      Visit(SA->get" << getUpperName() << "Expr());\n";
661     }
662 
663     void writeHasChildren(raw_ostream &OS) const override {
664       OS << "SA->is" << getUpperName() << "Expr()";
665     }
666   };
667 
668   class VariadicArgument : public Argument {
669     std::string Type, ArgName, ArgSizeName, RangeName;
670 
671   protected:
672     // Assumed to receive a parameter: raw_ostream OS.
673     virtual void writeValueImpl(raw_ostream &OS) const {
674       OS << "    OS << Val;\n";
675     }
676     // Assumed to receive a parameter: raw_ostream OS.
677     virtual void writeDumpImpl(raw_ostream &OS) const {
678       OS << "      OS << \" \" << Val;\n";
679     }
680 
681   public:
682     VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
683         : Argument(Arg, Attr), Type(std::move(T)),
684           ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
685           RangeName(std::string(getLowerName())) {}
686 
687     VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
688         : Argument(Arg, Attr), Type(std::move(T)),
689           ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
690           RangeName(std::string(getLowerName())) {}
691 
692     const std::string &getType() const { return Type; }
693     const std::string &getArgName() const { return ArgName; }
694     const std::string &getArgSizeName() const { return ArgSizeName; }
695     bool isVariadic() const override { return true; }
696 
697     void writeAccessors(raw_ostream &OS) const override {
698       std::string IteratorType = getLowerName().str() + "_iterator";
699       std::string BeginFn = getLowerName().str() + "_begin()";
700       std::string EndFn = getLowerName().str() + "_end()";
701 
702       OS << "  typedef " << Type << "* " << IteratorType << ";\n";
703       OS << "  " << IteratorType << " " << BeginFn << " const {"
704          << " return " << ArgName << "; }\n";
705       OS << "  " << IteratorType << " " << EndFn << " const {"
706          << " return " << ArgName << " + " << ArgSizeName << "; }\n";
707       OS << "  unsigned " << getLowerName() << "_size() const {"
708          << " return " << ArgSizeName << "; }\n";
709       OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
710          << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
711          << "); }\n";
712     }
713 
714     void writeSetter(raw_ostream &OS) const {
715       OS << "  void set" << getUpperName() << "(ASTContext &Ctx, ";
716       writeCtorParameters(OS);
717       OS << ") {\n";
718       OS << "    " << ArgSizeName << " = " << getUpperName() << "Size;\n";
719       OS << "    " << ArgName << " = new (Ctx, 16) " << getType() << "["
720          << ArgSizeName << "];\n";
721       OS << "  ";
722       writeCtorBody(OS);
723       OS << "  }\n";
724     }
725 
726     void writeCloneArgs(raw_ostream &OS) const override {
727       OS << ArgName << ", " << ArgSizeName;
728     }
729 
730     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
731       // This isn't elegant, but we have to go through public methods...
732       OS << "A->" << getLowerName() << "_begin(), "
733          << "A->" << getLowerName() << "_size()";
734     }
735 
736     void writeASTVisitorTraversal(raw_ostream &OS) const override {
737       // FIXME: Traverse the elements.
738     }
739 
740     void writeCtorBody(raw_ostream &OS) const override {
741       OS << "  std::copy(" << getUpperName() << ", " << getUpperName() << " + "
742          << ArgSizeName << ", " << ArgName << ");\n";
743     }
744 
745     void writeCtorInitializers(raw_ostream &OS) const override {
746       OS << ArgSizeName << "(" << getUpperName() << "Size), "
747          << ArgName << "(new (Ctx, 16) " << getType() << "["
748          << ArgSizeName << "])";
749     }
750 
751     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
752       OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
753     }
754 
755     void writeCtorParameters(raw_ostream &OS) const override {
756       OS << getType() << " *" << getUpperName() << ", unsigned "
757          << getUpperName() << "Size";
758     }
759 
760     void writeImplicitCtorArgs(raw_ostream &OS) const override {
761       OS << getUpperName() << ", " << getUpperName() << "Size";
762     }
763 
764     void writeDeclarations(raw_ostream &OS) const override {
765       OS << "  unsigned " << ArgSizeName << ";\n";
766       OS << "  " << getType() << " *" << ArgName << ";";
767     }
768 
769     void writePCHReadDecls(raw_ostream &OS) const override {
770       OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
771       OS << "    SmallVector<" << getType() << ", 4> "
772          << getLowerName() << ";\n";
773       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
774          << "Size);\n";
775 
776       // If we can't store the values in the current type (if it's something
777       // like StringRef), store them in a different type and convert the
778       // container afterwards.
779       std::string StorageType = std::string(getStorageType(getType()));
780       std::string StorageName = std::string(getLowerName());
781       if (StorageType != getType()) {
782         StorageName += "Storage";
783         OS << "    SmallVector<" << StorageType << ", 4> "
784            << StorageName << ";\n";
785         OS << "    " << StorageName << ".reserve(" << getLowerName()
786            << "Size);\n";
787       }
788 
789       OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
790       std::string read = ReadPCHRecord(Type);
791       OS << "      " << StorageName << ".push_back(" << read << ");\n";
792 
793       if (StorageType != getType()) {
794         OS << "    for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
795         OS << "      " << getLowerName() << ".push_back("
796            << StorageName << "[i]);\n";
797       }
798     }
799 
800     void writePCHReadArgs(raw_ostream &OS) const override {
801       OS << getLowerName() << ".data(), " << getLowerName() << "Size";
802     }
803 
804     void writePCHWrite(raw_ostream &OS) const override {
805       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
806       OS << "    for (auto &Val : SA->" << RangeName << "())\n";
807       OS << "      " << WritePCHRecord(Type, "Val");
808     }
809 
810     void writeValue(raw_ostream &OS) const override {
811       OS << "\";\n";
812       OS << "  for (const auto &Val : " << RangeName << "()) {\n"
813          << "    DelimitAttributeArgument(OS, IsFirstArgument);\n";
814       writeValueImpl(OS);
815       OS << "  }\n";
816       OS << "  OS << \"";
817     }
818 
819     void writeDump(raw_ostream &OS) const override {
820       OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
821       writeDumpImpl(OS);
822     }
823   };
824 
825   class VariadicOMPInteropInfoArgument : public VariadicArgument {
826   public:
827     VariadicOMPInteropInfoArgument(const Record &Arg, StringRef Attr)
828         : VariadicArgument(Arg, Attr, "OMPInteropInfo") {}
829 
830     void writeDump(raw_ostream &OS) const override {
831       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
832          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
833          << getLowerName() << "_end(); I != E; ++I) {\n";
834       OS << "      if (I->IsTarget && I->IsTargetSync)\n";
835       OS << "        OS << \" Target_TargetSync\";\n";
836       OS << "      else if (I->IsTarget)\n";
837       OS << "        OS << \" Target\";\n";
838       OS << "      else\n";
839       OS << "        OS << \" TargetSync\";\n";
840       OS << "    }\n";
841     }
842 
843     void writePCHReadDecls(raw_ostream &OS) const override {
844       OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
845       OS << "    SmallVector<OMPInteropInfo, 4> " << getLowerName() << ";\n";
846       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
847          << "Size);\n";
848       OS << "    for (unsigned I = 0, E = " << getLowerName() << "Size; ";
849       OS << "I != E; ++I) {\n";
850       OS << "      bool IsTarget = Record.readBool();\n";
851       OS << "      bool IsTargetSync = Record.readBool();\n";
852       OS << "      " << getLowerName()
853          << ".emplace_back(IsTarget, IsTargetSync);\n";
854       OS << "    }\n";
855     }
856 
857     void writePCHWrite(raw_ostream &OS) const override {
858       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
859       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
860          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
861          << getLowerName() << "_end(); I != E; ++I) {\n";
862       OS << "      Record.writeBool(I->IsTarget);\n";
863       OS << "      Record.writeBool(I->IsTargetSync);\n";
864       OS << "    }\n";
865     }
866   };
867 
868   class VariadicParamIdxArgument : public VariadicArgument {
869   public:
870     VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
871         : VariadicArgument(Arg, Attr, "ParamIdx") {}
872 
873   public:
874     void writeValueImpl(raw_ostream &OS) const override {
875       OS << "    OS << Val.getSourceIndex();\n";
876     }
877 
878     void writeDumpImpl(raw_ostream &OS) const override {
879       OS << "      OS << \" \" << Val.getSourceIndex();\n";
880     }
881   };
882 
883   struct VariadicParamOrParamIdxArgument : public VariadicArgument {
884     VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
885         : VariadicArgument(Arg, Attr, "int") {}
886   };
887 
888   // Unique the enums, but maintain the original declaration ordering.
889   std::vector<StringRef>
890   uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
891     std::vector<StringRef> uniques;
892     SmallDenseSet<StringRef, 8> unique_set;
893     for (const auto &i : enums) {
894       if (unique_set.insert(i).second)
895         uniques.push_back(i);
896     }
897     return uniques;
898   }
899 
900   class EnumArgument : public Argument {
901     std::string fullType;
902     StringRef shortType;
903     std::vector<StringRef> values, enums, uniques;
904     bool isExternal;
905 
906   public:
907     EnumArgument(const Record &Arg, StringRef Attr)
908         : Argument(Arg, Attr), values(Arg.getValueAsListOfStrings("Values")),
909           enums(Arg.getValueAsListOfStrings("Enums")),
910           uniques(uniqueEnumsInOrder(enums)),
911           isExternal(Arg.getValueAsBit("IsExternalType")) {
912       StringRef Type = Arg.getValueAsString("Type");
913       shortType = isExternal ? Type.rsplit("::").second : Type;
914       // If shortType didn't contain :: at all rsplit will give us an empty
915       // string.
916       if (shortType.empty())
917         shortType = Type;
918       fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
919 
920       // FIXME: Emit a proper error
921       assert(!uniques.empty());
922     }
923 
924     bool isEnumArg() const override { return true; }
925 
926     void writeAccessors(raw_ostream &OS) const override {
927       OS << "  " << fullType << " get" << getUpperName() << "() const {\n";
928       OS << "    return " << getLowerName() << ";\n";
929       OS << "  }";
930     }
931 
932     void writeCloneArgs(raw_ostream &OS) const override {
933       OS << getLowerName();
934     }
935 
936     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
937       OS << "A->get" << getUpperName() << "()";
938     }
939     void writeCtorInitializers(raw_ostream &OS) const override {
940       OS << getLowerName() << "(" << getUpperName() << ")";
941     }
942     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
943       OS << getLowerName() << "(" << fullType << "(0))";
944     }
945     void writeCtorParameters(raw_ostream &OS) const override {
946       OS << fullType << " " << getUpperName();
947     }
948     void writeDeclarations(raw_ostream &OS) const override {
949       if (!isExternal) {
950         auto i = uniques.cbegin(), e = uniques.cend();
951         // The last one needs to not have a comma.
952         --e;
953 
954         OS << "public:\n";
955         OS << "  enum " << shortType << " {\n";
956         for (; i != e; ++i)
957           OS << "    " << *i << ",\n";
958         OS << "    " << *e << "\n";
959         OS << "  };\n";
960       }
961 
962       OS << "private:\n";
963       OS << "  " << fullType << " " << getLowerName() << ";";
964     }
965 
966     void writePCHReadDecls(raw_ostream &OS) const override {
967       OS << "    " << fullType << " " << getLowerName() << "(static_cast<"
968          << fullType << ">(Record.readInt()));\n";
969     }
970 
971     void writePCHReadArgs(raw_ostream &OS) const override {
972       OS << getLowerName();
973     }
974 
975     void writePCHWrite(raw_ostream &OS) const override {
976       OS << "Record.push_back(static_cast<uint64_t>(SA->get" << getUpperName()
977          << "()));\n";
978     }
979 
980     void writeValue(raw_ostream &OS) const override {
981       // FIXME: this isn't 100% correct -- some enum arguments require printing
982       // as a string literal, while others require printing as an identifier.
983       // Tablegen currently does not distinguish between the two forms.
984       OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << shortType
985          << "ToStr(get" << getUpperName() << "()) << \"\\\"";
986     }
987 
988     void writeDump(raw_ostream &OS) const override {
989       OS << "    switch(SA->get" << getUpperName() << "()) {\n";
990       for (const auto &I : uniques) {
991         OS << "    case " << fullType << "::" << I << ":\n";
992         OS << "      OS << \" " << I << "\";\n";
993         OS << "      break;\n";
994       }
995       if (isExternal) {
996         OS << "    default:\n";
997         OS << "      llvm_unreachable(\"Invalid attribute value\");\n";
998       }
999       OS << "    }\n";
1000     }
1001 
1002     void writeConversion(raw_ostream &OS, bool Header) const {
1003       if (Header) {
1004         OS << "  static bool ConvertStrTo" << shortType << "(StringRef Val, "
1005            << fullType << " &Out);\n";
1006         OS << "  static const char *Convert" << shortType << "ToStr("
1007            << fullType << " Val);\n";
1008         return;
1009       }
1010 
1011       OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1012          << "(StringRef Val, " << fullType << " &Out) {\n";
1013       OS << "  std::optional<" << fullType << "> "
1014          << "R = llvm::StringSwitch<std::optional<" << fullType << ">>(Val)\n";
1015       for (size_t I = 0; I < enums.size(); ++I) {
1016         OS << "    .Case(\"" << values[I] << "\", ";
1017         OS << fullType << "::" << enums[I] << ")\n";
1018       }
1019       OS << "    .Default(std::optional<" << fullType << ">());\n";
1020       OS << "  if (R) {\n";
1021       OS << "    Out = *R;\n      return true;\n    }\n";
1022       OS << "  return false;\n";
1023       OS << "}\n\n";
1024 
1025       // Mapping from enumeration values back to enumeration strings isn't
1026       // trivial because some enumeration values have multiple named
1027       // enumerators, such as type_visibility(internal) and
1028       // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
1029       OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1030          << "ToStr(" << fullType << " Val) {\n"
1031          << "  switch(Val) {\n";
1032       SmallDenseSet<StringRef, 8> Uniques;
1033       for (size_t I = 0; I < enums.size(); ++I) {
1034         if (Uniques.insert(enums[I]).second)
1035           OS << "  case " << fullType << "::" << enums[I] << ": return \""
1036              << values[I] << "\";\n";
1037       }
1038       if (isExternal) {
1039         OS << "  default: llvm_unreachable(\"Invalid attribute value\");\n";
1040       }
1041       OS << "  }\n"
1042          << "  llvm_unreachable(\"No enumerator with that value\");\n"
1043          << "}\n";
1044     }
1045   };
1046 
1047   class VariadicEnumArgument: public VariadicArgument {
1048     std::string fullType;
1049     StringRef shortType;
1050     std::vector<StringRef> values, enums, uniques;
1051     bool isExternal;
1052 
1053   protected:
1054     void writeValueImpl(raw_ostream &OS) const override {
1055       // FIXME: this isn't 100% correct -- some enum arguments require printing
1056       // as a string literal, while others require printing as an identifier.
1057       // Tablegen currently does not distinguish between the two forms.
1058       OS << "    OS << \"\\\"\" << " << getAttrName() << "Attr::Convert"
1059          << shortType << "ToStr(Val)"
1060          << "<< \"\\\"\";\n";
1061     }
1062 
1063   public:
1064     VariadicEnumArgument(const Record &Arg, StringRef Attr)
1065         : VariadicArgument(Arg, Attr,
1066                            std::string(Arg.getValueAsString("Type"))),
1067           values(Arg.getValueAsListOfStrings("Values")),
1068           enums(Arg.getValueAsListOfStrings("Enums")),
1069           uniques(uniqueEnumsInOrder(enums)),
1070           isExternal(Arg.getValueAsBit("IsExternalType")) {
1071       StringRef Type = Arg.getValueAsString("Type");
1072       shortType = isExternal ? Type.rsplit("::").second : Type;
1073       // If shortType didn't contain :: at all rsplit will give us an empty
1074       // string.
1075       if (shortType.empty())
1076         shortType = Type;
1077       fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
1078 
1079       // FIXME: Emit a proper error
1080       assert(!uniques.empty());
1081     }
1082 
1083     bool isVariadicEnumArg() const override { return true; }
1084 
1085     void writeDeclarations(raw_ostream &OS) const override {
1086       if (!isExternal) {
1087         auto i = uniques.cbegin(), e = uniques.cend();
1088         // The last one needs to not have a comma.
1089         --e;
1090 
1091         OS << "public:\n";
1092         OS << "  enum " << shortType << " {\n";
1093         for (; i != e; ++i)
1094           OS << "    " << *i << ",\n";
1095         OS << "    " << *e << "\n";
1096         OS << "  };\n";
1097       }
1098       OS << "private:\n";
1099 
1100       VariadicArgument::writeDeclarations(OS);
1101     }
1102 
1103     void writeDump(raw_ostream &OS) const override {
1104       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1105          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1106          << getLowerName() << "_end(); I != E; ++I) {\n";
1107       OS << "      switch(*I) {\n";
1108       for (const auto &UI : uniques) {
1109         OS << "    case " << fullType << "::" << UI << ":\n";
1110         OS << "      OS << \" " << UI << "\";\n";
1111         OS << "      break;\n";
1112       }
1113       OS << "      }\n";
1114       OS << "    }\n";
1115     }
1116 
1117     void writePCHReadDecls(raw_ostream &OS) const override {
1118       OS << "    unsigned " << getLowerName() << "Size = Record.readInt();\n";
1119       OS << "    SmallVector<" << fullType << ", 4> " << getLowerName()
1120          << ";\n";
1121       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
1122          << "Size);\n";
1123       OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1124       OS << "      " << getLowerName() << ".push_back("
1125          << "static_cast<" << fullType << ">(Record.readInt()));\n";
1126     }
1127 
1128     void writePCHWrite(raw_ostream &OS) const override {
1129       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
1130       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1131          << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1132          << getLowerName() << "_end(); i != e; ++i)\n";
1133       OS << "      " << WritePCHRecord(fullType, "(*i)");
1134     }
1135 
1136     void writeConversion(raw_ostream &OS, bool Header) const {
1137       if (Header) {
1138         OS << "  static bool ConvertStrTo" << shortType << "(StringRef Val, "
1139            << fullType << " &Out);\n";
1140         OS << "  static const char *Convert" << shortType << "ToStr("
1141            << fullType << " Val);\n";
1142         return;
1143       }
1144 
1145       OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1146          << "(StringRef Val, ";
1147       OS << fullType << " &Out) {\n";
1148       OS << "  std::optional<" << fullType
1149          << "> R = llvm::StringSwitch<std::optional<";
1150       OS << fullType << ">>(Val)\n";
1151       for (size_t I = 0; I < enums.size(); ++I) {
1152         OS << "    .Case(\"" << values[I] << "\", ";
1153         OS << fullType << "::" << enums[I] << ")\n";
1154       }
1155       OS << "    .Default(std::optional<" << fullType << ">());\n";
1156       OS << "  if (R) {\n";
1157       OS << "    Out = *R;\n      return true;\n    }\n";
1158       OS << "  return false;\n";
1159       OS << "}\n\n";
1160 
1161       OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1162          << "ToStr(" << fullType << " Val) {\n"
1163          << "  switch(Val) {\n";
1164       SmallDenseSet<StringRef, 8> Uniques;
1165       for (size_t I = 0; I < enums.size(); ++I) {
1166         if (Uniques.insert(enums[I]).second)
1167           OS << "  case " << fullType << "::" << enums[I] << ": return \""
1168              << values[I] << "\";\n";
1169       }
1170       OS << "  }\n"
1171          << "  llvm_unreachable(\"No enumerator with that value\");\n"
1172          << "}\n";
1173     }
1174   };
1175 
1176   class VersionArgument : public Argument {
1177   public:
1178     VersionArgument(const Record &Arg, StringRef Attr)
1179       : Argument(Arg, Attr)
1180     {}
1181 
1182     void writeAccessors(raw_ostream &OS) const override {
1183       OS << "  VersionTuple get" << getUpperName() << "() const {\n";
1184       OS << "    return " << getLowerName() << ";\n";
1185       OS << "  }\n";
1186       OS << "  void set" << getUpperName()
1187          << "(ASTContext &C, VersionTuple V) {\n";
1188       OS << "    " << getLowerName() << " = V;\n";
1189       OS << "  }";
1190     }
1191 
1192     void writeCloneArgs(raw_ostream &OS) const override {
1193       OS << "get" << getUpperName() << "()";
1194     }
1195 
1196     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1197       OS << "A->get" << getUpperName() << "()";
1198     }
1199 
1200     void writeCtorInitializers(raw_ostream &OS) const override {
1201       OS << getLowerName() << "(" << getUpperName() << ")";
1202     }
1203 
1204     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1205       OS << getLowerName() << "()";
1206     }
1207 
1208     void writeCtorParameters(raw_ostream &OS) const override {
1209       OS << "VersionTuple " << getUpperName();
1210     }
1211 
1212     void writeDeclarations(raw_ostream &OS) const override {
1213       OS << "VersionTuple " << getLowerName() << ";\n";
1214     }
1215 
1216     void writePCHReadDecls(raw_ostream &OS) const override {
1217       OS << "    VersionTuple " << getLowerName()
1218          << "= Record.readVersionTuple();\n";
1219     }
1220 
1221     void writePCHReadArgs(raw_ostream &OS) const override {
1222       OS << getLowerName();
1223     }
1224 
1225     void writePCHWrite(raw_ostream &OS) const override {
1226       OS << "    Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1227     }
1228 
1229     void writeValue(raw_ostream &OS) const override {
1230       OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1231     }
1232 
1233     void writeDump(raw_ostream &OS) const override {
1234       OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
1235     }
1236   };
1237 
1238   class ExprArgument : public SimpleArgument {
1239   public:
1240     ExprArgument(const Record &Arg, StringRef Attr)
1241       : SimpleArgument(Arg, Attr, "Expr *")
1242     {}
1243 
1244     void writeASTVisitorTraversal(raw_ostream &OS) const override {
1245       OS << "  if (!"
1246          << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1247       OS << "    return false;\n";
1248     }
1249 
1250     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1251       OS << "tempInst" << getUpperName();
1252     }
1253 
1254     void writeTemplateInstantiation(raw_ostream &OS) const override {
1255       OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
1256       OS << "      {\n";
1257       OS << "        EnterExpressionEvaluationContext "
1258          << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1259       OS << "        ExprResult " << "Result = S.SubstExpr("
1260          << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1261       OS << "        if (Result.isInvalid())\n";
1262       OS << "          return nullptr;\n";
1263       OS << "        tempInst" << getUpperName() << " = Result.get();\n";
1264       OS << "      }\n";
1265     }
1266 
1267     void writeValue(raw_ostream &OS) const override {
1268       OS << "\";\n";
1269       OS << "    get" << getUpperName()
1270          << "()->printPretty(OS, nullptr, Policy);\n";
1271       OS << "    OS << \"";
1272     }
1273 
1274     void writeDump(raw_ostream &OS) const override {}
1275 
1276     void writeDumpChildren(raw_ostream &OS) const override {
1277       OS << "    Visit(SA->get" << getUpperName() << "());\n";
1278     }
1279 
1280     void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1281   };
1282 
1283   class VariadicExprArgument : public VariadicArgument {
1284   public:
1285     VariadicExprArgument(const Record &Arg, StringRef Attr)
1286       : VariadicArgument(Arg, Attr, "Expr *")
1287     {}
1288 
1289     VariadicExprArgument(StringRef ArgName, StringRef Attr)
1290         : VariadicArgument(ArgName, Attr, "Expr *") {}
1291 
1292     void writeASTVisitorTraversal(raw_ostream &OS) const override {
1293       OS << "  {\n";
1294       OS << "    " << getType() << " *I = A->" << getLowerName()
1295          << "_begin();\n";
1296       OS << "    " << getType() << " *E = A->" << getLowerName()
1297          << "_end();\n";
1298       OS << "    for (; I != E; ++I) {\n";
1299       OS << "      if (!getDerived().TraverseStmt(*I))\n";
1300       OS << "        return false;\n";
1301       OS << "    }\n";
1302       OS << "  }\n";
1303     }
1304 
1305     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1306       OS << "tempInst" << getUpperName() << ", "
1307          << "A->" << getLowerName() << "_size()";
1308     }
1309 
1310     void writeTemplateInstantiation(raw_ostream &OS) const override {
1311       OS << "      auto *tempInst" << getUpperName()
1312          << " = new (C, 16) " << getType()
1313          << "[A->" << getLowerName() << "_size()];\n";
1314       OS << "      {\n";
1315       OS << "        EnterExpressionEvaluationContext "
1316          << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1317       OS << "        " << getType() << " *TI = tempInst" << getUpperName()
1318          << ";\n";
1319       OS << "        " << getType() << " *I = A->" << getLowerName()
1320          << "_begin();\n";
1321       OS << "        " << getType() << " *E = A->" << getLowerName()
1322          << "_end();\n";
1323       OS << "        for (; I != E; ++I, ++TI) {\n";
1324       OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1325       OS << "          if (Result.isInvalid())\n";
1326       OS << "            return nullptr;\n";
1327       OS << "          *TI = Result.get();\n";
1328       OS << "        }\n";
1329       OS << "      }\n";
1330     }
1331 
1332     void writeDump(raw_ostream &OS) const override {}
1333 
1334     void writeDumpChildren(raw_ostream &OS) const override {
1335       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
1336          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1337          << getLowerName() << "_end(); I != E; ++I)\n";
1338       OS << "      Visit(*I);\n";
1339     }
1340 
1341     void writeHasChildren(raw_ostream &OS) const override {
1342       OS << "SA->" << getLowerName() << "_begin() != "
1343          << "SA->" << getLowerName() << "_end()";
1344     }
1345   };
1346 
1347   class VariadicIdentifierArgument : public VariadicArgument {
1348   public:
1349     VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1350       : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1351     {}
1352   };
1353 
1354   class VariadicStringArgument : public VariadicArgument {
1355   public:
1356     VariadicStringArgument(const Record &Arg, StringRef Attr)
1357       : VariadicArgument(Arg, Attr, "StringRef")
1358     {}
1359 
1360     void writeCtorBody(raw_ostream &OS) const override {
1361       OS << "  for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1362             "       ++I) {\n"
1363             "    StringRef Ref = " << getUpperName() << "[I];\n"
1364             "    if (!Ref.empty()) {\n"
1365             "      char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1366             "      std::memcpy(Mem, Ref.data(), Ref.size());\n"
1367             "      " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1368             "    }\n"
1369             "  }\n";
1370     }
1371 
1372     void writeValueImpl(raw_ostream &OS) const override {
1373       OS << "    OS << \"\\\"\" << Val << \"\\\"\";\n";
1374     }
1375   };
1376 
1377   class TypeArgument : public SimpleArgument {
1378   public:
1379     TypeArgument(const Record &Arg, StringRef Attr)
1380       : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1381     {}
1382 
1383     void writeAccessors(raw_ostream &OS) const override {
1384       OS << "  QualType get" << getUpperName() << "() const {\n";
1385       OS << "    return " << getLowerName() << "->getType();\n";
1386       OS << "  }";
1387       OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
1388       OS << "    return " << getLowerName() << ";\n";
1389       OS << "  }";
1390     }
1391 
1392     void writeASTVisitorTraversal(raw_ostream &OS) const override {
1393       OS << "  if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1394       OS << "    if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1395       OS << "      return false;\n";
1396     }
1397 
1398     void writeTemplateInstantiation(raw_ostream &OS) const override {
1399       OS << "      " << getType() << " tempInst" << getUpperName() << " =\n";
1400       OS << "        S.SubstType(A->get" << getUpperName() << "Loc(), "
1401          << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
1402       OS << "      if (!tempInst" << getUpperName() << ")\n";
1403       OS << "        return nullptr;\n";
1404     }
1405 
1406     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1407       OS << "tempInst" << getUpperName();
1408     }
1409 
1410     void writePCHWrite(raw_ostream &OS) const override {
1411       OS << "    "
1412          << WritePCHRecord(getType(),
1413                            "SA->get" + std::string(getUpperName()) + "Loc()");
1414     }
1415   };
1416 
1417 } // end anonymous namespace
1418 
1419 static std::unique_ptr<Argument>
1420 createArgument(const Record &Arg, StringRef Attr,
1421                const Record *Search = nullptr) {
1422   if (!Search)
1423     Search = &Arg;
1424 
1425   std::unique_ptr<Argument> Ptr;
1426   llvm::StringRef ArgName = Search->getName();
1427 
1428   if (ArgName == "AlignedArgument")
1429     Ptr = std::make_unique<AlignedArgument>(Arg, Attr);
1430   else if (ArgName == "EnumArgument")
1431     Ptr = std::make_unique<EnumArgument>(Arg, Attr);
1432   else if (ArgName == "ExprArgument")
1433     Ptr = std::make_unique<ExprArgument>(Arg, Attr);
1434   else if (ArgName == "DeclArgument")
1435     Ptr = std::make_unique<SimpleArgument>(
1436         Arg, Attr, (Arg.getValueAsDef("Kind")->getName() + "Decl *").str());
1437   else if (ArgName == "IdentifierArgument")
1438     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1439   else if (ArgName == "DefaultBoolArgument")
1440     Ptr = std::make_unique<DefaultSimpleArgument>(
1441         Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1442   else if (ArgName == "BoolArgument")
1443     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "bool");
1444   else if (ArgName == "DefaultIntArgument")
1445     Ptr = std::make_unique<DefaultSimpleArgument>(
1446         Arg, Attr, "int", Arg.getValueAsInt("Default"));
1447   else if (ArgName == "IntArgument")
1448     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "int");
1449   else if (ArgName == "StringArgument")
1450     Ptr = std::make_unique<StringArgument>(Arg, Attr);
1451   else if (ArgName == "TypeArgument")
1452     Ptr = std::make_unique<TypeArgument>(Arg, Attr);
1453   else if (ArgName == "UnsignedArgument")
1454     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1455   else if (ArgName == "VariadicUnsignedArgument")
1456     Ptr = std::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1457   else if (ArgName == "VariadicStringArgument")
1458     Ptr = std::make_unique<VariadicStringArgument>(Arg, Attr);
1459   else if (ArgName == "VariadicEnumArgument")
1460     Ptr = std::make_unique<VariadicEnumArgument>(Arg, Attr);
1461   else if (ArgName == "VariadicExprArgument")
1462     Ptr = std::make_unique<VariadicExprArgument>(Arg, Attr);
1463   else if (ArgName == "VariadicParamIdxArgument")
1464     Ptr = std::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1465   else if (ArgName == "VariadicParamOrParamIdxArgument")
1466     Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(Arg, Attr);
1467   else if (ArgName == "ParamIdxArgument")
1468     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
1469   else if (ArgName == "VariadicIdentifierArgument")
1470     Ptr = std::make_unique<VariadicIdentifierArgument>(Arg, Attr);
1471   else if (ArgName == "VersionArgument")
1472     Ptr = std::make_unique<VersionArgument>(Arg, Attr);
1473   else if (ArgName == "OMPTraitInfoArgument")
1474     Ptr = std::make_unique<SimpleArgument>(Arg, Attr, "OMPTraitInfo *");
1475   else if (ArgName == "VariadicOMPInteropInfoArgument")
1476     Ptr = std::make_unique<VariadicOMPInteropInfoArgument>(Arg, Attr);
1477 
1478   if (!Ptr) {
1479     // Search in reverse order so that the most-derived type is handled first.
1480     ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1481     for (const auto &Base : llvm::reverse(Bases)) {
1482       if ((Ptr = createArgument(Arg, Attr, Base.first)))
1483         break;
1484     }
1485   }
1486 
1487   if (Ptr && Arg.getValueAsBit("Optional"))
1488     Ptr->setOptional(true);
1489 
1490   if (Ptr && Arg.getValueAsBit("Fake"))
1491     Ptr->setFake(true);
1492 
1493   return Ptr;
1494 }
1495 
1496 static void writeAvailabilityValue(raw_ostream &OS) {
1497   OS << "\" << getPlatform()->getName();\n"
1498      << "  if (getStrict()) OS << \", strict\";\n"
1499      << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1500      << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1501      << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1502      << "  if (getUnavailable()) OS << \", unavailable\";\n"
1503      << "  OS << \"";
1504 }
1505 
1506 static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1507   OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1508   // Only GNU deprecated has an optional fixit argument at the second position.
1509   if (Variety == "GNU")
1510      OS << "    if (!getReplacement().empty()) OS << \", \\\"\""
1511            " << getReplacement() << \"\\\"\";\n";
1512   OS << "    OS << \"";
1513 }
1514 
1515 static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
1516   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1517 
1518   OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1519   if (Spellings.empty()) {
1520     OS << "  return \"(No spelling)\";\n}\n\n";
1521     return;
1522   }
1523 
1524   OS << "  switch (getAttributeSpellingListIndex()) {\n"
1525         "  default:\n"
1526         "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1527         "    return \"(No spelling)\";\n";
1528 
1529   for (unsigned I = 0; I < Spellings.size(); ++I)
1530     OS << "  case " << I << ":\n"
1531           "    return \"" << Spellings[I].name() << "\";\n";
1532   // End of the switch statement.
1533   OS << "  }\n";
1534   // End of the getSpelling function.
1535   OS << "}\n\n";
1536 }
1537 
1538 static void
1539 writePrettyPrintFunction(const Record &R,
1540                          const std::vector<std::unique_ptr<Argument>> &Args,
1541                          raw_ostream &OS) {
1542   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1543 
1544   OS << "void " << R.getName() << "Attr::printPretty("
1545     << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1546 
1547   if (Spellings.empty()) {
1548     OS << "}\n\n";
1549     return;
1550   }
1551 
1552   OS << "  bool IsFirstArgument = true; (void)IsFirstArgument;\n"
1553      << "  unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
1554      << "  switch (getAttributeSpellingListIndex()) {\n"
1555      << "  default:\n"
1556      << "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1557      << "    break;\n";
1558 
1559   for (unsigned I = 0; I < Spellings.size(); ++ I) {
1560     llvm::SmallString<16> Prefix;
1561     llvm::SmallString<8> Suffix;
1562     // The actual spelling of the name and namespace (if applicable)
1563     // of an attribute without considering prefix and suffix.
1564     llvm::SmallString<64> Spelling;
1565     std::string Name = Spellings[I].name();
1566     std::string Variety = Spellings[I].variety();
1567 
1568     if (Variety == "GNU") {
1569       Prefix = " __attribute__((";
1570       Suffix = "))";
1571     } else if (Variety == "CXX11" || Variety == "C23") {
1572       Prefix = " [[";
1573       Suffix = "]]";
1574       std::string Namespace = Spellings[I].nameSpace();
1575       if (!Namespace.empty()) {
1576         Spelling += Namespace;
1577         Spelling += "::";
1578       }
1579     } else if (Variety == "Declspec") {
1580       Prefix = " __declspec(";
1581       Suffix = ")";
1582     } else if (Variety == "Microsoft") {
1583       Prefix = "[";
1584       Suffix = "]";
1585     } else if (Variety == "Keyword") {
1586       Prefix = " ";
1587       Suffix = "";
1588     } else if (Variety == "Pragma") {
1589       Prefix = "#pragma ";
1590       Suffix = "\n";
1591       std::string Namespace = Spellings[I].nameSpace();
1592       if (!Namespace.empty()) {
1593         Spelling += Namespace;
1594         Spelling += " ";
1595       }
1596     } else if (Variety == "HLSLSemantic") {
1597       Prefix = ":";
1598       Suffix = "";
1599     } else {
1600       llvm_unreachable("Unknown attribute syntax variety!");
1601     }
1602 
1603     Spelling += Name;
1604 
1605     OS << "  case " << I << " : {\n"
1606        << "    OS << \"" << Prefix << Spelling << "\";\n";
1607 
1608     if (Variety == "Pragma") {
1609       OS << "    printPrettyPragma(OS, Policy);\n";
1610       OS << "    OS << \"\\n\";";
1611       OS << "    break;\n";
1612       OS << "  }\n";
1613       continue;
1614     }
1615 
1616     if (Spelling == "availability") {
1617       OS << "    OS << \"(";
1618       writeAvailabilityValue(OS);
1619       OS << ")\";\n";
1620     } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1621       OS << "    OS << \"(";
1622       writeDeprecatedAttrValue(OS, Variety);
1623       OS << ")\";\n";
1624     } else {
1625       // To avoid printing parentheses around an empty argument list or
1626       // printing spurious commas at the end of an argument list, we need to
1627       // determine where the last provided non-fake argument is.
1628       bool FoundNonOptArg = false;
1629       for (const auto &arg : llvm::reverse(Args)) {
1630         if (arg->isFake())
1631           continue;
1632         if (FoundNonOptArg)
1633           continue;
1634         // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1635         // any way to detect whether the argument was omitted.
1636         if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1637           FoundNonOptArg = true;
1638           continue;
1639         }
1640         OS << "    if (" << arg->getIsOmitted() << ")\n"
1641            << "      ++TrailingOmittedArgs;\n";
1642       }
1643       unsigned ArgIndex = 0;
1644       for (const auto &arg : Args) {
1645         if (arg->isFake())
1646           continue;
1647         std::string IsOmitted = arg->getIsOmitted();
1648         if (arg->isOptional() && IsOmitted != "false")
1649           OS << "    if (!(" << IsOmitted << ")) {\n";
1650         // Variadic arguments print their own leading comma.
1651         if (!arg->isVariadic())
1652           OS << "    DelimitAttributeArgument(OS, IsFirstArgument);\n";
1653         OS << "    OS << \"";
1654         arg->writeValue(OS);
1655         OS << "\";\n";
1656         if (arg->isOptional() && IsOmitted != "false")
1657           OS << "    }\n";
1658         ++ArgIndex;
1659       }
1660       if (ArgIndex != 0)
1661         OS << "    if (!IsFirstArgument)\n"
1662            << "      OS << \")\";\n";
1663     }
1664     OS << "    OS << \"" << Suffix << "\";\n"
1665        << "    break;\n"
1666        << "  }\n";
1667   }
1668 
1669   // End of the switch statement.
1670   OS << "}\n";
1671   // End of the print function.
1672   OS << "}\n\n";
1673 }
1674 
1675 /// Return the index of a spelling in a spelling list.
1676 static unsigned
1677 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1678                      const FlattenedSpelling &Spelling) {
1679   assert(!SpellingList.empty() && "Spelling list is empty!");
1680 
1681   for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1682     const FlattenedSpelling &S = SpellingList[Index];
1683     if (S.variety() != Spelling.variety())
1684       continue;
1685     if (S.nameSpace() != Spelling.nameSpace())
1686       continue;
1687     if (S.name() != Spelling.name())
1688       continue;
1689 
1690     return Index;
1691   }
1692 
1693   llvm_unreachable("Unknown spelling!");
1694 }
1695 
1696 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1697   std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1698   if (Accessors.empty())
1699     return;
1700 
1701   const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1702   assert(!SpellingList.empty() &&
1703          "Attribute with empty spelling list can't have accessors!");
1704   for (const auto *Accessor : Accessors) {
1705     const StringRef Name = Accessor->getValueAsString("Name");
1706     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1707 
1708     OS << "  bool " << Name
1709        << "() const { return getAttributeSpellingListIndex() == ";
1710     for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1711       OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1712       if (Index != Spellings.size() - 1)
1713         OS << " ||\n    getAttributeSpellingListIndex() == ";
1714       else
1715         OS << "; }\n";
1716     }
1717   }
1718 }
1719 
1720 static bool
1721 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1722   assert(!Spellings.empty() && "An empty list of spellings was provided");
1723   std::string FirstName =
1724       std::string(NormalizeNameForSpellingComparison(Spellings.front().name()));
1725   for (const auto &Spelling :
1726        llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1727     std::string Name =
1728         std::string(NormalizeNameForSpellingComparison(Spelling.name()));
1729     if (Name != FirstName)
1730       return false;
1731   }
1732   return true;
1733 }
1734 
1735 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1736 static std::string
1737 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1738                         SemanticSpellingMap &Map) {
1739   // The enumerants are automatically generated based on the variety,
1740   // namespace (if present) and name for each attribute spelling. However,
1741   // care is taken to avoid trampling on the reserved namespace due to
1742   // underscores.
1743   std::string Ret("  enum Spelling {\n");
1744   std::set<std::string> Uniques;
1745   unsigned Idx = 0;
1746 
1747   // If we have a need to have this many spellings we likely need to add an
1748   // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1749   // value of SpellingNotCalculated there and here.
1750   assert(Spellings.size() < 15 &&
1751          "Too many spellings, would step on SpellingNotCalculated in "
1752          "AttributeCommonInfo");
1753   for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1754     const FlattenedSpelling &S = *I;
1755     const std::string &Variety = S.variety();
1756     const std::string &Spelling = S.name();
1757     const std::string &Namespace = S.nameSpace();
1758     std::string EnumName;
1759 
1760     EnumName += (Variety + "_");
1761     if (!Namespace.empty())
1762       EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1763       "_");
1764     EnumName += NormalizeNameForSpellingComparison(Spelling);
1765 
1766     // Even if the name is not unique, this spelling index corresponds to a
1767     // particular enumerant name that we've calculated.
1768     Map[Idx] = EnumName;
1769 
1770     // Since we have been stripping underscores to avoid trampling on the
1771     // reserved namespace, we may have inadvertently created duplicate
1772     // enumerant names. These duplicates are not considered part of the
1773     // semantic spelling, and can be elided.
1774     if (Uniques.find(EnumName) != Uniques.end())
1775       continue;
1776 
1777     Uniques.insert(EnumName);
1778     if (I != Spellings.begin())
1779       Ret += ",\n";
1780     // Duplicate spellings are not considered part of the semantic spelling
1781     // enumeration, but the spelling index and semantic spelling values are
1782     // meant to be equivalent, so we must specify a concrete value for each
1783     // enumerator.
1784     Ret += "    " + EnumName + " = " + llvm::utostr(Idx);
1785   }
1786   Ret += ",\n  SpellingNotCalculated = 15\n";
1787   Ret += "\n  };\n\n";
1788   return Ret;
1789 }
1790 
1791 void WriteSemanticSpellingSwitch(const std::string &VarName,
1792                                  const SemanticSpellingMap &Map,
1793                                  raw_ostream &OS) {
1794   OS << "  switch (" << VarName << ") {\n    default: "
1795     << "llvm_unreachable(\"Unknown spelling list index\");\n";
1796   for (const auto &I : Map)
1797     OS << "    case " << I.first << ": return " << I.second << ";\n";
1798   OS << "  }\n";
1799 }
1800 
1801 // Emits the LateParsed property for attributes.
1802 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1803   OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1804   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1805 
1806   for (const auto *Attr : Attrs) {
1807     bool LateParsed = Attr->getValueAsBit("LateParsed");
1808 
1809     if (LateParsed) {
1810       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1811 
1812       // FIXME: Handle non-GNU attributes
1813       for (const auto &I : Spellings) {
1814         if (I.variety() != "GNU")
1815           continue;
1816         OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1817       }
1818     }
1819   }
1820   OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1821 }
1822 
1823 static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1824   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1825   for (const auto &I : Spellings) {
1826     if (I.variety() == "GNU" || I.variety() == "CXX11")
1827       return true;
1828   }
1829   return false;
1830 }
1831 
1832 namespace {
1833 
1834 struct AttributeSubjectMatchRule {
1835   const Record *MetaSubject;
1836   const Record *Constraint;
1837 
1838   AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1839       : MetaSubject(MetaSubject), Constraint(Constraint) {
1840     assert(MetaSubject && "Missing subject");
1841   }
1842 
1843   bool isSubRule() const { return Constraint != nullptr; }
1844 
1845   std::vector<Record *> getSubjects() const {
1846     return (Constraint ? Constraint : MetaSubject)
1847         ->getValueAsListOfDefs("Subjects");
1848   }
1849 
1850   std::vector<Record *> getLangOpts() const {
1851     if (Constraint) {
1852       // Lookup the options in the sub-rule first, in case the sub-rule
1853       // overrides the rules options.
1854       std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1855       if (!Opts.empty())
1856         return Opts;
1857     }
1858     return MetaSubject->getValueAsListOfDefs("LangOpts");
1859   }
1860 
1861   // Abstract rules are used only for sub-rules
1862   bool isAbstractRule() const { return getSubjects().empty(); }
1863 
1864   StringRef getName() const {
1865     return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1866   }
1867 
1868   bool isNegatedSubRule() const {
1869     assert(isSubRule() && "Not a sub-rule");
1870     return Constraint->getValueAsBit("Negated");
1871   }
1872 
1873   std::string getSpelling() const {
1874     std::string Result = std::string(MetaSubject->getValueAsString("Name"));
1875     if (isSubRule()) {
1876       Result += '(';
1877       if (isNegatedSubRule())
1878         Result += "unless(";
1879       Result += getName();
1880       if (isNegatedSubRule())
1881         Result += ')';
1882       Result += ')';
1883     }
1884     return Result;
1885   }
1886 
1887   std::string getEnumValueName() const {
1888     SmallString<128> Result;
1889     Result += "SubjectMatchRule_";
1890     Result += MetaSubject->getValueAsString("Name");
1891     if (isSubRule()) {
1892       Result += "_";
1893       if (isNegatedSubRule())
1894         Result += "not_";
1895       Result += Constraint->getValueAsString("Name");
1896     }
1897     if (isAbstractRule())
1898       Result += "_abstract";
1899     return std::string(Result.str());
1900   }
1901 
1902   std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1903 
1904   static const char *EnumName;
1905 };
1906 
1907 const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1908 
1909 struct PragmaClangAttributeSupport {
1910   std::vector<AttributeSubjectMatchRule> Rules;
1911 
1912   class RuleOrAggregateRuleSet {
1913     std::vector<AttributeSubjectMatchRule> Rules;
1914     bool IsRule;
1915     RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1916                            bool IsRule)
1917         : Rules(Rules), IsRule(IsRule) {}
1918 
1919   public:
1920     bool isRule() const { return IsRule; }
1921 
1922     const AttributeSubjectMatchRule &getRule() const {
1923       assert(IsRule && "not a rule!");
1924       return Rules[0];
1925     }
1926 
1927     ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1928       return Rules;
1929     }
1930 
1931     static RuleOrAggregateRuleSet
1932     getRule(const AttributeSubjectMatchRule &Rule) {
1933       return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1934     }
1935     static RuleOrAggregateRuleSet
1936     getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1937       return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1938     }
1939   };
1940   llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
1941 
1942   PragmaClangAttributeSupport(RecordKeeper &Records);
1943 
1944   bool isAttributedSupported(const Record &Attribute);
1945 
1946   void emitMatchRuleList(raw_ostream &OS);
1947 
1948   void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1949 
1950   void generateParsingHelpers(raw_ostream &OS);
1951 };
1952 
1953 } // end anonymous namespace
1954 
1955 static bool isSupportedPragmaClangAttributeSubject(const Record &Subject) {
1956   // FIXME: #pragma clang attribute does not currently support statement
1957   // attributes, so test whether the subject is one that appertains to a
1958   // declaration node. However, it may be reasonable for support for statement
1959   // attributes to be added.
1960   if (Subject.isSubClassOf("DeclNode") || Subject.isSubClassOf("DeclBase") ||
1961       Subject.getName() == "DeclBase")
1962     return true;
1963 
1964   if (Subject.isSubClassOf("SubsetSubject"))
1965     return isSupportedPragmaClangAttributeSubject(
1966         *Subject.getValueAsDef("Base"));
1967 
1968   return false;
1969 }
1970 
1971 static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1972   const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
1973   if (!CurrentBase)
1974     return false;
1975   if (CurrentBase == Base)
1976     return true;
1977   return doesDeclDeriveFrom(CurrentBase, Base);
1978 }
1979 
1980 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1981     RecordKeeper &Records) {
1982   std::vector<Record *> MetaSubjects =
1983       Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1984   auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1985                                        const Record *MetaSubject,
1986                                        const Record *Constraint) {
1987     Rules.emplace_back(MetaSubject, Constraint);
1988     std::vector<Record *> ApplicableSubjects =
1989         SubjectContainer->getValueAsListOfDefs("Subjects");
1990     for (const auto *Subject : ApplicableSubjects) {
1991       bool Inserted =
1992           SubjectsToRules
1993               .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1994                                         AttributeSubjectMatchRule(MetaSubject,
1995                                                                   Constraint)))
1996               .second;
1997       if (!Inserted) {
1998         PrintFatalError("Attribute subject match rules should not represent"
1999                         "same attribute subjects.");
2000       }
2001     }
2002   };
2003   for (const auto *MetaSubject : MetaSubjects) {
2004     MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
2005     std::vector<Record *> Constraints =
2006         MetaSubject->getValueAsListOfDefs("Constraints");
2007     for (const auto *Constraint : Constraints)
2008       MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
2009   }
2010 
2011   std::vector<Record *> Aggregates =
2012       Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
2013   std::vector<Record *> DeclNodes =
2014     Records.getAllDerivedDefinitions(DeclNodeClassName);
2015   for (const auto *Aggregate : Aggregates) {
2016     Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
2017 
2018     // Gather sub-classes of the aggregate subject that act as attribute
2019     // subject rules.
2020     std::vector<AttributeSubjectMatchRule> Rules;
2021     for (const auto *D : DeclNodes) {
2022       if (doesDeclDeriveFrom(D, SubjectDecl)) {
2023         auto It = SubjectsToRules.find(D);
2024         if (It == SubjectsToRules.end())
2025           continue;
2026         if (!It->second.isRule() || It->second.getRule().isSubRule())
2027           continue; // Assume that the rule will be included as well.
2028         Rules.push_back(It->second.getRule());
2029       }
2030     }
2031 
2032     bool Inserted =
2033         SubjectsToRules
2034             .try_emplace(SubjectDecl,
2035                          RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
2036             .second;
2037     if (!Inserted) {
2038       PrintFatalError("Attribute subject match rules should not represent"
2039                       "same attribute subjects.");
2040     }
2041   }
2042 }
2043 
2044 static PragmaClangAttributeSupport &
2045 getPragmaAttributeSupport(RecordKeeper &Records) {
2046   static PragmaClangAttributeSupport Instance(Records);
2047   return Instance;
2048 }
2049 
2050 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
2051   OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
2052   OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
2053         "IsNegated) "
2054      << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
2055   OS << "#endif\n";
2056   for (const auto &Rule : Rules) {
2057     OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
2058     OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
2059        << Rule.isAbstractRule();
2060     if (Rule.isSubRule())
2061       OS << ", "
2062          << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
2063          << ", " << Rule.isNegatedSubRule();
2064     OS << ")\n";
2065   }
2066   OS << "#undef ATTR_MATCH_SUB_RULE\n";
2067 }
2068 
2069 bool PragmaClangAttributeSupport::isAttributedSupported(
2070     const Record &Attribute) {
2071   // If the attribute explicitly specified whether to support #pragma clang
2072   // attribute, use that setting.
2073   bool Unset;
2074   bool SpecifiedResult =
2075     Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
2076   if (!Unset)
2077     return SpecifiedResult;
2078 
2079   // Opt-out rules:
2080   // An attribute requires delayed parsing (LateParsed is on)
2081   if (Attribute.getValueAsBit("LateParsed"))
2082     return false;
2083   // An attribute has no GNU/CXX11 spelling
2084   if (!hasGNUorCXX11Spelling(Attribute))
2085     return false;
2086   // An attribute subject list has a subject that isn't covered by one of the
2087   // subject match rules or has no subjects at all.
2088   if (Attribute.isValueUnset("Subjects"))
2089     return false;
2090   const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
2091   std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2092   bool HasAtLeastOneValidSubject = false;
2093   for (const auto *Subject : Subjects) {
2094     if (!isSupportedPragmaClangAttributeSubject(*Subject))
2095       continue;
2096     if (!SubjectsToRules.contains(Subject))
2097       return false;
2098     HasAtLeastOneValidSubject = true;
2099   }
2100   return HasAtLeastOneValidSubject;
2101 }
2102 
2103 static std::string GenerateTestExpression(ArrayRef<Record *> LangOpts) {
2104   std::string Test;
2105 
2106   for (auto *E : LangOpts) {
2107     if (!Test.empty())
2108       Test += " || ";
2109 
2110     const StringRef Code = E->getValueAsString("CustomCode");
2111     if (!Code.empty()) {
2112       Test += "(";
2113       Test += Code;
2114       Test += ")";
2115       if (!E->getValueAsString("Name").empty()) {
2116         PrintWarning(
2117             E->getLoc(),
2118             "non-empty 'Name' field ignored because 'CustomCode' was supplied");
2119       }
2120     } else {
2121       Test += "LangOpts.";
2122       Test += E->getValueAsString("Name");
2123     }
2124   }
2125 
2126   if (Test.empty())
2127     return "true";
2128 
2129   return Test;
2130 }
2131 
2132 void
2133 PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2134                                                       raw_ostream &OS) {
2135   if (!isAttributedSupported(Attr) || Attr.isValueUnset("Subjects"))
2136     return;
2137   // Generate a function that constructs a set of matching rules that describe
2138   // to which declarations the attribute should apply to.
2139   OS << "void getPragmaAttributeMatchRules("
2140      << "llvm::SmallVectorImpl<std::pair<"
2141      << AttributeSubjectMatchRule::EnumName
2142      << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2143   const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2144   std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2145   for (const auto *Subject : Subjects) {
2146     if (!isSupportedPragmaClangAttributeSubject(*Subject))
2147       continue;
2148     auto It = SubjectsToRules.find(Subject);
2149     assert(It != SubjectsToRules.end() &&
2150            "This attribute is unsupported by #pragma clang attribute");
2151     for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2152       // The rule might be language specific, so only subtract it from the given
2153       // rules if the specific language options are specified.
2154       std::vector<Record *> LangOpts = Rule.getLangOpts();
2155       OS << "  MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
2156          << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2157          << "));\n";
2158     }
2159   }
2160   OS << "}\n\n";
2161 }
2162 
2163 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2164   // Generate routines that check the names of sub-rules.
2165   OS << "std::optional<attr::SubjectMatchRule> "
2166         "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2167   OS << "  return std::nullopt;\n";
2168   OS << "}\n\n";
2169 
2170   llvm::MapVector<const Record *, std::vector<AttributeSubjectMatchRule>>
2171       SubMatchRules;
2172   for (const auto &Rule : Rules) {
2173     if (!Rule.isSubRule())
2174       continue;
2175     SubMatchRules[Rule.MetaSubject].push_back(Rule);
2176   }
2177 
2178   for (const auto &SubMatchRule : SubMatchRules) {
2179     OS << "std::optional<attr::SubjectMatchRule> "
2180           "isAttributeSubjectMatchSubRuleFor_"
2181        << SubMatchRule.first->getValueAsString("Name")
2182        << "(StringRef Name, bool IsUnless) {\n";
2183     OS << "  if (IsUnless)\n";
2184     OS << "    return "
2185           "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2186     for (const auto &Rule : SubMatchRule.second) {
2187       if (Rule.isNegatedSubRule())
2188         OS << "    Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2189            << ").\n";
2190     }
2191     OS << "    Default(std::nullopt);\n";
2192     OS << "  return "
2193           "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2194     for (const auto &Rule : SubMatchRule.second) {
2195       if (!Rule.isNegatedSubRule())
2196         OS << "  Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2197            << ").\n";
2198     }
2199     OS << "  Default(std::nullopt);\n";
2200     OS << "}\n\n";
2201   }
2202 
2203   // Generate the function that checks for the top-level rules.
2204   OS << "std::pair<std::optional<attr::SubjectMatchRule>, "
2205         "std::optional<attr::SubjectMatchRule> (*)(StringRef, "
2206         "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2207   OS << "  return "
2208         "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, "
2209         "std::optional<attr::SubjectMatchRule> (*) (StringRef, "
2210         "bool)>>(Name).\n";
2211   for (const auto &Rule : Rules) {
2212     if (Rule.isSubRule())
2213       continue;
2214     std::string SubRuleFunction;
2215     if (SubMatchRules.count(Rule.MetaSubject))
2216       SubRuleFunction =
2217           ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2218     else
2219       SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2220     OS << "  Case(\"" << Rule.getName() << "\", std::make_pair("
2221        << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2222   }
2223   OS << "  Default(std::make_pair(std::nullopt, "
2224         "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2225   OS << "}\n\n";
2226 
2227   // Generate the function that checks for the submatch rules.
2228   OS << "const char *validAttributeSubjectMatchSubRules("
2229      << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2230   OS << "  switch (Rule) {\n";
2231   for (const auto &SubMatchRule : SubMatchRules) {
2232     OS << "  case "
2233        << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2234        << ":\n";
2235     OS << "  return \"'";
2236     bool IsFirst = true;
2237     for (const auto &Rule : SubMatchRule.second) {
2238       if (!IsFirst)
2239         OS << ", '";
2240       IsFirst = false;
2241       if (Rule.isNegatedSubRule())
2242         OS << "unless(";
2243       OS << Rule.getName();
2244       if (Rule.isNegatedSubRule())
2245         OS << ')';
2246       OS << "'";
2247     }
2248     OS << "\";\n";
2249   }
2250   OS << "  default: return nullptr;\n";
2251   OS << "  }\n";
2252   OS << "}\n\n";
2253 }
2254 
2255 template <typename Fn>
2256 static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2257   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2258   SmallDenseSet<StringRef, 8> Seen;
2259   for (const FlattenedSpelling &S : Spellings) {
2260     if (Seen.insert(S.name()).second)
2261       F(S);
2262   }
2263 }
2264 
2265 static bool isTypeArgument(const Record *Arg) {
2266   return !Arg->getSuperClasses().empty() &&
2267          Arg->getSuperClasses().back().first->getName() == "TypeArgument";
2268 }
2269 
2270 /// Emits the first-argument-is-type property for attributes.
2271 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2272   OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2273   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2274 
2275   for (const auto *Attr : Attrs) {
2276     // Determine whether the first argument is a type.
2277     std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2278     if (Args.empty())
2279       continue;
2280 
2281     if (!isTypeArgument(Args[0]))
2282       continue;
2283 
2284     // All these spellings take a single type argument.
2285     forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2286       OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2287     });
2288   }
2289   OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2290 }
2291 
2292 /// Emits the parse-arguments-in-unevaluated-context property for
2293 /// attributes.
2294 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2295   OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2296   ParsedAttrMap Attrs = getParsedAttrList(Records);
2297   for (const auto &I : Attrs) {
2298     const Record &Attr = *I.second;
2299 
2300     if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2301       continue;
2302 
2303     // All these spellings take are parsed unevaluated.
2304     forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2305       OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2306     });
2307   }
2308   OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2309 }
2310 
2311 static bool isIdentifierArgument(const Record *Arg) {
2312   return !Arg->getSuperClasses().empty() &&
2313     llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2314     .Case("IdentifierArgument", true)
2315     .Case("EnumArgument", true)
2316     .Case("VariadicEnumArgument", true)
2317     .Default(false);
2318 }
2319 
2320 static bool isVariadicIdentifierArgument(const Record *Arg) {
2321   return !Arg->getSuperClasses().empty() &&
2322          llvm::StringSwitch<bool>(
2323              Arg->getSuperClasses().back().first->getName())
2324              .Case("VariadicIdentifierArgument", true)
2325              .Case("VariadicParamOrParamIdxArgument", true)
2326              .Default(false);
2327 }
2328 
2329 static bool isVariadicExprArgument(const Record *Arg) {
2330   return !Arg->getSuperClasses().empty() &&
2331          llvm::StringSwitch<bool>(
2332              Arg->getSuperClasses().back().first->getName())
2333              .Case("VariadicExprArgument", true)
2334              .Default(false);
2335 }
2336 
2337 static bool isStringLiteralArgument(const Record *Arg) {
2338   return !Arg->getSuperClasses().empty() &&
2339          llvm::StringSwitch<bool>(
2340              Arg->getSuperClasses().back().first->getName())
2341              .Case("StringArgument", true)
2342              .Default(false);
2343 }
2344 
2345 static bool isVariadicStringLiteralArgument(const Record *Arg) {
2346   return !Arg->getSuperClasses().empty() &&
2347          llvm::StringSwitch<bool>(
2348              Arg->getSuperClasses().back().first->getName())
2349              .Case("VariadicStringArgument", true)
2350              .Default(false);
2351 }
2352 
2353 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2354                                                    raw_ostream &OS) {
2355   OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2356   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2357   for (const auto *A : Attrs) {
2358     // Determine whether the first argument is a variadic identifier.
2359     std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2360     if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2361       continue;
2362 
2363     // All these spellings take an identifier argument.
2364     forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2365       OS << ".Case(\"" << S.name() << "\", "
2366          << "true"
2367          << ")\n";
2368     });
2369   }
2370   OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2371 }
2372 
2373 // Emits the list of arguments that should be parsed as unevaluated string
2374 // literals for each attribute.
2375 static void emitClangAttrUnevaluatedStringLiteralList(RecordKeeper &Records,
2376                                                       raw_ostream &OS) {
2377   OS << "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
2378   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2379   for (const auto *Attr : Attrs) {
2380     std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2381     uint32_t Bits = 0;
2382     assert(Args.size() <= 32 && "unsupported number of arguments in attribute");
2383     for (uint32_t N = 0; N < Args.size(); ++N) {
2384       Bits |= (isStringLiteralArgument(Args[N]) << N);
2385       // If we have a variadic string argument, set all the remaining bits to 1
2386       if (isVariadicStringLiteralArgument(Args[N])) {
2387         Bits |= maskTrailingZeros<decltype(Bits)>(N);
2388         break;
2389       }
2390     }
2391     if (!Bits)
2392       continue;
2393     // All these spellings have at least one string literal has argument.
2394     forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2395       OS << ".Case(\"" << S.name() << "\", " << Bits << ")\n";
2396     });
2397   }
2398   OS << "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
2399 }
2400 
2401 // Emits the first-argument-is-identifier property for attributes.
2402 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2403   OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2404   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2405 
2406   for (const auto *Attr : Attrs) {
2407     // Determine whether the first argument is an identifier.
2408     std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2409     if (Args.empty() || !isIdentifierArgument(Args[0]))
2410       continue;
2411 
2412     // All these spellings take an identifier argument.
2413     forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2414       OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2415     });
2416   }
2417   OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2418 }
2419 
2420 static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2421   return !Arg->getSuperClasses().empty() &&
2422          llvm::StringSwitch<bool>(
2423              Arg->getSuperClasses().back().first->getName())
2424              .Case("VariadicParamOrParamIdxArgument", true)
2425              .Default(false);
2426 }
2427 
2428 static void emitClangAttrThisIsaIdentifierArgList(RecordKeeper &Records,
2429                                                   raw_ostream &OS) {
2430   OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2431   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2432   for (const auto *A : Attrs) {
2433     // Determine whether the first argument is a variadic identifier.
2434     std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2435     if (Args.empty() || !keywordThisIsaIdentifierInArgument(Args[0]))
2436       continue;
2437 
2438     // All these spellings take an identifier argument.
2439     forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2440       OS << ".Case(\"" << S.name() << "\", "
2441          << "true"
2442          << ")\n";
2443     });
2444   }
2445   OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2446 }
2447 
2448 static void emitClangAttrAcceptsExprPack(RecordKeeper &Records,
2449                                          raw_ostream &OS) {
2450   OS << "#if defined(CLANG_ATTR_ACCEPTS_EXPR_PACK)\n";
2451   ParsedAttrMap Attrs = getParsedAttrList(Records);
2452   for (const auto &I : Attrs) {
2453     const Record &Attr = *I.second;
2454 
2455     if (!Attr.getValueAsBit("AcceptsExprPack"))
2456       continue;
2457 
2458     forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2459       OS << ".Case(\"" << S.name() << "\", true)\n";
2460     });
2461   }
2462   OS << "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
2463 }
2464 
2465 static bool isRegularKeywordAttribute(const FlattenedSpelling &S) {
2466   return (S.variety() == "Keyword" &&
2467           !S.getSpellingRecord().getValueAsBit("HasOwnParseRules"));
2468 }
2469 
2470 static void emitFormInitializer(raw_ostream &OS,
2471                                 const FlattenedSpelling &Spelling,
2472                                 StringRef SpellingIndex) {
2473   bool IsAlignas =
2474       (Spelling.variety() == "Keyword" && Spelling.name() == "alignas");
2475   OS << "{AttributeCommonInfo::AS_" << Spelling.variety() << ", "
2476      << SpellingIndex << ", " << (IsAlignas ? "true" : "false")
2477      << " /*IsAlignas*/, "
2478      << (isRegularKeywordAttribute(Spelling) ? "true" : "false")
2479      << " /*IsRegularKeywordAttribute*/}";
2480 }
2481 
2482 static void emitAttributes(RecordKeeper &Records, raw_ostream &OS,
2483                            bool Header) {
2484   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2485   ParsedAttrMap AttrMap = getParsedAttrList(Records);
2486 
2487   // Helper to print the starting character of an attribute argument. If there
2488   // hasn't been an argument yet, it prints an opening parenthese; otherwise it
2489   // prints a comma.
2490   OS << "static inline void DelimitAttributeArgument("
2491      << "raw_ostream& OS, bool& IsFirst) {\n"
2492      << "  if (IsFirst) {\n"
2493      << "    IsFirst = false;\n"
2494      << "    OS << \"(\";\n"
2495      << "  } else\n"
2496      << "    OS << \", \";\n"
2497      << "}\n";
2498 
2499   for (const auto *Attr : Attrs) {
2500     const Record &R = *Attr;
2501 
2502     // FIXME: Currently, documentation is generated as-needed due to the fact
2503     // that there is no way to allow a generated project "reach into" the docs
2504     // directory (for instance, it may be an out-of-tree build). However, we want
2505     // to ensure that every attribute has a Documentation field, and produce an
2506     // error if it has been neglected. Otherwise, the on-demand generation which
2507     // happens server-side will fail. This code is ensuring that functionality,
2508     // even though this Emitter doesn't technically need the documentation.
2509     // When attribute documentation can be generated as part of the build
2510     // itself, this code can be removed.
2511     (void)R.getValueAsListOfDefs("Documentation");
2512 
2513     if (!R.getValueAsBit("ASTNode"))
2514       continue;
2515 
2516     ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
2517     assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2518     std::string SuperName;
2519     bool Inheritable = false;
2520     for (const auto &Super : llvm::reverse(Supers)) {
2521       const Record *R = Super.first;
2522       if (R->getName() != "TargetSpecificAttr" &&
2523           R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2524         SuperName = std::string(R->getName());
2525       if (R->getName() == "InheritableAttr")
2526         Inheritable = true;
2527     }
2528 
2529     if (Header)
2530       OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2531     else
2532       OS << "\n// " << R.getName() << "Attr implementation\n\n";
2533 
2534     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2535     std::vector<std::unique_ptr<Argument>> Args;
2536     Args.reserve(ArgRecords.size());
2537 
2538     bool AttrAcceptsExprPack = Attr->getValueAsBit("AcceptsExprPack");
2539     if (AttrAcceptsExprPack) {
2540       for (size_t I = 0; I < ArgRecords.size(); ++I) {
2541         const Record *ArgR = ArgRecords[I];
2542         if (isIdentifierArgument(ArgR) || isVariadicIdentifierArgument(ArgR) ||
2543             isTypeArgument(ArgR))
2544           PrintFatalError(Attr->getLoc(),
2545                           "Attributes accepting packs cannot also "
2546                           "have identifier or type arguments.");
2547         // When trying to determine if value-dependent expressions can populate
2548         // the attribute without prior instantiation, the decision is made based
2549         // on the assumption that only the last argument is ever variadic.
2550         if (I < (ArgRecords.size() - 1) && isVariadicExprArgument(ArgR))
2551           PrintFatalError(Attr->getLoc(),
2552                           "Attributes accepting packs can only have the last "
2553                           "argument be variadic.");
2554       }
2555     }
2556 
2557     bool HasOptArg = false;
2558     bool HasFakeArg = false;
2559     for (const auto *ArgRecord : ArgRecords) {
2560       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2561       if (Header) {
2562         Args.back()->writeDeclarations(OS);
2563         OS << "\n\n";
2564       }
2565 
2566       // For these purposes, fake takes priority over optional.
2567       if (Args.back()->isFake()) {
2568         HasFakeArg = true;
2569       } else if (Args.back()->isOptional()) {
2570         HasOptArg = true;
2571       }
2572     }
2573 
2574     std::unique_ptr<VariadicExprArgument> DelayedArgs = nullptr;
2575     if (AttrAcceptsExprPack) {
2576       DelayedArgs =
2577           std::make_unique<VariadicExprArgument>("DelayedArgs", R.getName());
2578       if (Header) {
2579         DelayedArgs->writeDeclarations(OS);
2580         OS << "\n\n";
2581       }
2582     }
2583 
2584     if (Header)
2585       OS << "public:\n";
2586 
2587     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2588 
2589     // If there are zero or one spellings, all spelling-related functionality
2590     // can be elided. If all of the spellings share the same name, the spelling
2591     // functionality can also be elided.
2592     bool ElideSpelling = (Spellings.size() <= 1) ||
2593                          SpellingNamesAreCommon(Spellings);
2594 
2595     // This maps spelling index values to semantic Spelling enumerants.
2596     SemanticSpellingMap SemanticToSyntacticMap;
2597 
2598     std::string SpellingEnum;
2599     if (Spellings.size() > 1)
2600       SpellingEnum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2601     if (Header)
2602       OS << SpellingEnum;
2603 
2604     const auto &ParsedAttrSpellingItr = llvm::find_if(
2605         AttrMap, [R](const std::pair<std::string, const Record *> &P) {
2606           return &R == P.second;
2607         });
2608 
2609     // Emit CreateImplicit factory methods.
2610     auto emitCreate = [&](bool Implicit, bool DelayedArgsOnly, bool emitFake) {
2611       if (Header)
2612         OS << "  static ";
2613       OS << R.getName() << "Attr *";
2614       if (!Header)
2615         OS << R.getName() << "Attr::";
2616       OS << "Create";
2617       if (Implicit)
2618         OS << "Implicit";
2619       if (DelayedArgsOnly)
2620         OS << "WithDelayedArgs";
2621       OS << "(";
2622       OS << "ASTContext &Ctx";
2623       if (!DelayedArgsOnly) {
2624         for (auto const &ai : Args) {
2625           if (ai->isFake() && !emitFake)
2626             continue;
2627           OS << ", ";
2628           ai->writeCtorParameters(OS);
2629         }
2630       } else {
2631         OS << ", ";
2632         DelayedArgs->writeCtorParameters(OS);
2633       }
2634       OS << ", const AttributeCommonInfo &CommonInfo";
2635       OS << ")";
2636       if (Header) {
2637         OS << ";\n";
2638         return;
2639       }
2640 
2641       OS << " {\n";
2642       OS << "  auto *A = new (Ctx) " << R.getName();
2643       OS << "Attr(Ctx, CommonInfo";
2644 
2645       if (!DelayedArgsOnly) {
2646         for (auto const &ai : Args) {
2647           if (ai->isFake() && !emitFake)
2648             continue;
2649           OS << ", ";
2650           ai->writeImplicitCtorArgs(OS);
2651         }
2652       }
2653       OS << ");\n";
2654       if (Implicit) {
2655         OS << "  A->setImplicit(true);\n";
2656       }
2657       if (Implicit || ElideSpelling) {
2658         OS << "  if (!A->isAttributeSpellingListCalculated() && "
2659               "!A->getAttrName())\n";
2660         OS << "    A->setAttributeSpellingListIndex(0);\n";
2661       }
2662       if (DelayedArgsOnly) {
2663         OS << "  A->setDelayedArgs(Ctx, ";
2664         DelayedArgs->writeImplicitCtorArgs(OS);
2665         OS << ");\n";
2666       }
2667       OS << "  return A;\n}\n\n";
2668     };
2669 
2670     auto emitCreateNoCI = [&](bool Implicit, bool DelayedArgsOnly,
2671                               bool emitFake) {
2672       if (Header)
2673         OS << "  static ";
2674       OS << R.getName() << "Attr *";
2675       if (!Header)
2676         OS << R.getName() << "Attr::";
2677       OS << "Create";
2678       if (Implicit)
2679         OS << "Implicit";
2680       if (DelayedArgsOnly)
2681         OS << "WithDelayedArgs";
2682       OS << "(";
2683       OS << "ASTContext &Ctx";
2684       if (!DelayedArgsOnly) {
2685         for (auto const &ai : Args) {
2686           if (ai->isFake() && !emitFake)
2687             continue;
2688           OS << ", ";
2689           ai->writeCtorParameters(OS);
2690         }
2691       } else {
2692         OS << ", ";
2693         DelayedArgs->writeCtorParameters(OS);
2694       }
2695       OS << ", SourceRange Range";
2696       if (Header)
2697         OS << " = {}";
2698       if (Spellings.size() > 1) {
2699         OS << ", Spelling S";
2700         if (Header)
2701           OS << " = " << SemanticToSyntacticMap[0];
2702       }
2703       OS << ")";
2704       if (Header) {
2705         OS << ";\n";
2706         return;
2707       }
2708 
2709       OS << " {\n";
2710       OS << "  AttributeCommonInfo I(Range, ";
2711 
2712       if (ParsedAttrSpellingItr != std::end(AttrMap))
2713         OS << "AT_" << ParsedAttrSpellingItr->first;
2714       else
2715         OS << "NoSemaHandlerAttribute";
2716 
2717       if (Spellings.size() == 0) {
2718         OS << ", AttributeCommonInfo::Form::Implicit()";
2719       } else if (Spellings.size() == 1) {
2720         OS << ", ";
2721         emitFormInitializer(OS, Spellings[0], "0");
2722       } else {
2723         OS << ", [&]() {\n";
2724         OS << "    switch (S) {\n";
2725         std::set<std::string> Uniques;
2726         unsigned Idx = 0;
2727         for (auto I = Spellings.begin(), E = Spellings.end(); I != E;
2728              ++I, ++Idx) {
2729           const FlattenedSpelling &S = *I;
2730           const auto &Name = SemanticToSyntacticMap[Idx];
2731           if (Uniques.insert(Name).second) {
2732             OS << "    case " << Name << ":\n";
2733             OS << "      return AttributeCommonInfo::Form";
2734             emitFormInitializer(OS, S, Name);
2735             OS << ";\n";
2736           }
2737         }
2738         OS << "    default:\n";
2739         OS << "      llvm_unreachable(\"Unknown attribute spelling!\");\n"
2740            << "      return AttributeCommonInfo::Form";
2741         emitFormInitializer(OS, Spellings[0], "0");
2742         OS << ";\n"
2743            << "    }\n"
2744            << "  }()";
2745       }
2746 
2747       OS << ");\n";
2748       OS << "  return Create";
2749       if (Implicit)
2750         OS << "Implicit";
2751       if (DelayedArgsOnly)
2752         OS << "WithDelayedArgs";
2753       OS << "(Ctx";
2754       if (!DelayedArgsOnly) {
2755         for (auto const &ai : Args) {
2756           if (ai->isFake() && !emitFake)
2757             continue;
2758           OS << ", ";
2759           ai->writeImplicitCtorArgs(OS);
2760         }
2761       } else {
2762         OS << ", ";
2763         DelayedArgs->writeImplicitCtorArgs(OS);
2764       }
2765       OS << ", I);\n";
2766       OS << "}\n\n";
2767     };
2768 
2769     auto emitCreates = [&](bool DelayedArgsOnly, bool emitFake) {
2770       emitCreate(true, DelayedArgsOnly, emitFake);
2771       emitCreate(false, DelayedArgsOnly, emitFake);
2772       emitCreateNoCI(true, DelayedArgsOnly, emitFake);
2773       emitCreateNoCI(false, DelayedArgsOnly, emitFake);
2774     };
2775 
2776     if (Header)
2777       OS << "  // Factory methods\n";
2778 
2779     // Emit a CreateImplicit that takes all the arguments.
2780     emitCreates(false, true);
2781 
2782     // Emit a CreateImplicit that takes all the non-fake arguments.
2783     if (HasFakeArg)
2784       emitCreates(false, false);
2785 
2786     // Emit a CreateWithDelayedArgs that takes only the dependent argument
2787     // expressions.
2788     if (DelayedArgs)
2789       emitCreates(true, false);
2790 
2791     // Emit constructors.
2792     auto emitCtor = [&](bool emitOpt, bool emitFake, bool emitNoArgs) {
2793       auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2794         if (emitNoArgs)
2795           return false;
2796         if (arg->isFake())
2797           return emitFake;
2798         if (arg->isOptional())
2799           return emitOpt;
2800         return true;
2801       };
2802       if (Header)
2803         OS << "  ";
2804       else
2805         OS << R.getName() << "Attr::";
2806       OS << R.getName()
2807          << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2808       OS << '\n';
2809       for (auto const &ai : Args) {
2810         if (!shouldEmitArg(ai))
2811           continue;
2812         OS << "              , ";
2813         ai->writeCtorParameters(OS);
2814         OS << "\n";
2815       }
2816 
2817       OS << "             )";
2818       if (Header) {
2819         OS << ";\n";
2820         return;
2821       }
2822       OS << "\n  : " << SuperName << "(Ctx, CommonInfo, ";
2823       OS << "attr::" << R.getName() << ", "
2824          << (R.getValueAsBit("LateParsed") ? "true" : "false");
2825       if (Inheritable) {
2826         OS << ", "
2827            << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2828                                                               : "false");
2829       }
2830       OS << ")\n";
2831 
2832       for (auto const &ai : Args) {
2833         OS << "              , ";
2834         if (!shouldEmitArg(ai)) {
2835           ai->writeCtorDefaultInitializers(OS);
2836         } else {
2837           ai->writeCtorInitializers(OS);
2838         }
2839         OS << "\n";
2840       }
2841       if (DelayedArgs) {
2842         OS << "              , ";
2843         DelayedArgs->writeCtorDefaultInitializers(OS);
2844         OS << "\n";
2845       }
2846 
2847       OS << "  {\n";
2848 
2849       for (auto const &ai : Args) {
2850         if (!shouldEmitArg(ai))
2851           continue;
2852         ai->writeCtorBody(OS);
2853       }
2854       OS << "}\n\n";
2855     };
2856 
2857     if (Header)
2858       OS << "\n  // Constructors\n";
2859 
2860     // Emit a constructor that includes all the arguments.
2861     // This is necessary for cloning.
2862     emitCtor(true, true, false);
2863 
2864     // Emit a constructor that takes all the non-fake arguments.
2865     if (HasFakeArg)
2866       emitCtor(true, false, false);
2867 
2868     // Emit a constructor that takes all the non-fake, non-optional arguments.
2869     if (HasOptArg)
2870       emitCtor(false, false, false);
2871 
2872     // Emit constructors that takes no arguments if none already exists.
2873     // This is used for delaying arguments.
2874     bool HasRequiredArgs =
2875         llvm::count_if(Args, [=](const std::unique_ptr<Argument> &arg) {
2876           return !arg->isFake() && !arg->isOptional();
2877         });
2878     if (DelayedArgs && HasRequiredArgs)
2879       emitCtor(false, false, true);
2880 
2881     if (Header) {
2882       OS << '\n';
2883       OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2884       OS << "  void printPretty(raw_ostream &OS,\n"
2885          << "                   const PrintingPolicy &Policy) const;\n";
2886       OS << "  const char *getSpelling() const;\n";
2887     }
2888 
2889     if (!ElideSpelling) {
2890       assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2891       if (Header)
2892         OS << "  Spelling getSemanticSpelling() const;\n";
2893       else {
2894         OS << R.getName() << "Attr::Spelling " << R.getName()
2895            << "Attr::getSemanticSpelling() const {\n";
2896         WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2897                                     SemanticToSyntacticMap, OS);
2898         OS << "}\n";
2899       }
2900     }
2901 
2902     if (Header)
2903       writeAttrAccessorDefinition(R, OS);
2904 
2905     for (auto const &ai : Args) {
2906       if (Header) {
2907         ai->writeAccessors(OS);
2908       } else {
2909         ai->writeAccessorDefinitions(OS);
2910       }
2911       OS << "\n\n";
2912 
2913       // Don't write conversion routines for fake arguments.
2914       if (ai->isFake()) continue;
2915 
2916       if (ai->isEnumArg())
2917         static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
2918                                                                      Header);
2919       else if (ai->isVariadicEnumArg())
2920         static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
2921             OS, Header);
2922     }
2923 
2924     if (Header) {
2925       if (DelayedArgs) {
2926         DelayedArgs->writeAccessors(OS);
2927         DelayedArgs->writeSetter(OS);
2928       }
2929 
2930       OS << R.getValueAsString("AdditionalMembers");
2931       OS << "\n\n";
2932 
2933       OS << "  static bool classof(const Attr *A) { return A->getKind() == "
2934          << "attr::" << R.getName() << "; }\n";
2935 
2936       OS << "};\n\n";
2937     } else {
2938       if (DelayedArgs)
2939         DelayedArgs->writeAccessorDefinitions(OS);
2940 
2941       OS << R.getName() << "Attr *" << R.getName()
2942          << "Attr::clone(ASTContext &C) const {\n";
2943       OS << "  auto *A = new (C) " << R.getName() << "Attr(C, *this";
2944       for (auto const &ai : Args) {
2945         OS << ", ";
2946         ai->writeCloneArgs(OS);
2947       }
2948       OS << ");\n";
2949       OS << "  A->Inherited = Inherited;\n";
2950       OS << "  A->IsPackExpansion = IsPackExpansion;\n";
2951       OS << "  A->setImplicit(Implicit);\n";
2952       if (DelayedArgs) {
2953         OS << "  A->setDelayedArgs(C, ";
2954         DelayedArgs->writeCloneArgs(OS);
2955         OS << ");\n";
2956       }
2957       OS << "  return A;\n}\n\n";
2958 
2959       writePrettyPrintFunction(R, Args, OS);
2960       writeGetSpellingFunction(R, OS);
2961     }
2962   }
2963 }
2964 // Emits the class definitions for attributes.
2965 void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2966   emitSourceFileHeader("Attribute classes' definitions", OS, Records);
2967 
2968   OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2969   OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2970 
2971   emitAttributes(Records, OS, true);
2972 
2973   OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2974 }
2975 
2976 // Emits the class method definitions for attributes.
2977 void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2978   emitSourceFileHeader("Attribute classes' member function definitions", OS,
2979                        Records);
2980 
2981   emitAttributes(Records, OS, false);
2982 
2983   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2984 
2985   // Instead of relying on virtual dispatch we just create a huge dispatch
2986   // switch. This is both smaller and faster than virtual functions.
2987   auto EmitFunc = [&](const char *Method) {
2988     OS << "  switch (getKind()) {\n";
2989     for (const auto *Attr : Attrs) {
2990       const Record &R = *Attr;
2991       if (!R.getValueAsBit("ASTNode"))
2992         continue;
2993 
2994       OS << "  case attr::" << R.getName() << ":\n";
2995       OS << "    return cast<" << R.getName() << "Attr>(this)->" << Method
2996          << ";\n";
2997     }
2998     OS << "  }\n";
2999     OS << "  llvm_unreachable(\"Unexpected attribute kind!\");\n";
3000     OS << "}\n\n";
3001   };
3002 
3003   OS << "const char *Attr::getSpelling() const {\n";
3004   EmitFunc("getSpelling()");
3005 
3006   OS << "Attr *Attr::clone(ASTContext &C) const {\n";
3007   EmitFunc("clone(C)");
3008 
3009   OS << "void Attr::printPretty(raw_ostream &OS, "
3010         "const PrintingPolicy &Policy) const {\n";
3011   EmitFunc("printPretty(OS, Policy)");
3012 }
3013 
3014 static void emitAttrList(raw_ostream &OS, StringRef Class,
3015                          const std::vector<Record*> &AttrList) {
3016   for (auto Cur : AttrList) {
3017     OS << Class << "(" << Cur->getName() << ")\n";
3018   }
3019 }
3020 
3021 // Determines if an attribute has a Pragma spelling.
3022 static bool AttrHasPragmaSpelling(const Record *R) {
3023   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3024   return llvm::any_of(Spellings, [](const FlattenedSpelling &S) {
3025     return S.variety() == "Pragma";
3026   });
3027 }
3028 
3029 namespace {
3030 
3031   struct AttrClassDescriptor {
3032     const char * const MacroName;
3033     const char * const TableGenName;
3034   };
3035 
3036 } // end anonymous namespace
3037 
3038 static const AttrClassDescriptor AttrClassDescriptors[] = {
3039   { "ATTR", "Attr" },
3040   { "TYPE_ATTR", "TypeAttr" },
3041   { "STMT_ATTR", "StmtAttr" },
3042   { "DECL_OR_STMT_ATTR", "DeclOrStmtAttr" },
3043   { "INHERITABLE_ATTR", "InheritableAttr" },
3044   { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
3045   { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
3046   { "PARAMETER_ABI_ATTR", "ParameterABIAttr" },
3047   { "HLSL_ANNOTATION_ATTR", "HLSLAnnotationAttr"}
3048 };
3049 
3050 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
3051                               const char *superName) {
3052   OS << "#ifndef " << name << "\n";
3053   OS << "#define " << name << "(NAME) ";
3054   if (superName) OS << superName << "(NAME)";
3055   OS << "\n#endif\n\n";
3056 }
3057 
3058 namespace {
3059 
3060   /// A class of attributes.
3061   struct AttrClass {
3062     const AttrClassDescriptor &Descriptor;
3063     Record *TheRecord;
3064     AttrClass *SuperClass = nullptr;
3065     std::vector<AttrClass*> SubClasses;
3066     std::vector<Record*> Attrs;
3067 
3068     AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
3069       : Descriptor(Descriptor), TheRecord(R) {}
3070 
3071     void emitDefaultDefines(raw_ostream &OS) const {
3072       // Default the macro unless this is a root class (i.e. Attr).
3073       if (SuperClass) {
3074         emitDefaultDefine(OS, Descriptor.MacroName,
3075                           SuperClass->Descriptor.MacroName);
3076       }
3077     }
3078 
3079     void emitUndefs(raw_ostream &OS) const {
3080       OS << "#undef " << Descriptor.MacroName << "\n";
3081     }
3082 
3083     void emitAttrList(raw_ostream &OS) const {
3084       for (auto SubClass : SubClasses) {
3085         SubClass->emitAttrList(OS);
3086       }
3087 
3088       ::emitAttrList(OS, Descriptor.MacroName, Attrs);
3089     }
3090 
3091     void classifyAttrOnRoot(Record *Attr) {
3092       bool result = classifyAttr(Attr);
3093       assert(result && "failed to classify on root"); (void) result;
3094     }
3095 
3096     void emitAttrRange(raw_ostream &OS) const {
3097       OS << "ATTR_RANGE(" << Descriptor.TableGenName
3098          << ", " << getFirstAttr()->getName()
3099          << ", " << getLastAttr()->getName() << ")\n";
3100     }
3101 
3102   private:
3103     bool classifyAttr(Record *Attr) {
3104       // Check all the subclasses.
3105       for (auto SubClass : SubClasses) {
3106         if (SubClass->classifyAttr(Attr))
3107           return true;
3108       }
3109 
3110       // It's not more specific than this class, but it might still belong here.
3111       if (Attr->isSubClassOf(TheRecord)) {
3112         Attrs.push_back(Attr);
3113         return true;
3114       }
3115 
3116       return false;
3117     }
3118 
3119     Record *getFirstAttr() const {
3120       if (!SubClasses.empty())
3121         return SubClasses.front()->getFirstAttr();
3122       return Attrs.front();
3123     }
3124 
3125     Record *getLastAttr() const {
3126       if (!Attrs.empty())
3127         return Attrs.back();
3128       return SubClasses.back()->getLastAttr();
3129     }
3130   };
3131 
3132   /// The entire hierarchy of attribute classes.
3133   class AttrClassHierarchy {
3134     std::vector<std::unique_ptr<AttrClass>> Classes;
3135 
3136   public:
3137     AttrClassHierarchy(RecordKeeper &Records) {
3138       // Find records for all the classes.
3139       for (auto &Descriptor : AttrClassDescriptors) {
3140         Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
3141         AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
3142         Classes.emplace_back(Class);
3143       }
3144 
3145       // Link up the hierarchy.
3146       for (auto &Class : Classes) {
3147         if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
3148           Class->SuperClass = SuperClass;
3149           SuperClass->SubClasses.push_back(Class.get());
3150         }
3151       }
3152 
3153 #ifndef NDEBUG
3154       for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
3155         assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
3156                "only the first class should be a root class!");
3157       }
3158 #endif
3159     }
3160 
3161     void emitDefaultDefines(raw_ostream &OS) const {
3162       for (auto &Class : Classes) {
3163         Class->emitDefaultDefines(OS);
3164       }
3165     }
3166 
3167     void emitUndefs(raw_ostream &OS) const {
3168       for (auto &Class : Classes) {
3169         Class->emitUndefs(OS);
3170       }
3171     }
3172 
3173     void emitAttrLists(raw_ostream &OS) const {
3174       // Just start from the root class.
3175       Classes[0]->emitAttrList(OS);
3176     }
3177 
3178     void emitAttrRanges(raw_ostream &OS) const {
3179       for (auto &Class : Classes)
3180         Class->emitAttrRange(OS);
3181     }
3182 
3183     void classifyAttr(Record *Attr) {
3184       // Add the attribute to the root class.
3185       Classes[0]->classifyAttrOnRoot(Attr);
3186     }
3187 
3188   private:
3189     AttrClass *findClassByRecord(Record *R) const {
3190       for (auto &Class : Classes) {
3191         if (Class->TheRecord == R)
3192           return Class.get();
3193       }
3194       return nullptr;
3195     }
3196 
3197     AttrClass *findSuperClass(Record *R) const {
3198       // TableGen flattens the superclass list, so we just need to walk it
3199       // in reverse.
3200       auto SuperClasses = R->getSuperClasses();
3201       for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
3202         auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
3203         if (SuperClass) return SuperClass;
3204       }
3205       return nullptr;
3206     }
3207   };
3208 
3209 } // end anonymous namespace
3210 
3211 namespace clang {
3212 
3213 // Emits the enumeration list for attributes.
3214 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
3215   emitSourceFileHeader("List of all attributes that Clang recognizes", OS,
3216                        Records);
3217 
3218   AttrClassHierarchy Hierarchy(Records);
3219 
3220   // Add defaulting macro definitions.
3221   Hierarchy.emitDefaultDefines(OS);
3222   emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
3223 
3224   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3225   std::vector<Record *> PragmaAttrs;
3226   for (auto *Attr : Attrs) {
3227     if (!Attr->getValueAsBit("ASTNode"))
3228       continue;
3229 
3230     // Add the attribute to the ad-hoc groups.
3231     if (AttrHasPragmaSpelling(Attr))
3232       PragmaAttrs.push_back(Attr);
3233 
3234     // Place it in the hierarchy.
3235     Hierarchy.classifyAttr(Attr);
3236   }
3237 
3238   // Emit the main attribute list.
3239   Hierarchy.emitAttrLists(OS);
3240 
3241   // Emit the ad hoc groups.
3242   emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
3243 
3244   // Emit the attribute ranges.
3245   OS << "#ifdef ATTR_RANGE\n";
3246   Hierarchy.emitAttrRanges(OS);
3247   OS << "#undef ATTR_RANGE\n";
3248   OS << "#endif\n";
3249 
3250   Hierarchy.emitUndefs(OS);
3251   OS << "#undef PRAGMA_SPELLING_ATTR\n";
3252 }
3253 
3254 // Emits the enumeration list for attributes.
3255 void EmitClangAttrPrintList(const std::string &FieldName, RecordKeeper &Records,
3256                             raw_ostream &OS) {
3257   emitSourceFileHeader(
3258       "List of attributes that can be print on the left side of a decl", OS,
3259       Records);
3260 
3261   AttrClassHierarchy Hierarchy(Records);
3262 
3263   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3264   std::vector<Record *> PragmaAttrs;
3265   bool first = false;
3266 
3267   for (auto *Attr : Attrs) {
3268     if (!Attr->getValueAsBit("ASTNode"))
3269       continue;
3270 
3271     if (!Attr->getValueAsBit(FieldName))
3272       continue;
3273 
3274     if (!first) {
3275       first = true;
3276       OS << "#define CLANG_ATTR_LIST_" << FieldName;
3277     }
3278 
3279     OS << " \\\n case attr::" << Attr->getName() << ":";
3280   }
3281 
3282   OS << '\n';
3283 }
3284 
3285 // Emits the enumeration list for attributes.
3286 void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
3287   emitSourceFileHeader(
3288       "List of all attribute subject matching rules that Clang recognizes", OS,
3289       Records);
3290   PragmaClangAttributeSupport &PragmaAttributeSupport =
3291       getPragmaAttributeSupport(Records);
3292   emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
3293   PragmaAttributeSupport.emitMatchRuleList(OS);
3294   OS << "#undef ATTR_MATCH_RULE\n";
3295 }
3296 
3297 // Emits the code to read an attribute from a precompiled header.
3298 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
3299   emitSourceFileHeader("Attribute deserialization code", OS, Records);
3300 
3301   Record *InhClass = Records.getClass("InheritableAttr");
3302   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
3303                        ArgRecords;
3304   std::vector<std::unique_ptr<Argument>> Args;
3305   std::unique_ptr<VariadicExprArgument> DelayedArgs;
3306 
3307   OS << "  switch (Kind) {\n";
3308   for (const auto *Attr : Attrs) {
3309     const Record &R = *Attr;
3310     if (!R.getValueAsBit("ASTNode"))
3311       continue;
3312 
3313     OS << "  case attr::" << R.getName() << ": {\n";
3314     if (R.isSubClassOf(InhClass))
3315       OS << "    bool isInherited = Record.readInt();\n";
3316     OS << "    bool isImplicit = Record.readInt();\n";
3317     OS << "    bool isPackExpansion = Record.readInt();\n";
3318     DelayedArgs = nullptr;
3319     if (Attr->getValueAsBit("AcceptsExprPack")) {
3320       DelayedArgs =
3321           std::make_unique<VariadicExprArgument>("DelayedArgs", R.getName());
3322       DelayedArgs->writePCHReadDecls(OS);
3323     }
3324     ArgRecords = R.getValueAsListOfDefs("Args");
3325     Args.clear();
3326     for (const auto *Arg : ArgRecords) {
3327       Args.emplace_back(createArgument(*Arg, R.getName()));
3328       Args.back()->writePCHReadDecls(OS);
3329     }
3330     OS << "    New = new (Context) " << R.getName() << "Attr(Context, Info";
3331     for (auto const &ri : Args) {
3332       OS << ", ";
3333       ri->writePCHReadArgs(OS);
3334     }
3335     OS << ");\n";
3336     if (R.isSubClassOf(InhClass))
3337       OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
3338     OS << "    New->setImplicit(isImplicit);\n";
3339     OS << "    New->setPackExpansion(isPackExpansion);\n";
3340     if (DelayedArgs) {
3341       OS << "    cast<" << R.getName()
3342          << "Attr>(New)->setDelayedArgs(Context, ";
3343       DelayedArgs->writePCHReadArgs(OS);
3344       OS << ");\n";
3345     }
3346     OS << "    break;\n";
3347     OS << "  }\n";
3348   }
3349   OS << "  }\n";
3350 }
3351 
3352 // Emits the code to write an attribute to a precompiled header.
3353 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
3354   emitSourceFileHeader("Attribute serialization code", OS, Records);
3355 
3356   Record *InhClass = Records.getClass("InheritableAttr");
3357   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3358 
3359   OS << "  switch (A->getKind()) {\n";
3360   for (const auto *Attr : Attrs) {
3361     const Record &R = *Attr;
3362     if (!R.getValueAsBit("ASTNode"))
3363       continue;
3364     OS << "  case attr::" << R.getName() << ": {\n";
3365     Args = R.getValueAsListOfDefs("Args");
3366     if (R.isSubClassOf(InhClass) || !Args.empty())
3367       OS << "    const auto *SA = cast<" << R.getName()
3368          << "Attr>(A);\n";
3369     if (R.isSubClassOf(InhClass))
3370       OS << "    Record.push_back(SA->isInherited());\n";
3371     OS << "    Record.push_back(A->isImplicit());\n";
3372     OS << "    Record.push_back(A->isPackExpansion());\n";
3373     if (Attr->getValueAsBit("AcceptsExprPack"))
3374       VariadicExprArgument("DelayedArgs", R.getName()).writePCHWrite(OS);
3375 
3376     for (const auto *Arg : Args)
3377       createArgument(*Arg, R.getName())->writePCHWrite(OS);
3378     OS << "    break;\n";
3379     OS << "  }\n";
3380   }
3381   OS << "  }\n";
3382 }
3383 
3384 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
3385 // parameter with only a single check type, if applicable.
3386 static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
3387                                             std::string *FnName,
3388                                             StringRef ListName,
3389                                             StringRef CheckAgainst,
3390                                             StringRef Scope) {
3391   if (!R->isValueUnset(ListName)) {
3392     Test += " && (";
3393     std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
3394     for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
3395       StringRef Part = *I;
3396       Test += CheckAgainst;
3397       Test += " == ";
3398       Test += Scope;
3399       Test += Part;
3400       if (I + 1 != E)
3401         Test += " || ";
3402       if (FnName)
3403         *FnName += Part;
3404     }
3405     Test += ")";
3406     return true;
3407   }
3408   return false;
3409 }
3410 
3411 // Generate a conditional expression to check if the current target satisfies
3412 // the conditions for a TargetSpecificAttr record, and append the code for
3413 // those checks to the Test string. If the FnName string pointer is non-null,
3414 // append a unique suffix to distinguish this set of target checks from other
3415 // TargetSpecificAttr records.
3416 static bool GenerateTargetSpecificAttrChecks(const Record *R,
3417                                              std::vector<StringRef> &Arches,
3418                                              std::string &Test,
3419                                              std::string *FnName) {
3420   bool AnyTargetChecks = false;
3421 
3422   // It is assumed that there will be an llvm::Triple object
3423   // named "T" and a TargetInfo object named "Target" within
3424   // scope that can be used to determine whether the attribute exists in
3425   // a given target.
3426   Test += "true";
3427   // If one or more architectures is specified, check those.  Arches are handled
3428   // differently because GenerateTargetRequirements needs to combine the list
3429   // with ParseKind.
3430   if (!Arches.empty()) {
3431     AnyTargetChecks = true;
3432     Test += " && (";
3433     for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3434       StringRef Part = *I;
3435       Test += "T.getArch() == llvm::Triple::";
3436       Test += Part;
3437       if (I + 1 != E)
3438         Test += " || ";
3439       if (FnName)
3440         *FnName += Part;
3441     }
3442     Test += ")";
3443   }
3444 
3445   // If the attribute is specific to particular OSes, check those.
3446   AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3447       R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
3448 
3449   // If one or more object formats is specified, check those.
3450   AnyTargetChecks |=
3451       GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
3452                                       "T.getObjectFormat()", "llvm::Triple::");
3453 
3454   // If custom code is specified, emit it.
3455   StringRef Code = R->getValueAsString("CustomCode");
3456   if (!Code.empty()) {
3457     AnyTargetChecks = true;
3458     Test += " && (";
3459     Test += Code;
3460     Test += ")";
3461   }
3462 
3463   return AnyTargetChecks;
3464 }
3465 
3466 static void GenerateHasAttrSpellingStringSwitch(
3467     const std::vector<std::pair<const Record *, FlattenedSpelling>> &Attrs,
3468     raw_ostream &OS, const std::string &Variety,
3469     const std::string &Scope = "") {
3470   for (const auto &[Attr, Spelling] : Attrs) {
3471     // C++11-style attributes have specific version information associated with
3472     // them. If the attribute has no scope, the version information must not
3473     // have the default value (1), as that's incorrect. Instead, the unscoped
3474     // attribute version information should be taken from the SD-6 standing
3475     // document, which can be found at:
3476     // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3477     //
3478     // C23-style attributes have the same kind of version information
3479     // associated with them. The unscoped attribute version information should
3480     // be taken from the specification of the attribute in the C Standard.
3481     //
3482     // Clang-specific attributes have the same kind of version information
3483     // associated with them. This version is typically the default value (1).
3484     // These version values are clang-specific and should typically be
3485     // incremented once the attribute changes its syntax and/or semantics in a
3486     // a way that is impactful to the end user.
3487     int Version = 1;
3488 
3489     assert(Spelling.variety() == Variety);
3490     std::string Name = "";
3491     if (Spelling.nameSpace().empty() || Scope == Spelling.nameSpace()) {
3492       Name = Spelling.name();
3493       Version = static_cast<int>(
3494           Spelling.getSpellingRecord().getValueAsInt("Version"));
3495       // Verify that explicitly specified CXX11 and C23 spellings (i.e.
3496       // not inferred from Clang/GCC spellings) have a version that's
3497       // different from the default (1).
3498       bool RequiresValidVersion =
3499           (Variety == "CXX11" || Variety == "C23") &&
3500           Spelling.getSpellingRecord().getValueAsString("Variety") == Variety;
3501       if (RequiresValidVersion && Scope.empty() && Version == 1)
3502         PrintError(Spelling.getSpellingRecord().getLoc(),
3503                    "Standard attributes must have "
3504                    "valid version information.");
3505     }
3506 
3507     std::string Test;
3508     if (Attr->isSubClassOf("TargetSpecificAttr")) {
3509       const Record *R = Attr->getValueAsDef("Target");
3510       std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3511       GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
3512 
3513       // If this is the C++11 variety, also add in the LangOpts test.
3514       if (Variety == "CXX11")
3515         Test += " && LangOpts.CPlusPlus11";
3516     } else if (!Attr->getValueAsListOfDefs("TargetSpecificSpellings").empty()) {
3517       // Add target checks if this spelling is target-specific.
3518       const std::vector<Record *> TargetSpellings =
3519           Attr->getValueAsListOfDefs("TargetSpecificSpellings");
3520       for (const auto &TargetSpelling : TargetSpellings) {
3521         // Find spelling that matches current scope and name.
3522         for (const auto &Spelling : GetFlattenedSpellings(*TargetSpelling)) {
3523           if (Scope == Spelling.nameSpace() && Name == Spelling.name()) {
3524             const Record *Target = TargetSpelling->getValueAsDef("Target");
3525             std::vector<StringRef> Arches =
3526                 Target->getValueAsListOfStrings("Arches");
3527             GenerateTargetSpecificAttrChecks(Target, Arches, Test,
3528                                              /*FnName=*/nullptr);
3529             break;
3530           }
3531         }
3532       }
3533 
3534       if (Variety == "CXX11")
3535         Test += " && LangOpts.CPlusPlus11";
3536     } else if (Variety == "CXX11")
3537       // C++11 mode should be checked against LangOpts, which is presumed to be
3538       // present in the caller.
3539       Test = "LangOpts.CPlusPlus11";
3540 
3541     std::string TestStr = !Test.empty()
3542                               ? Test + " ? " + llvm::itostr(Version) + " : 0"
3543                               : llvm::itostr(Version);
3544     if (Scope.empty() || Scope == Spelling.nameSpace())
3545       OS << "    .Case(\"" << Spelling.name() << "\", " << TestStr << ")\n";
3546   }
3547   OS << "    .Default(0);\n";
3548 }
3549 
3550 // Emits the list of tokens for regular keyword attributes.
3551 void EmitClangAttrTokenKinds(RecordKeeper &Records, raw_ostream &OS) {
3552   emitSourceFileHeader("A list of tokens generated from the attribute"
3553                        " definitions",
3554                        OS);
3555   // Assume for now that the same token is not used in multiple regular
3556   // keyword attributes.
3557   for (auto *R : Records.getAllDerivedDefinitions("Attr"))
3558     for (const auto &S : GetFlattenedSpellings(*R))
3559       if (isRegularKeywordAttribute(S)) {
3560         if (!R->getValueAsListOfDefs("Args").empty())
3561           PrintError(R->getLoc(),
3562                      "RegularKeyword attributes with arguments are not "
3563                      "yet supported");
3564         OS << "KEYWORD_ATTRIBUTE("
3565            << S.getSpellingRecord().getValueAsString("Name") << ")\n";
3566       }
3567   OS << "#undef KEYWORD_ATTRIBUTE\n";
3568 }
3569 
3570 // Emits the list of spellings for attributes.
3571 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3572   emitSourceFileHeader("Code to implement the __has_attribute logic", OS,
3573                        Records);
3574 
3575   // Separate all of the attributes out into four group: generic, C++11, GNU,
3576   // and declspecs. Then generate a big switch statement for each of them.
3577   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3578   std::vector<std::pair<const Record *, FlattenedSpelling>> Declspec, Microsoft,
3579       GNU, Pragma, HLSLSemantic;
3580   std::map<std::string,
3581            std::vector<std::pair<const Record *, FlattenedSpelling>>>
3582       CXX, C23;
3583 
3584   // Walk over the list of all attributes, and split them out based on the
3585   // spelling variety.
3586   for (auto *R : Attrs) {
3587     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3588     for (const auto &SI : Spellings) {
3589       const std::string &Variety = SI.variety();
3590       if (Variety == "GNU")
3591         GNU.emplace_back(R, SI);
3592       else if (Variety == "Declspec")
3593         Declspec.emplace_back(R, SI);
3594       else if (Variety == "Microsoft")
3595         Microsoft.emplace_back(R, SI);
3596       else if (Variety == "CXX11")
3597         CXX[SI.nameSpace()].emplace_back(R, SI);
3598       else if (Variety == "C23")
3599         C23[SI.nameSpace()].emplace_back(R, SI);
3600       else if (Variety == "Pragma")
3601         Pragma.emplace_back(R, SI);
3602       else if (Variety == "HLSLSemantic")
3603         HLSLSemantic.emplace_back(R, SI);
3604     }
3605   }
3606 
3607   OS << "const llvm::Triple &T = Target.getTriple();\n";
3608   OS << "switch (Syntax) {\n";
3609   OS << "case AttributeCommonInfo::Syntax::AS_GNU:\n";
3610   OS << "  return llvm::StringSwitch<int>(Name)\n";
3611   GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3612   OS << "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
3613   OS << "  return llvm::StringSwitch<int>(Name)\n";
3614   GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
3615   OS << "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
3616   OS << "  return llvm::StringSwitch<int>(Name)\n";
3617   GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
3618   OS << "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
3619   OS << "  return llvm::StringSwitch<int>(Name)\n";
3620   GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
3621   OS << "case AttributeCommonInfo::Syntax::AS_HLSLSemantic:\n";
3622   OS << "  return llvm::StringSwitch<int>(Name)\n";
3623   GenerateHasAttrSpellingStringSwitch(HLSLSemantic, OS, "HLSLSemantic");
3624   auto fn = [&OS](const char *Spelling,
3625                   const std::map<
3626                       std::string,
3627                       std::vector<std::pair<const Record *, FlattenedSpelling>>>
3628                       &List) {
3629     OS << "case AttributeCommonInfo::Syntax::AS_" << Spelling << ": {\n";
3630     // C++11-style attributes are further split out based on the Scope.
3631     for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
3632       if (I != List.cbegin())
3633         OS << " else ";
3634       if (I->first.empty())
3635         OS << "if (ScopeName == \"\") {\n";
3636       else
3637         OS << "if (ScopeName == \"" << I->first << "\") {\n";
3638       OS << "  return llvm::StringSwitch<int>(Name)\n";
3639       GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
3640       OS << "}";
3641     }
3642     OS << "\n} break;\n";
3643   };
3644   fn("CXX11", CXX);
3645   fn("C23", C23);
3646   OS << "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
3647   OS << "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
3648   OS << "  llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
3649   OS << "  return 0;\n";
3650   OS << "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
3651   OS << "  llvm_unreachable (\"hasAttribute not supported for "
3652         "AS_Implicit\");\n";
3653   OS << "  return 0;\n";
3654 
3655   OS << "}\n";
3656 }
3657 
3658 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
3659   emitSourceFileHeader("Code to translate different attribute spellings into "
3660                        "internal identifiers",
3661                        OS, Records);
3662 
3663   OS << "  switch (getParsedKind()) {\n";
3664   OS << "    case IgnoredAttribute:\n";
3665   OS << "    case UnknownAttribute:\n";
3666   OS << "    case NoSemaHandlerAttribute:\n";
3667   OS << "      llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3668 
3669   ParsedAttrMap Attrs = getParsedAttrList(Records);
3670   for (const auto &I : Attrs) {
3671     const Record &R = *I.second;
3672     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3673     OS << "  case AT_" << I.first << ": {\n";
3674     for (unsigned I = 0; I < Spellings.size(); ++ I) {
3675       OS << "    if (Name == \"" << Spellings[I].name() << "\" && "
3676          << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
3677          << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3678          << "        return " << I << ";\n";
3679     }
3680 
3681     OS << "    break;\n";
3682     OS << "  }\n";
3683   }
3684 
3685   OS << "  }\n";
3686   OS << "  return 0;\n";
3687 }
3688 
3689 // Emits code used by RecursiveASTVisitor to visit attributes
3690 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3691   emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS,
3692                        Records);
3693 
3694   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3695 
3696   // Write method declarations for Traverse* methods.
3697   // We emit this here because we only generate methods for attributes that
3698   // are declared as ASTNodes.
3699   OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3700   for (const auto *Attr : Attrs) {
3701     const Record &R = *Attr;
3702     if (!R.getValueAsBit("ASTNode"))
3703       continue;
3704     OS << "  bool Traverse"
3705        << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3706     OS << "  bool Visit"
3707        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3708        << "    return true; \n"
3709        << "  }\n";
3710   }
3711   OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3712 
3713   // Write individual Traverse* methods for each attribute class.
3714   for (const auto *Attr : Attrs) {
3715     const Record &R = *Attr;
3716     if (!R.getValueAsBit("ASTNode"))
3717       continue;
3718 
3719     OS << "template <typename Derived>\n"
3720        << "bool VISITORCLASS<Derived>::Traverse"
3721        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3722        << "  if (!getDerived().VisitAttr(A))\n"
3723        << "    return false;\n"
3724        << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3725        << "    return false;\n";
3726 
3727     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3728     for (const auto *Arg : ArgRecords)
3729       createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3730 
3731     if (Attr->getValueAsBit("AcceptsExprPack"))
3732       VariadicExprArgument("DelayedArgs", R.getName())
3733           .writeASTVisitorTraversal(OS);
3734 
3735     OS << "  return true;\n";
3736     OS << "}\n\n";
3737   }
3738 
3739   // Write generic Traverse routine
3740   OS << "template <typename Derived>\n"
3741      << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3742      << "  if (!A)\n"
3743      << "    return true;\n"
3744      << "\n"
3745      << "  switch (A->getKind()) {\n";
3746 
3747   for (const auto *Attr : Attrs) {
3748     const Record &R = *Attr;
3749     if (!R.getValueAsBit("ASTNode"))
3750       continue;
3751 
3752     OS << "    case attr::" << R.getName() << ":\n"
3753        << "      return getDerived().Traverse" << R.getName() << "Attr("
3754        << "cast<" << R.getName() << "Attr>(A));\n";
3755   }
3756   OS << "  }\n";  // end switch
3757   OS << "  llvm_unreachable(\"bad attribute kind\");\n";
3758   OS << "}\n";  // end function
3759   OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
3760 }
3761 
3762 void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3763                                             raw_ostream &OS,
3764                                             bool AppliesToDecl) {
3765 
3766   OS << "  switch (At->getKind()) {\n";
3767   for (const auto *Attr : Attrs) {
3768     const Record &R = *Attr;
3769     if (!R.getValueAsBit("ASTNode"))
3770       continue;
3771     OS << "    case attr::" << R.getName() << ": {\n";
3772     bool ShouldClone = R.getValueAsBit("Clone") &&
3773                        (!AppliesToDecl ||
3774                         R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3775 
3776     if (!ShouldClone) {
3777       OS << "      return nullptr;\n";
3778       OS << "    }\n";
3779       continue;
3780     }
3781 
3782     OS << "      const auto *A = cast<"
3783        << R.getName() << "Attr>(At);\n";
3784     bool TDependent = R.getValueAsBit("TemplateDependent");
3785 
3786     if (!TDependent) {
3787       OS << "      return A->clone(C);\n";
3788       OS << "    }\n";
3789       continue;
3790     }
3791 
3792     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3793     std::vector<std::unique_ptr<Argument>> Args;
3794     Args.reserve(ArgRecords.size());
3795 
3796     for (const auto *ArgRecord : ArgRecords)
3797       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
3798 
3799     for (auto const &ai : Args)
3800       ai->writeTemplateInstantiation(OS);
3801 
3802     OS << "      return new (C) " << R.getName() << "Attr(C, *A";
3803     for (auto const &ai : Args) {
3804       OS << ", ";
3805       ai->writeTemplateInstantiationArgs(OS);
3806     }
3807     OS << ");\n"
3808        << "    }\n";
3809   }
3810   OS << "  } // end switch\n"
3811      << "  llvm_unreachable(\"Unknown attribute!\");\n"
3812      << "  return nullptr;\n";
3813 }
3814 
3815 // Emits code to instantiate dependent attributes on templates.
3816 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3817   emitSourceFileHeader("Template instantiation code for attributes", OS,
3818                        Records);
3819 
3820   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3821 
3822   OS << "namespace clang {\n"
3823      << "namespace sema {\n\n"
3824      << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3825      << "Sema &S,\n"
3826      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3827   EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3828   OS << "}\n\n"
3829      << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3830      << " ASTContext &C, Sema &S,\n"
3831      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3832   EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3833   OS << "}\n\n"
3834      << "} // end namespace sema\n"
3835      << "} // end namespace clang\n";
3836 }
3837 
3838 // Emits the list of parsed attributes.
3839 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3840   emitSourceFileHeader("List of all attributes that Clang recognizes", OS,
3841                        Records);
3842 
3843   OS << "#ifndef PARSED_ATTR\n";
3844   OS << "#define PARSED_ATTR(NAME) NAME\n";
3845   OS << "#endif\n\n";
3846 
3847   ParsedAttrMap Names = getParsedAttrList(Records);
3848   for (const auto &I : Names) {
3849     OS << "PARSED_ATTR(" << I.first << ")\n";
3850   }
3851 }
3852 
3853 static bool isArgVariadic(const Record &R, StringRef AttrName) {
3854   return createArgument(R, AttrName)->isVariadic();
3855 }
3856 
3857 static void emitArgInfo(const Record &R, raw_ostream &OS) {
3858   // This function will count the number of arguments specified for the
3859   // attribute and emit the number of required arguments followed by the
3860   // number of optional arguments.
3861   std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3862   unsigned ArgCount = 0, OptCount = 0, ArgMemberCount = 0;
3863   bool HasVariadic = false;
3864   for (const auto *Arg : Args) {
3865     // If the arg is fake, it's the user's job to supply it: general parsing
3866     // logic shouldn't need to know anything about it.
3867     if (Arg->getValueAsBit("Fake"))
3868       continue;
3869     Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3870     ++ArgMemberCount;
3871     if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3872       HasVariadic = true;
3873   }
3874 
3875   // If there is a variadic argument, we will set the optional argument count
3876   // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3877   OS << "    /*NumArgs=*/" << ArgCount << ",\n";
3878   OS << "    /*OptArgs=*/" << (HasVariadic ? 15 : OptCount) << ",\n";
3879   OS << "    /*NumArgMembers=*/" << ArgMemberCount << ",\n";
3880 }
3881 
3882 static std::string GetDiagnosticSpelling(const Record &R) {
3883   std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
3884   if (!Ret.empty())
3885     return Ret;
3886 
3887   // If we couldn't find the DiagSpelling in this object, we can check to see
3888   // if the object is one that has a base, and if it is, loop up to the Base
3889   // member recursively.
3890   if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
3891     return GetDiagnosticSpelling(*Base);
3892 
3893   return "";
3894 }
3895 
3896 static std::string CalculateDiagnostic(const Record &S) {
3897   // If the SubjectList object has a custom diagnostic associated with it,
3898   // return that directly.
3899   const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3900   if (!CustomDiag.empty())
3901     return ("\"" + Twine(CustomDiag) + "\"").str();
3902 
3903   std::vector<std::string> DiagList;
3904   std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3905   for (const auto *Subject : Subjects) {
3906     const Record &R = *Subject;
3907     // Get the diagnostic text from the Decl or Stmt node given.
3908     std::string V = GetDiagnosticSpelling(R);
3909     if (V.empty()) {
3910       PrintError(R.getLoc(),
3911                  "Could not determine diagnostic spelling for the node: " +
3912                      R.getName() + "; please add one to DeclNodes.td");
3913     } else {
3914       // The node may contain a list of elements itself, so split the elements
3915       // by a comma, and trim any whitespace.
3916       SmallVector<StringRef, 2> Frags;
3917       llvm::SplitString(V, Frags, ",");
3918       for (auto Str : Frags) {
3919         DiagList.push_back(std::string(Str.trim()));
3920       }
3921     }
3922   }
3923 
3924   if (DiagList.empty()) {
3925     PrintFatalError(S.getLoc(),
3926                     "Could not deduce diagnostic argument for Attr subjects");
3927     return "";
3928   }
3929 
3930   // FIXME: this is not particularly good for localization purposes and ideally
3931   // should be part of the diagnostics engine itself with some sort of list
3932   // specifier.
3933 
3934   // A single member of the list can be returned directly.
3935   if (DiagList.size() == 1)
3936     return '"' + DiagList.front() + '"';
3937 
3938   if (DiagList.size() == 2)
3939     return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3940 
3941   // If there are more than two in the list, we serialize the first N - 1
3942   // elements with a comma. This leaves the string in the state: foo, bar,
3943   // baz (but misses quux). We can then add ", and " for the last element
3944   // manually.
3945   std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3946   return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3947 }
3948 
3949 static std::string GetSubjectWithSuffix(const Record *R) {
3950   const std::string &B = std::string(R->getName());
3951   if (B == "DeclBase")
3952     return "Decl";
3953   return B + "Decl";
3954 }
3955 
3956 static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3957   return "is" + Subject.getName().str();
3958 }
3959 
3960 static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
3961   std::string FnName = functionNameForCustomAppertainsTo(Subject);
3962 
3963   // If this code has already been generated, we don't need to do anything.
3964   static std::set<std::string> CustomSubjectSet;
3965   auto I = CustomSubjectSet.find(FnName);
3966   if (I != CustomSubjectSet.end())
3967     return;
3968 
3969   // This only works with non-root Decls.
3970   Record *Base = Subject.getValueAsDef(BaseFieldName);
3971 
3972   // Not currently support custom subjects within custom subjects.
3973   if (Base->isSubClassOf("SubsetSubject")) {
3974     PrintFatalError(Subject.getLoc(),
3975                     "SubsetSubjects within SubsetSubjects is not supported");
3976     return;
3977   }
3978 
3979   OS << "static bool " << FnName << "(const Decl *D) {\n";
3980   OS << "  if (const auto *S = dyn_cast<";
3981   OS << GetSubjectWithSuffix(Base);
3982   OS << ">(D))\n";
3983   OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
3984   OS << "  return false;\n";
3985   OS << "}\n\n";
3986 
3987   CustomSubjectSet.insert(FnName);
3988 }
3989 
3990 static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3991   // If the attribute does not contain a Subjects definition, then use the
3992   // default appertainsTo logic.
3993   if (Attr.isValueUnset("Subjects"))
3994     return;
3995 
3996   const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3997   std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3998 
3999   // If the list of subjects is empty, it is assumed that the attribute
4000   // appertains to everything.
4001   if (Subjects.empty())
4002     return;
4003 
4004   bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
4005 
4006   // Split the subjects into declaration subjects and statement subjects.
4007   // FIXME: subset subjects are added to the declaration list until there are
4008   // enough statement attributes with custom subject needs to warrant
4009   // the implementation effort.
4010   std::vector<Record *> DeclSubjects, StmtSubjects;
4011   llvm::copy_if(
4012       Subjects, std::back_inserter(DeclSubjects), [](const Record *R) {
4013         return R->isSubClassOf("SubsetSubject") || !R->isSubClassOf("StmtNode");
4014       });
4015   llvm::copy_if(Subjects, std::back_inserter(StmtSubjects),
4016                 [](const Record *R) { return R->isSubClassOf("StmtNode"); });
4017 
4018   // We should have sorted all of the subjects into two lists.
4019   // FIXME: this assertion will be wrong if we ever add type attribute subjects.
4020   assert(DeclSubjects.size() + StmtSubjects.size() == Subjects.size());
4021 
4022   if (DeclSubjects.empty()) {
4023     // If there are no decl subjects but there are stmt subjects, diagnose
4024     // trying to apply a statement attribute to a declaration.
4025     if (!StmtSubjects.empty()) {
4026       OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
4027       OS << "const Decl *D) const override {\n";
4028       OS << "  S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
4029       OS << "    << AL << AL.isRegularKeywordAttribute() << "
4030             "D->getLocation();\n";
4031       OS << "  return false;\n";
4032       OS << "}\n\n";
4033     }
4034   } else {
4035     // Otherwise, generate an appertainsTo check specific to this attribute
4036     // which checks all of the given subjects against the Decl passed in.
4037     OS << "bool diagAppertainsToDecl(Sema &S, ";
4038     OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
4039     OS << "  if (";
4040     for (auto I = DeclSubjects.begin(), E = DeclSubjects.end(); I != E; ++I) {
4041       // If the subject has custom code associated with it, use the generated
4042       // function for it. The function cannot be inlined into this check (yet)
4043       // because it requires the subject to be of a specific type, and were that
4044       // information inlined here, it would not support an attribute with
4045       // multiple custom subjects.
4046       if ((*I)->isSubClassOf("SubsetSubject"))
4047         OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
4048       else
4049         OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
4050 
4051       if (I + 1 != E)
4052         OS << " && ";
4053     }
4054     OS << ") {\n";
4055     OS << "    S.Diag(Attr.getLoc(), diag::";
4056     OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4057                 : "err_attribute_wrong_decl_type_str");
4058     OS << ")\n";
4059     OS << "      << Attr << Attr.isRegularKeywordAttribute() << ";
4060     OS << CalculateDiagnostic(*SubjectObj) << ";\n";
4061     OS << "    return false;\n";
4062     OS << "  }\n";
4063     OS << "  return true;\n";
4064     OS << "}\n\n";
4065   }
4066 
4067   if (StmtSubjects.empty()) {
4068     // If there are no stmt subjects but there are decl subjects, diagnose
4069     // trying to apply a declaration attribute to a statement.
4070     if (!DeclSubjects.empty()) {
4071       OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
4072       OS << "const Stmt *St) const override {\n";
4073       OS << "  S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
4074       OS << "    << AL << AL.isRegularKeywordAttribute() << "
4075             "St->getBeginLoc();\n";
4076       OS << "  return false;\n";
4077       OS << "}\n\n";
4078     }
4079   } else {
4080     // Now, do the same for statements.
4081     OS << "bool diagAppertainsToStmt(Sema &S, ";
4082     OS << "const ParsedAttr &Attr, const Stmt *St) const override {\n";
4083     OS << "  if (";
4084     for (auto I = StmtSubjects.begin(), E = StmtSubjects.end(); I != E; ++I) {
4085       OS << "!isa<" << (*I)->getName() << ">(St)";
4086       if (I + 1 != E)
4087         OS << " && ";
4088     }
4089     OS << ") {\n";
4090     OS << "    S.Diag(Attr.getLoc(), diag::";
4091     OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4092                 : "err_attribute_wrong_decl_type_str");
4093     OS << ")\n";
4094     OS << "      << Attr << Attr.isRegularKeywordAttribute() << ";
4095     OS << CalculateDiagnostic(*SubjectObj) << ";\n";
4096     OS << "    return false;\n";
4097     OS << "  }\n";
4098     OS << "  return true;\n";
4099     OS << "}\n\n";
4100   }
4101 }
4102 
4103 // Generates the mutual exclusion checks. The checks for parsed attributes are
4104 // written into OS and the checks for merging declaration attributes are
4105 // written into MergeOS.
4106 static void GenerateMutualExclusionsChecks(const Record &Attr,
4107                                            const RecordKeeper &Records,
4108                                            raw_ostream &OS,
4109                                            raw_ostream &MergeDeclOS,
4110                                            raw_ostream &MergeStmtOS) {
4111   // Find all of the definitions that inherit from MutualExclusions and include
4112   // the given attribute in the list of exclusions to generate the
4113   // diagMutualExclusion() check.
4114   std::vector<Record *> ExclusionsList =
4115       Records.getAllDerivedDefinitions("MutualExclusions");
4116 
4117   // We don't do any of this magic for type attributes yet.
4118   if (Attr.isSubClassOf("TypeAttr"))
4119     return;
4120 
4121   // This means the attribute is either a statement attribute, a decl
4122   // attribute, or both; find out which.
4123   bool CurAttrIsStmtAttr =
4124       Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr");
4125   bool CurAttrIsDeclAttr =
4126       !CurAttrIsStmtAttr || Attr.isSubClassOf("DeclOrStmtAttr");
4127 
4128   std::vector<std::string> DeclAttrs, StmtAttrs;
4129 
4130   for (const Record *Exclusion : ExclusionsList) {
4131     std::vector<Record *> MutuallyExclusiveAttrs =
4132         Exclusion->getValueAsListOfDefs("Exclusions");
4133     auto IsCurAttr = [Attr](const Record *R) {
4134       return R->getName() == Attr.getName();
4135     };
4136     if (llvm::any_of(MutuallyExclusiveAttrs, IsCurAttr)) {
4137       // This list of exclusions includes the attribute we're looking for, so
4138       // add the exclusive attributes to the proper list for checking.
4139       for (const Record *AttrToExclude : MutuallyExclusiveAttrs) {
4140         if (IsCurAttr(AttrToExclude))
4141           continue;
4142 
4143         if (CurAttrIsStmtAttr)
4144           StmtAttrs.push_back((AttrToExclude->getName() + "Attr").str());
4145         if (CurAttrIsDeclAttr)
4146           DeclAttrs.push_back((AttrToExclude->getName() + "Attr").str());
4147       }
4148     }
4149   }
4150 
4151   // If there are any decl or stmt attributes, silence -Woverloaded-virtual
4152   // warnings for them both.
4153   if (!DeclAttrs.empty() || !StmtAttrs.empty())
4154     OS << "  using ParsedAttrInfo::diagMutualExclusion;\n\n";
4155 
4156   // If we discovered any decl or stmt attributes to test for, generate the
4157   // predicates for them now.
4158   if (!DeclAttrs.empty()) {
4159     // Generate the ParsedAttrInfo subclass logic for declarations.
4160     OS << "  bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
4161        << "const Decl *D) const override {\n";
4162     for (const std::string &A : DeclAttrs) {
4163       OS << "    if (const auto *A = D->getAttr<" << A << ">()) {\n";
4164       OS << "      S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
4165          << " << AL << A << (AL.isRegularKeywordAttribute() ||"
4166          << " A->isRegularKeywordAttribute());\n";
4167       OS << "      S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
4168       OS << "      \nreturn false;\n";
4169       OS << "    }\n";
4170     }
4171     OS << "    return true;\n";
4172     OS << "  }\n\n";
4173 
4174     // Also generate the declaration attribute merging logic if the current
4175     // attribute is one that can be inheritted on a declaration. It is assumed
4176     // this code will be executed in the context of a function with parameters:
4177     // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
4178     // true on success).
4179     if (Attr.isSubClassOf("InheritableAttr")) {
4180       MergeDeclOS << "  if (const auto *Second = dyn_cast<"
4181                   << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4182       for (const std::string &A : DeclAttrs) {
4183         MergeDeclOS << "    if (const auto *First = D->getAttr<" << A
4184                     << ">()) {\n";
4185         MergeDeclOS << "      S.Diag(First->getLocation(), "
4186                     << "diag::err_attributes_are_not_compatible) << First << "
4187                     << "Second << (First->isRegularKeywordAttribute() || "
4188                     << "Second->isRegularKeywordAttribute());\n";
4189         MergeDeclOS << "      S.Diag(Second->getLocation(), "
4190                     << "diag::note_conflicting_attribute);\n";
4191         MergeDeclOS << "      return false;\n";
4192         MergeDeclOS << "    }\n";
4193       }
4194       MergeDeclOS << "    return true;\n";
4195       MergeDeclOS << "  }\n";
4196     }
4197   }
4198 
4199   // Statement attributes are a bit different from declarations. With
4200   // declarations, each attribute is added to the declaration as it is
4201   // processed, and so you can look on the Decl * itself to see if there is a
4202   // conflicting attribute. Statement attributes are processed as a group
4203   // because AttributedStmt needs to tail-allocate all of the attribute nodes
4204   // at once. This means we cannot check whether the statement already contains
4205   // an attribute to check for the conflict. Instead, we need to check whether
4206   // the given list of semantic attributes contain any conflicts. It is assumed
4207   // this code will be executed in the context of a function with parameters:
4208   // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
4209   // loop which loops over the container C with a loop variable named A to
4210   // represent the current attribute to check for conflicts.
4211   //
4212   // FIXME: it would be nice not to walk over the list of potential attributes
4213   // to apply to the statement more than once, but statements typically don't
4214   // have long lists of attributes on them, so re-walking the list should not
4215   // be an expensive operation.
4216   if (!StmtAttrs.empty()) {
4217     MergeStmtOS << "    if (const auto *Second = dyn_cast<"
4218                 << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4219     MergeStmtOS << "      auto Iter = llvm::find_if(C, [](const Attr *Check) "
4220                 << "{ return isa<";
4221     interleave(
4222         StmtAttrs, [&](const std::string &Name) { MergeStmtOS << Name; },
4223         [&] { MergeStmtOS << ", "; });
4224     MergeStmtOS << ">(Check); });\n";
4225     MergeStmtOS << "      if (Iter != C.end()) {\n";
4226     MergeStmtOS << "        S.Diag((*Iter)->getLocation(), "
4227                 << "diag::err_attributes_are_not_compatible) << *Iter << "
4228                 << "Second << ((*Iter)->isRegularKeywordAttribute() || "
4229                 << "Second->isRegularKeywordAttribute());\n";
4230     MergeStmtOS << "        S.Diag(Second->getLocation(), "
4231                 << "diag::note_conflicting_attribute);\n";
4232     MergeStmtOS << "        return false;\n";
4233     MergeStmtOS << "      }\n";
4234     MergeStmtOS << "    }\n";
4235   }
4236 }
4237 
4238 static void
4239 emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
4240                         raw_ostream &OS) {
4241   OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
4242      << AttributeSubjectMatchRule::EnumName << " rule) {\n";
4243   OS << "  switch (rule) {\n";
4244   for (const auto &Rule : PragmaAttributeSupport.Rules) {
4245     if (Rule.isAbstractRule()) {
4246       OS << "  case " << Rule.getEnumValue() << ":\n";
4247       OS << "    assert(false && \"Abstract matcher rule isn't allowed\");\n";
4248       OS << "    return false;\n";
4249       continue;
4250     }
4251     std::vector<Record *> Subjects = Rule.getSubjects();
4252     assert(!Subjects.empty() && "Missing subjects");
4253     OS << "  case " << Rule.getEnumValue() << ":\n";
4254     OS << "    return ";
4255     for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
4256       // If the subject has custom code associated with it, use the function
4257       // that was generated for GenerateAppertainsTo to check if the declaration
4258       // is valid.
4259       if ((*I)->isSubClassOf("SubsetSubject"))
4260         OS << functionNameForCustomAppertainsTo(**I) << "(D)";
4261       else
4262         OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
4263 
4264       if (I + 1 != E)
4265         OS << " || ";
4266     }
4267     OS << ";\n";
4268   }
4269   OS << "  }\n";
4270   OS << "  llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
4271   OS << "}\n\n";
4272 }
4273 
4274 static void GenerateLangOptRequirements(const Record &R,
4275                                         raw_ostream &OS) {
4276   // If the attribute has an empty or unset list of language requirements,
4277   // use the default handler.
4278   std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
4279   if (LangOpts.empty())
4280     return;
4281 
4282   OS << "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
4283   OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
4284   OS << "}\n\n";
4285 }
4286 
4287 static void GenerateTargetRequirements(const Record &Attr,
4288                                        const ParsedAttrMap &Dupes,
4289                                        raw_ostream &OS) {
4290   // If the attribute is not a target specific attribute, use the default
4291   // target handler.
4292   if (!Attr.isSubClassOf("TargetSpecificAttr"))
4293     return;
4294 
4295   // Get the list of architectures to be tested for.
4296   const Record *R = Attr.getValueAsDef("Target");
4297   std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
4298 
4299   // If there are other attributes which share the same parsed attribute kind,
4300   // such as target-specific attributes with a shared spelling, collapse the
4301   // duplicate architectures. This is required because a shared target-specific
4302   // attribute has only one ParsedAttr::Kind enumeration value, but it
4303   // applies to multiple target architectures. In order for the attribute to be
4304   // considered valid, all of its architectures need to be included.
4305   if (!Attr.isValueUnset("ParseKind")) {
4306     const StringRef APK = Attr.getValueAsString("ParseKind");
4307     for (const auto &I : Dupes) {
4308       if (I.first == APK) {
4309         std::vector<StringRef> DA =
4310             I.second->getValueAsDef("Target")->getValueAsListOfStrings(
4311                 "Arches");
4312         Arches.insert(Arches.end(), DA.begin(), DA.end());
4313       }
4314     }
4315   }
4316 
4317   std::string FnName = "isTarget";
4318   std::string Test;
4319   bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
4320 
4321   OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
4322   if (UsesT)
4323     OS << "  const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4324   OS << "  return " << Test << ";\n";
4325   OS << "}\n\n";
4326 }
4327 
4328 static void
4329 GenerateSpellingTargetRequirements(const Record &Attr,
4330                                    const std::vector<Record *> &TargetSpellings,
4331                                    raw_ostream &OS) {
4332   // If there are no target specific spellings, use the default target handler.
4333   if (TargetSpellings.empty())
4334     return;
4335 
4336   std::string Test;
4337   bool UsesT = false;
4338   const std::vector<FlattenedSpelling> SpellingList =
4339       GetFlattenedSpellings(Attr);
4340   for (unsigned TargetIndex = 0; TargetIndex < TargetSpellings.size();
4341        ++TargetIndex) {
4342     const auto &TargetSpelling = TargetSpellings[TargetIndex];
4343     std::vector<FlattenedSpelling> Spellings =
4344         GetFlattenedSpellings(*TargetSpelling);
4345 
4346     Test += "((SpellingListIndex == ";
4347     for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
4348       Test +=
4349           llvm::itostr(getSpellingListIndex(SpellingList, Spellings[Index]));
4350       if (Index != Spellings.size() - 1)
4351         Test += " ||\n    SpellingListIndex == ";
4352       else
4353         Test += ") && ";
4354     }
4355 
4356     const Record *Target = TargetSpelling->getValueAsDef("Target");
4357     std::vector<StringRef> Arches = Target->getValueAsListOfStrings("Arches");
4358     std::string FnName = "isTargetSpelling";
4359     UsesT |= GenerateTargetSpecificAttrChecks(Target, Arches, Test, &FnName);
4360     Test += ")";
4361     if (TargetIndex != TargetSpellings.size() - 1)
4362       Test += " || ";
4363   }
4364 
4365   OS << "bool spellingExistsInTarget(const TargetInfo &Target,\n";
4366   OS << "                            const unsigned SpellingListIndex) const "
4367         "override {\n";
4368   if (UsesT)
4369     OS << "  const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4370   OS << "  return " << Test << ";\n", OS << "}\n\n";
4371 }
4372 
4373 static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
4374                                                     raw_ostream &OS) {
4375   // If the attribute does not have a semantic form, we can bail out early.
4376   if (!Attr.getValueAsBit("ASTNode"))
4377     return;
4378 
4379   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4380 
4381   // If there are zero or one spellings, or all of the spellings share the same
4382   // name, we can also bail out early.
4383   if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
4384     return;
4385 
4386   // Generate the enumeration we will use for the mapping.
4387   SemanticSpellingMap SemanticToSyntacticMap;
4388   std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
4389   std::string Name = Attr.getName().str() + "AttrSpellingMap";
4390 
4391   OS << "unsigned spellingIndexToSemanticSpelling(";
4392   OS << "const ParsedAttr &Attr) const override {\n";
4393   OS << Enum;
4394   OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
4395   WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
4396   OS << "}\n\n";
4397 }
4398 
4399 static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
4400   // Only generate if Attr can be handled simply.
4401   if (!Attr.getValueAsBit("SimpleHandler"))
4402     return;
4403 
4404   // Generate a function which just converts from ParsedAttr to the Attr type.
4405   OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
4406   OS << "const ParsedAttr &Attr) const override {\n";
4407   OS << "  D->addAttr(::new (S.Context) " << Attr.getName();
4408   OS << "Attr(S.Context, Attr));\n";
4409   OS << "  return AttributeApplied;\n";
4410   OS << "}\n\n";
4411 }
4412 
4413 static bool isParamExpr(const Record *Arg) {
4414   return !Arg->getSuperClasses().empty() &&
4415          llvm::StringSwitch<bool>(
4416              Arg->getSuperClasses().back().first->getName())
4417              .Case("ExprArgument", true)
4418              .Case("VariadicExprArgument", true)
4419              .Default(false);
4420 }
4421 
4422 void GenerateIsParamExpr(const Record &Attr, raw_ostream &OS) {
4423   OS << "bool isParamExpr(size_t N) const override {\n";
4424   OS << "  return ";
4425   auto Args = Attr.getValueAsListOfDefs("Args");
4426   for (size_t I = 0; I < Args.size(); ++I)
4427     if (isParamExpr(Args[I]))
4428       OS << "(N == " << I << ") || ";
4429   OS << "false;\n";
4430   OS << "}\n\n";
4431 }
4432 
4433 void GenerateHandleAttrWithDelayedArgs(RecordKeeper &Records, raw_ostream &OS) {
4434   OS << "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
4435   OS << "const ParsedAttr &Attr) {\n";
4436   OS << "  SmallVector<Expr *, 4> ArgExprs;\n";
4437   OS << "  ArgExprs.reserve(Attr.getNumArgs());\n";
4438   OS << "  for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
4439   OS << "    assert(!Attr.isArgIdent(I));\n";
4440   OS << "    ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
4441   OS << "  }\n";
4442   OS << "  clang::Attr *CreatedAttr = nullptr;\n";
4443   OS << "  switch (Attr.getKind()) {\n";
4444   OS << "  default:\n";
4445   OS << "    llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
4446   ParsedAttrMap Attrs = getParsedAttrList(Records);
4447   for (const auto &I : Attrs) {
4448     const Record &R = *I.second;
4449     if (!R.getValueAsBit("AcceptsExprPack"))
4450       continue;
4451     OS << "  case ParsedAttr::AT_" << I.first << ": {\n";
4452     OS << "    CreatedAttr = " << R.getName() << "Attr::CreateWithDelayedArgs";
4453     OS << "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
4454     OS << "    break;\n";
4455     OS << "  }\n";
4456   }
4457   OS << "  }\n";
4458   OS << "  D->addAttr(CreatedAttr);\n";
4459   OS << "}\n\n";
4460 }
4461 
4462 static bool IsKnownToGCC(const Record &Attr) {
4463   // Look at the spellings for this subject; if there are any spellings which
4464   // claim to be known to GCC, the attribute is known to GCC.
4465   return llvm::any_of(
4466       GetFlattenedSpellings(Attr),
4467       [](const FlattenedSpelling &S) { return S.knownToGCC(); });
4468 }
4469 
4470 /// Emits the parsed attribute helpers
4471 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
4472   emitSourceFileHeader("Parsed attribute helpers", OS, Records);
4473 
4474   OS << "#if !defined(WANT_DECL_MERGE_LOGIC) && "
4475      << "!defined(WANT_STMT_MERGE_LOGIC)\n";
4476   PragmaClangAttributeSupport &PragmaAttributeSupport =
4477       getPragmaAttributeSupport(Records);
4478 
4479   // Get the list of parsed attributes, and accept the optional list of
4480   // duplicates due to the ParseKind.
4481   ParsedAttrMap Dupes;
4482   ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
4483 
4484   // Generate all of the custom appertainsTo functions that the attributes
4485   // will be using.
4486   for (const auto &I : Attrs) {
4487     const Record &Attr = *I.second;
4488     if (Attr.isValueUnset("Subjects"))
4489       continue;
4490     const Record *SubjectObj = Attr.getValueAsDef("Subjects");
4491     for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
4492       if (Subject->isSubClassOf("SubsetSubject"))
4493         GenerateCustomAppertainsTo(*Subject, OS);
4494   }
4495 
4496   // This stream is used to collect all of the declaration attribute merging
4497   // logic for performing mutual exclusion checks. This gets emitted at the
4498   // end of the file in a helper function of its own.
4499   std::string DeclMergeChecks, StmtMergeChecks;
4500   raw_string_ostream MergeDeclOS(DeclMergeChecks), MergeStmtOS(StmtMergeChecks);
4501 
4502   // Generate a ParsedAttrInfo struct for each of the attributes.
4503   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4504     // TODO: If the attribute's kind appears in the list of duplicates, that is
4505     // because it is a target-specific attribute that appears multiple times.
4506     // It would be beneficial to test whether the duplicates are "similar
4507     // enough" to each other to not cause problems. For instance, check that
4508     // the spellings are identical, and custom parsing rules match, etc.
4509 
4510     // We need to generate struct instances based off ParsedAttrInfo from
4511     // ParsedAttr.cpp.
4512     const std::string &AttrName = I->first;
4513     const Record &Attr = *I->second;
4514     auto Spellings = GetFlattenedSpellings(Attr);
4515     if (!Spellings.empty()) {
4516       OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
4517          << "Spellings[] = {\n";
4518       for (const auto &S : Spellings) {
4519         const std::string &RawSpelling = S.name();
4520         std::string Spelling;
4521         if (!S.nameSpace().empty())
4522           Spelling += S.nameSpace() + "::";
4523         if (S.variety() == "GNU")
4524           Spelling += NormalizeGNUAttrSpelling(RawSpelling);
4525         else
4526           Spelling += RawSpelling;
4527         OS << "  {AttributeCommonInfo::AS_" << S.variety();
4528         OS << ", \"" << Spelling << "\"},\n";
4529       }
4530       OS << "};\n";
4531     }
4532 
4533     std::vector<std::string> ArgNames;
4534     for (const auto &Arg : Attr.getValueAsListOfDefs("Args")) {
4535       bool UnusedUnset;
4536       if (Arg->getValueAsBitOrUnset("Fake", UnusedUnset))
4537         continue;
4538       ArgNames.push_back(Arg->getValueAsString("Name").str());
4539       for (const auto &Class : Arg->getSuperClasses()) {
4540         if (Class.first->getName().starts_with("Variadic")) {
4541           ArgNames.back().append("...");
4542           break;
4543         }
4544       }
4545     }
4546     if (!ArgNames.empty()) {
4547       OS << "static constexpr const char *" << I->first << "ArgNames[] = {\n";
4548       for (const auto &N : ArgNames)
4549         OS << '"' << N << "\",";
4550       OS << "};\n";
4551     }
4552 
4553     OS << "struct ParsedAttrInfo" << I->first
4554        << " final : public ParsedAttrInfo {\n";
4555     OS << "  constexpr ParsedAttrInfo" << I->first << "() : ParsedAttrInfo(\n";
4556     OS << "    /*AttrKind=*/ParsedAttr::AT_" << AttrName << ",\n";
4557     emitArgInfo(Attr, OS);
4558     OS << "    /*HasCustomParsing=*/";
4559     OS << Attr.getValueAsBit("HasCustomParsing") << ",\n";
4560     OS << "    /*AcceptsExprPack=*/";
4561     OS << Attr.getValueAsBit("AcceptsExprPack") << ",\n";
4562     OS << "    /*IsTargetSpecific=*/";
4563     OS << Attr.isSubClassOf("TargetSpecificAttr") << ",\n";
4564     OS << "    /*IsType=*/";
4565     OS << (Attr.isSubClassOf("TypeAttr") || Attr.isSubClassOf("DeclOrTypeAttr"))
4566        << ",\n";
4567     OS << "    /*IsStmt=*/";
4568     OS << (Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr"))
4569        << ",\n";
4570     OS << "    /*IsKnownToGCC=*/";
4571     OS << IsKnownToGCC(Attr) << ",\n";
4572     OS << "    /*IsSupportedByPragmaAttribute=*/";
4573     OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ",\n";
4574     if (!Spellings.empty())
4575       OS << "    /*Spellings=*/" << I->first << "Spellings,\n";
4576     else
4577       OS << "    /*Spellings=*/{},\n";
4578     if (!ArgNames.empty())
4579       OS << "    /*ArgNames=*/" << I->first << "ArgNames";
4580     else
4581       OS << "    /*ArgNames=*/{}";
4582     OS << ") {}\n";
4583     GenerateAppertainsTo(Attr, OS);
4584     GenerateMutualExclusionsChecks(Attr, Records, OS, MergeDeclOS, MergeStmtOS);
4585     GenerateLangOptRequirements(Attr, OS);
4586     GenerateTargetRequirements(Attr, Dupes, OS);
4587     GenerateSpellingTargetRequirements(
4588         Attr, Attr.getValueAsListOfDefs("TargetSpecificSpellings"), OS);
4589     GenerateSpellingIndexToSemanticSpelling(Attr, OS);
4590     PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
4591     GenerateHandleDeclAttribute(Attr, OS);
4592     GenerateIsParamExpr(Attr, OS);
4593     OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
4594     OS << "};\n";
4595     OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
4596        << "::Instance;\n";
4597   }
4598 
4599   OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
4600   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4601     OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
4602   }
4603   OS << "};\n\n";
4604 
4605   // Generate function for handling attributes with delayed arguments
4606   GenerateHandleAttrWithDelayedArgs(Records, OS);
4607 
4608   // Generate the attribute match rules.
4609   emitAttributeMatchRules(PragmaAttributeSupport, OS);
4610 
4611   OS << "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
4612 
4613   // Write out the declaration merging check logic.
4614   OS << "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
4615      << "const Attr *A) {\n";
4616   OS << MergeDeclOS.str();
4617   OS << "  return true;\n";
4618   OS << "}\n\n";
4619 
4620   OS << "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
4621 
4622   // Write out the statement merging check logic.
4623   OS << "static bool DiagnoseMutualExclusions(Sema &S, "
4624      << "const SmallVectorImpl<const Attr *> &C) {\n";
4625   OS << "  for (const Attr *A : C) {\n";
4626   OS << MergeStmtOS.str();
4627   OS << "  }\n";
4628   OS << "  return true;\n";
4629   OS << "}\n\n";
4630 
4631   OS << "#endif\n";
4632 }
4633 
4634 // Emits the kind list of parsed attributes
4635 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
4636   emitSourceFileHeader("Attribute name matcher", OS, Records);
4637 
4638   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4639   std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
4640       Keywords, Pragma, C23, HLSLSemantic;
4641   std::set<std::string> Seen;
4642   for (const auto *A : Attrs) {
4643     const Record &Attr = *A;
4644 
4645     bool SemaHandler = Attr.getValueAsBit("SemaHandler");
4646     bool Ignored = Attr.getValueAsBit("Ignored");
4647     if (SemaHandler || Ignored) {
4648       // Attribute spellings can be shared between target-specific attributes,
4649       // and can be shared between syntaxes for the same attribute. For
4650       // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
4651       // specific attribute, or MSP430-specific attribute. Additionally, an
4652       // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
4653       // for the same semantic attribute. Ultimately, we need to map each of
4654       // these to a single AttributeCommonInfo::Kind value, but the
4655       // StringMatcher class cannot handle duplicate match strings. So we
4656       // generate a list of string to match based on the syntax, and emit
4657       // multiple string matchers depending on the syntax used.
4658       std::string AttrName;
4659       if (Attr.isSubClassOf("TargetSpecificAttr") &&
4660           !Attr.isValueUnset("ParseKind")) {
4661         AttrName = std::string(Attr.getValueAsString("ParseKind"));
4662         if (!Seen.insert(AttrName).second)
4663           continue;
4664       } else
4665         AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
4666 
4667       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4668       for (const auto &S : Spellings) {
4669         const std::string &RawSpelling = S.name();
4670         std::vector<StringMatcher::StringPair> *Matches = nullptr;
4671         std::string Spelling;
4672         const std::string &Variety = S.variety();
4673         if (Variety == "CXX11") {
4674           Matches = &CXX11;
4675           if (!S.nameSpace().empty())
4676             Spelling += S.nameSpace() + "::";
4677         } else if (Variety == "C23") {
4678           Matches = &C23;
4679           if (!S.nameSpace().empty())
4680             Spelling += S.nameSpace() + "::";
4681         } else if (Variety == "GNU")
4682           Matches = &GNU;
4683         else if (Variety == "Declspec")
4684           Matches = &Declspec;
4685         else if (Variety == "Microsoft")
4686           Matches = &Microsoft;
4687         else if (Variety == "Keyword")
4688           Matches = &Keywords;
4689         else if (Variety == "Pragma")
4690           Matches = &Pragma;
4691         else if (Variety == "HLSLSemantic")
4692           Matches = &HLSLSemantic;
4693 
4694         assert(Matches && "Unsupported spelling variety found");
4695 
4696         if (Variety == "GNU")
4697           Spelling += NormalizeGNUAttrSpelling(RawSpelling);
4698         else
4699           Spelling += RawSpelling;
4700 
4701         if (SemaHandler)
4702           Matches->push_back(StringMatcher::StringPair(
4703               Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
4704         else
4705           Matches->push_back(StringMatcher::StringPair(
4706               Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
4707       }
4708     }
4709   }
4710 
4711   OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
4712   OS << "AttributeCommonInfo::Syntax Syntax) {\n";
4713   OS << "  if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
4714   StringMatcher("Name", GNU, OS).Emit();
4715   OS << "  } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
4716   StringMatcher("Name", Declspec, OS).Emit();
4717   OS << "  } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
4718   StringMatcher("Name", Microsoft, OS).Emit();
4719   OS << "  } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
4720   StringMatcher("Name", CXX11, OS).Emit();
4721   OS << "  } else if (AttributeCommonInfo::AS_C23 == Syntax) {\n";
4722   StringMatcher("Name", C23, OS).Emit();
4723   OS << "  } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
4724   OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
4725   StringMatcher("Name", Keywords, OS).Emit();
4726   OS << "  } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
4727   StringMatcher("Name", Pragma, OS).Emit();
4728   OS << "  } else if (AttributeCommonInfo::AS_HLSLSemantic == Syntax) {\n";
4729   StringMatcher("Name", HLSLSemantic, OS).Emit();
4730   OS << "  }\n";
4731   OS << "  return AttributeCommonInfo::UnknownAttribute;\n"
4732      << "}\n";
4733 }
4734 
4735 // Emits the code to dump an attribute.
4736 void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
4737   emitSourceFileHeader("Attribute text node dumper", OS, Records);
4738 
4739   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
4740   for (const auto *Attr : Attrs) {
4741     const Record &R = *Attr;
4742     if (!R.getValueAsBit("ASTNode"))
4743       continue;
4744 
4745     // If the attribute has a semantically-meaningful name (which is determined
4746     // by whether there is a Spelling enumeration for it), then write out the
4747     // spelling used for the attribute.
4748 
4749     std::string FunctionContent;
4750     llvm::raw_string_ostream SS(FunctionContent);
4751 
4752     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
4753     if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
4754       SS << "    OS << \" \" << A->getSpelling();\n";
4755 
4756     Args = R.getValueAsListOfDefs("Args");
4757     for (const auto *Arg : Args)
4758       createArgument(*Arg, R.getName())->writeDump(SS);
4759 
4760     if (Attr->getValueAsBit("AcceptsExprPack"))
4761       VariadicExprArgument("DelayedArgs", R.getName()).writeDump(OS);
4762 
4763     if (SS.tell()) {
4764       OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
4765          << "Attr *A) {\n";
4766       if (!Args.empty())
4767         OS << "    const auto *SA = cast<" << R.getName()
4768            << "Attr>(A); (void)SA;\n";
4769       OS << SS.str();
4770       OS << "  }\n";
4771     }
4772   }
4773 }
4774 
4775 void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
4776   emitSourceFileHeader("Attribute text node traverser", OS, Records);
4777 
4778   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
4779   for (const auto *Attr : Attrs) {
4780     const Record &R = *Attr;
4781     if (!R.getValueAsBit("ASTNode"))
4782       continue;
4783 
4784     std::string FunctionContent;
4785     llvm::raw_string_ostream SS(FunctionContent);
4786 
4787     Args = R.getValueAsListOfDefs("Args");
4788     for (const auto *Arg : Args)
4789       createArgument(*Arg, R.getName())->writeDumpChildren(SS);
4790     if (Attr->getValueAsBit("AcceptsExprPack"))
4791       VariadicExprArgument("DelayedArgs", R.getName()).writeDumpChildren(SS);
4792     if (SS.tell()) {
4793       OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
4794          << "Attr *A) {\n";
4795       if (!Args.empty())
4796         OS << "    const auto *SA = cast<" << R.getName()
4797            << "Attr>(A); (void)SA;\n";
4798       OS << SS.str();
4799       OS << "  }\n";
4800     }
4801   }
4802 }
4803 
4804 void EmitClangAttrParserStringSwitches(RecordKeeper &Records, raw_ostream &OS) {
4805   emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS, Records);
4806   emitClangAttrArgContextList(Records, OS);
4807   emitClangAttrIdentifierArgList(Records, OS);
4808   emitClangAttrUnevaluatedStringLiteralList(Records, OS);
4809   emitClangAttrVariadicIdentifierArgList(Records, OS);
4810   emitClangAttrThisIsaIdentifierArgList(Records, OS);
4811   emitClangAttrAcceptsExprPack(Records, OS);
4812   emitClangAttrTypeArgList(Records, OS);
4813   emitClangAttrLateParsedList(Records, OS);
4814 }
4815 
4816 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
4817                                                         raw_ostream &OS) {
4818   getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
4819 }
4820 
4821 void EmitClangAttrDocTable(RecordKeeper &Records, raw_ostream &OS) {
4822   emitSourceFileHeader("Clang attribute documentation", OS, Records);
4823 
4824   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4825   for (const auto *A : Attrs) {
4826     if (!A->getValueAsBit("ASTNode"))
4827       continue;
4828     std::vector<Record *> Docs = A->getValueAsListOfDefs("Documentation");
4829     assert(!Docs.empty());
4830     // Only look at the first documentation if there are several.
4831     // (Currently there's only one such attr, revisit if this becomes common).
4832     StringRef Text =
4833         Docs.front()->getValueAsOptionalString("Content").value_or("");
4834     OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
4835        << "R\"reST(" << Text.trim() << ")reST\";\n";
4836   }
4837 }
4838 
4839 enum class SpellingKind : size_t {
4840   GNU,
4841   CXX11,
4842   C23,
4843   Declspec,
4844   Microsoft,
4845   Keyword,
4846   Pragma,
4847   HLSLSemantic,
4848   NumSpellingKinds
4849 };
4850 static const size_t NumSpellingKinds = (size_t)SpellingKind::NumSpellingKinds;
4851 
4852 class SpellingList {
4853   std::vector<std::string> Spellings[NumSpellingKinds];
4854 
4855 public:
4856   ArrayRef<std::string> operator[](SpellingKind K) const {
4857     return Spellings[(size_t)K];
4858   }
4859 
4860   void add(const Record &Attr, FlattenedSpelling Spelling) {
4861     SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
4862                             .Case("GNU", SpellingKind::GNU)
4863                             .Case("CXX11", SpellingKind::CXX11)
4864                             .Case("C23", SpellingKind::C23)
4865                             .Case("Declspec", SpellingKind::Declspec)
4866                             .Case("Microsoft", SpellingKind::Microsoft)
4867                             .Case("Keyword", SpellingKind::Keyword)
4868                             .Case("Pragma", SpellingKind::Pragma)
4869                             .Case("HLSLSemantic", SpellingKind::HLSLSemantic);
4870     std::string Name;
4871     if (!Spelling.nameSpace().empty()) {
4872       switch (Kind) {
4873       case SpellingKind::CXX11:
4874       case SpellingKind::C23:
4875         Name = Spelling.nameSpace() + "::";
4876         break;
4877       case SpellingKind::Pragma:
4878         Name = Spelling.nameSpace() + " ";
4879         break;
4880       default:
4881         PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
4882       }
4883     }
4884     Name += Spelling.name();
4885 
4886     Spellings[(size_t)Kind].push_back(Name);
4887   }
4888 };
4889 
4890 class DocumentationData {
4891 public:
4892   const Record *Documentation;
4893   const Record *Attribute;
4894   std::string Heading;
4895   SpellingList SupportedSpellings;
4896 
4897   DocumentationData(const Record &Documentation, const Record &Attribute,
4898                     std::pair<std::string, SpellingList> HeadingAndSpellings)
4899       : Documentation(&Documentation), Attribute(&Attribute),
4900         Heading(std::move(HeadingAndSpellings.first)),
4901         SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
4902 };
4903 
4904 static void WriteCategoryHeader(const Record *DocCategory,
4905                                 raw_ostream &OS) {
4906   const StringRef Name = DocCategory->getValueAsString("Name");
4907   OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
4908 
4909   // If there is content, print that as well.
4910   const StringRef ContentStr = DocCategory->getValueAsString("Content");
4911   // Trim leading and trailing newlines and spaces.
4912   OS << ContentStr.trim();
4913 
4914   OS << "\n\n";
4915 }
4916 
4917 static std::pair<std::string, SpellingList>
4918 GetAttributeHeadingAndSpellings(const Record &Documentation,
4919                                 const Record &Attribute,
4920                                 StringRef Cat) {
4921   // FIXME: there is no way to have a per-spelling category for the attribute
4922   // documentation. This may not be a limiting factor since the spellings
4923   // should generally be consistently applied across the category.
4924 
4925   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
4926   if (Spellings.empty())
4927     PrintFatalError(Attribute.getLoc(),
4928                     "Attribute has no supported spellings; cannot be "
4929                     "documented");
4930 
4931   // Determine the heading to be used for this attribute.
4932   std::string Heading = std::string(Documentation.getValueAsString("Heading"));
4933   if (Heading.empty()) {
4934     // If there's only one spelling, we can simply use that.
4935     if (Spellings.size() == 1)
4936       Heading = Spellings.begin()->name();
4937     else {
4938       std::set<std::string> Uniques;
4939       for (auto I = Spellings.begin(), E = Spellings.end();
4940            I != E; ++I) {
4941         std::string Spelling =
4942             std::string(NormalizeNameForSpellingComparison(I->name()));
4943         Uniques.insert(Spelling);
4944       }
4945       // If the semantic map has only one spelling, that is sufficient for our
4946       // needs.
4947       if (Uniques.size() == 1)
4948         Heading = *Uniques.begin();
4949       // If it's in the undocumented category, just construct a header by
4950       // concatenating all the spellings. Might not be great, but better than
4951       // nothing.
4952       else if (Cat == "Undocumented")
4953         Heading = llvm::join(Uniques.begin(), Uniques.end(), ", ");
4954     }
4955   }
4956 
4957   // If the heading is still empty, it is an error.
4958   if (Heading.empty())
4959     PrintFatalError(Attribute.getLoc(),
4960                     "This attribute requires a heading to be specified");
4961 
4962   SpellingList SupportedSpellings;
4963   for (const auto &I : Spellings)
4964     SupportedSpellings.add(Attribute, I);
4965 
4966   return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
4967 }
4968 
4969 static void WriteDocumentation(RecordKeeper &Records,
4970                                const DocumentationData &Doc, raw_ostream &OS) {
4971   OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
4972 
4973   // List what spelling syntaxes the attribute supports.
4974   // Note: "#pragma clang attribute" is handled outside the spelling kinds loop
4975   // so it must be last.
4976   OS << ".. csv-table:: Supported Syntaxes\n";
4977   OS << "   :header: \"GNU\", \"C++11\", \"C23\", \"``__declspec``\",";
4978   OS << " \"Keyword\", \"``#pragma``\", \"HLSL Semantic\", \"``#pragma clang ";
4979   OS << "attribute``\"\n\n   \"";
4980   for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
4981     SpellingKind K = (SpellingKind)Kind;
4982     // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4983     // support them.
4984     if (K == SpellingKind::Microsoft)
4985       continue;
4986 
4987     bool PrintedAny = false;
4988     for (StringRef Spelling : Doc.SupportedSpellings[K]) {
4989       if (PrintedAny)
4990         OS << " |br| ";
4991       OS << "``" << Spelling << "``";
4992       PrintedAny = true;
4993     }
4994 
4995     OS << "\",\"";
4996   }
4997 
4998   if (getPragmaAttributeSupport(Records).isAttributedSupported(
4999           *Doc.Attribute))
5000     OS << "Yes";
5001   OS << "\"\n\n";
5002 
5003   // If the attribute is deprecated, print a message about it, and possibly
5004   // provide a replacement attribute.
5005   if (!Doc.Documentation->isValueUnset("Deprecated")) {
5006     OS << "This attribute has been deprecated, and may be removed in a future "
5007        << "version of Clang.";
5008     const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
5009     const StringRef Replacement = Deprecated.getValueAsString("Replacement");
5010     if (!Replacement.empty())
5011       OS << "  This attribute has been superseded by ``" << Replacement
5012          << "``.";
5013     OS << "\n\n";
5014   }
5015 
5016   const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
5017   // Trim leading and trailing newlines and spaces.
5018   OS << ContentStr.trim();
5019 
5020   OS << "\n\n\n";
5021 }
5022 
5023 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
5024   // Get the documentation introduction paragraph.
5025   const Record *Documentation = Records.getDef("GlobalDocumentation");
5026   if (!Documentation) {
5027     PrintFatalError("The Documentation top-level definition is missing, "
5028                     "no documentation will be generated.");
5029     return;
5030   }
5031 
5032   OS << Documentation->getValueAsString("Intro") << "\n";
5033 
5034   // Gather the Documentation lists from each of the attributes, based on the
5035   // category provided.
5036   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
5037   struct CategoryLess {
5038     bool operator()(const Record *L, const Record *R) const {
5039       return L->getValueAsString("Name") < R->getValueAsString("Name");
5040     }
5041   };
5042   std::map<const Record *, std::vector<DocumentationData>, CategoryLess>
5043       SplitDocs;
5044   for (const auto *A : Attrs) {
5045     const Record &Attr = *A;
5046     std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
5047     for (const auto *D : Docs) {
5048       const Record &Doc = *D;
5049       const Record *Category = Doc.getValueAsDef("Category");
5050       // If the category is "InternalOnly", then there cannot be any other
5051       // documentation categories (otherwise, the attribute would be
5052       // emitted into the docs).
5053       const StringRef Cat = Category->getValueAsString("Name");
5054       bool InternalOnly = Cat == "InternalOnly";
5055       if (InternalOnly && Docs.size() > 1)
5056         PrintFatalError(Doc.getLoc(),
5057                         "Attribute is \"InternalOnly\", but has multiple "
5058                         "documentation categories");
5059 
5060       if (!InternalOnly)
5061         SplitDocs[Category].push_back(DocumentationData(
5062             Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr, Cat)));
5063     }
5064   }
5065 
5066   // Having split the attributes out based on what documentation goes where,
5067   // we can begin to generate sections of documentation.
5068   for (auto &I : SplitDocs) {
5069     WriteCategoryHeader(I.first, OS);
5070 
5071     llvm::sort(I.second,
5072                [](const DocumentationData &D1, const DocumentationData &D2) {
5073                  return D1.Heading < D2.Heading;
5074                });
5075 
5076     // Walk over each of the attributes in the category and write out their
5077     // documentation.
5078     for (const auto &Doc : I.second)
5079       WriteDocumentation(Records, Doc, OS);
5080   }
5081 }
5082 
5083 void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
5084                                                 raw_ostream &OS) {
5085   PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
5086   ParsedAttrMap Attrs = getParsedAttrList(Records);
5087   OS << "#pragma clang attribute supports the following attributes:\n";
5088   for (const auto &I : Attrs) {
5089     if (!Support.isAttributedSupported(*I.second))
5090       continue;
5091     OS << I.first;
5092     if (I.second->isValueUnset("Subjects")) {
5093       OS << " ()\n";
5094       continue;
5095     }
5096     const Record *SubjectObj = I.second->getValueAsDef("Subjects");
5097     std::vector<Record *> Subjects =
5098         SubjectObj->getValueAsListOfDefs("Subjects");
5099     OS << " (";
5100     bool PrintComma = false;
5101     for (const auto &Subject : llvm::enumerate(Subjects)) {
5102       if (!isSupportedPragmaClangAttributeSubject(*Subject.value()))
5103         continue;
5104       if (PrintComma)
5105         OS << ", ";
5106       PrintComma = true;
5107       PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
5108           Support.SubjectsToRules.find(Subject.value())->getSecond();
5109       if (RuleSet.isRule()) {
5110         OS << RuleSet.getRule().getEnumValueName();
5111         continue;
5112       }
5113       OS << "(";
5114       for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
5115         if (Rule.index())
5116           OS << ", ";
5117         OS << Rule.value().getEnumValueName();
5118       }
5119       OS << ")";
5120     }
5121     OS << ")\n";
5122   }
5123   OS << "End of supported attributes.\n";
5124 }
5125 
5126 } // end namespace clang
5127