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