xref: /freebsd/contrib/llvm-project/clang/utils/TableGen/ClangAttrEmitter.cpp (revision c8e7f78a3d28ff6e6223ed136ada8e1e2f34965e)
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         OS << "    switch (S) {\n";
2644         std::set<std::string> Uniques;
2645         unsigned Idx = 0;
2646         for (auto I = Spellings.begin(), E = Spellings.end(); I != E;
2647              ++I, ++Idx) {
2648           const FlattenedSpelling &S = *I;
2649           const auto &Name = SemanticToSyntacticMap[Idx];
2650           if (Uniques.insert(Name).second) {
2651             OS << "    case " << Name << ":\n";
2652             OS << "      return AttributeCommonInfo::Form";
2653             emitFormInitializer(OS, S, Name);
2654             OS << ";\n";
2655           }
2656         }
2657         OS << "    default:\n";
2658         OS << "      llvm_unreachable(\"Unknown attribute spelling!\");\n"
2659            << "      return AttributeCommonInfo::Form";
2660         emitFormInitializer(OS, Spellings[0], "0");
2661         OS << ";\n"
2662            << "    }\n"
2663            << "  }()";
2664       }
2665 
2666       OS << ");\n";
2667       OS << "  return Create";
2668       if (Implicit)
2669         OS << "Implicit";
2670       if (DelayedArgsOnly)
2671         OS << "WithDelayedArgs";
2672       OS << "(Ctx";
2673       if (!DelayedArgsOnly) {
2674         for (auto const &ai : Args) {
2675           if (ai->isFake() && !emitFake)
2676             continue;
2677           OS << ", ";
2678           ai->writeImplicitCtorArgs(OS);
2679         }
2680       } else {
2681         OS << ", ";
2682         DelayedArgs->writeImplicitCtorArgs(OS);
2683       }
2684       OS << ", I);\n";
2685       OS << "}\n\n";
2686     };
2687 
2688     auto emitCreates = [&](bool DelayedArgsOnly, bool emitFake) {
2689       emitCreate(true, DelayedArgsOnly, emitFake);
2690       emitCreate(false, DelayedArgsOnly, emitFake);
2691       emitCreateNoCI(true, DelayedArgsOnly, emitFake);
2692       emitCreateNoCI(false, DelayedArgsOnly, emitFake);
2693     };
2694 
2695     if (Header)
2696       OS << "  // Factory methods\n";
2697 
2698     // Emit a CreateImplicit that takes all the arguments.
2699     emitCreates(false, true);
2700 
2701     // Emit a CreateImplicit that takes all the non-fake arguments.
2702     if (HasFakeArg)
2703       emitCreates(false, false);
2704 
2705     // Emit a CreateWithDelayedArgs that takes only the dependent argument
2706     // expressions.
2707     if (DelayedArgs)
2708       emitCreates(true, false);
2709 
2710     // Emit constructors.
2711     auto emitCtor = [&](bool emitOpt, bool emitFake, bool emitNoArgs) {
2712       auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2713         if (emitNoArgs)
2714           return false;
2715         if (arg->isFake())
2716           return emitFake;
2717         if (arg->isOptional())
2718           return emitOpt;
2719         return true;
2720       };
2721       if (Header)
2722         OS << "  ";
2723       else
2724         OS << R.getName() << "Attr::";
2725       OS << R.getName()
2726          << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
2727       OS << '\n';
2728       for (auto const &ai : Args) {
2729         if (!shouldEmitArg(ai))
2730           continue;
2731         OS << "              , ";
2732         ai->writeCtorParameters(OS);
2733         OS << "\n";
2734       }
2735 
2736       OS << "             )";
2737       if (Header) {
2738         OS << ";\n";
2739         return;
2740       }
2741       OS << "\n  : " << SuperName << "(Ctx, CommonInfo, ";
2742       OS << "attr::" << R.getName() << ", "
2743          << (R.getValueAsBit("LateParsed") ? "true" : "false");
2744       if (Inheritable) {
2745         OS << ", "
2746            << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2747                                                               : "false");
2748       }
2749       OS << ")\n";
2750 
2751       for (auto const &ai : Args) {
2752         OS << "              , ";
2753         if (!shouldEmitArg(ai)) {
2754           ai->writeCtorDefaultInitializers(OS);
2755         } else {
2756           ai->writeCtorInitializers(OS);
2757         }
2758         OS << "\n";
2759       }
2760       if (DelayedArgs) {
2761         OS << "              , ";
2762         DelayedArgs->writeCtorDefaultInitializers(OS);
2763         OS << "\n";
2764       }
2765 
2766       OS << "  {\n";
2767 
2768       for (auto const &ai : Args) {
2769         if (!shouldEmitArg(ai))
2770           continue;
2771         ai->writeCtorBody(OS);
2772       }
2773       OS << "}\n\n";
2774     };
2775 
2776     if (Header)
2777       OS << "\n  // Constructors\n";
2778 
2779     // Emit a constructor that includes all the arguments.
2780     // This is necessary for cloning.
2781     emitCtor(true, true, false);
2782 
2783     // Emit a constructor that takes all the non-fake arguments.
2784     if (HasFakeArg)
2785       emitCtor(true, false, false);
2786 
2787     // Emit a constructor that takes all the non-fake, non-optional arguments.
2788     if (HasOptArg)
2789       emitCtor(false, false, false);
2790 
2791     // Emit constructors that takes no arguments if none already exists.
2792     // This is used for delaying arguments.
2793     bool HasRequiredArgs =
2794         llvm::count_if(Args, [=](const std::unique_ptr<Argument> &arg) {
2795           return !arg->isFake() && !arg->isOptional();
2796         });
2797     if (DelayedArgs && HasRequiredArgs)
2798       emitCtor(false, false, true);
2799 
2800     if (Header) {
2801       OS << '\n';
2802       OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2803       OS << "  void printPretty(raw_ostream &OS,\n"
2804          << "                   const PrintingPolicy &Policy) const;\n";
2805       OS << "  const char *getSpelling() const;\n";
2806     }
2807 
2808     if (!ElideSpelling) {
2809       assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2810       if (Header)
2811         OS << "  Spelling getSemanticSpelling() const;\n";
2812       else {
2813         OS << R.getName() << "Attr::Spelling " << R.getName()
2814            << "Attr::getSemanticSpelling() const {\n";
2815         WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
2816                                     SemanticToSyntacticMap, OS);
2817         OS << "}\n";
2818       }
2819     }
2820 
2821     if (Header)
2822       writeAttrAccessorDefinition(R, OS);
2823 
2824     for (auto const &ai : Args) {
2825       if (Header) {
2826         ai->writeAccessors(OS);
2827       } else {
2828         ai->writeAccessorDefinitions(OS);
2829       }
2830       OS << "\n\n";
2831 
2832       // Don't write conversion routines for fake arguments.
2833       if (ai->isFake()) continue;
2834 
2835       if (ai->isEnumArg())
2836         static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
2837                                                                      Header);
2838       else if (ai->isVariadicEnumArg())
2839         static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
2840             OS, Header);
2841     }
2842 
2843     if (Header) {
2844       if (DelayedArgs) {
2845         DelayedArgs->writeAccessors(OS);
2846         DelayedArgs->writeSetter(OS);
2847       }
2848 
2849       OS << R.getValueAsString("AdditionalMembers");
2850       OS << "\n\n";
2851 
2852       OS << "  static bool classof(const Attr *A) { return A->getKind() == "
2853          << "attr::" << R.getName() << "; }\n";
2854 
2855       OS << "};\n\n";
2856     } else {
2857       if (DelayedArgs)
2858         DelayedArgs->writeAccessorDefinitions(OS);
2859 
2860       OS << R.getName() << "Attr *" << R.getName()
2861          << "Attr::clone(ASTContext &C) const {\n";
2862       OS << "  auto *A = new (C) " << R.getName() << "Attr(C, *this";
2863       for (auto const &ai : Args) {
2864         OS << ", ";
2865         ai->writeCloneArgs(OS);
2866       }
2867       OS << ");\n";
2868       OS << "  A->Inherited = Inherited;\n";
2869       OS << "  A->IsPackExpansion = IsPackExpansion;\n";
2870       OS << "  A->setImplicit(Implicit);\n";
2871       if (DelayedArgs) {
2872         OS << "  A->setDelayedArgs(C, ";
2873         DelayedArgs->writeCloneArgs(OS);
2874         OS << ");\n";
2875       }
2876       OS << "  return A;\n}\n\n";
2877 
2878       writePrettyPrintFunction(R, Args, OS);
2879       writeGetSpellingFunction(R, OS);
2880     }
2881   }
2882 }
2883 // Emits the class definitions for attributes.
2884 void clang::EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2885   emitSourceFileHeader("Attribute classes' definitions", OS);
2886 
2887   OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2888   OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2889 
2890   emitAttributes(Records, OS, true);
2891 
2892   OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2893 }
2894 
2895 // Emits the class method definitions for attributes.
2896 void clang::EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2897   emitSourceFileHeader("Attribute classes' member function definitions", OS);
2898 
2899   emitAttributes(Records, OS, false);
2900 
2901   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2902 
2903   // Instead of relying on virtual dispatch we just create a huge dispatch
2904   // switch. This is both smaller and faster than virtual functions.
2905   auto EmitFunc = [&](const char *Method) {
2906     OS << "  switch (getKind()) {\n";
2907     for (const auto *Attr : Attrs) {
2908       const Record &R = *Attr;
2909       if (!R.getValueAsBit("ASTNode"))
2910         continue;
2911 
2912       OS << "  case attr::" << R.getName() << ":\n";
2913       OS << "    return cast<" << R.getName() << "Attr>(this)->" << Method
2914          << ";\n";
2915     }
2916     OS << "  }\n";
2917     OS << "  llvm_unreachable(\"Unexpected attribute kind!\");\n";
2918     OS << "}\n\n";
2919   };
2920 
2921   OS << "const char *Attr::getSpelling() const {\n";
2922   EmitFunc("getSpelling()");
2923 
2924   OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2925   EmitFunc("clone(C)");
2926 
2927   OS << "void Attr::printPretty(raw_ostream &OS, "
2928         "const PrintingPolicy &Policy) const {\n";
2929   EmitFunc("printPretty(OS, Policy)");
2930 }
2931 
2932 static void emitAttrList(raw_ostream &OS, StringRef Class,
2933                          const std::vector<Record*> &AttrList) {
2934   for (auto Cur : AttrList) {
2935     OS << Class << "(" << Cur->getName() << ")\n";
2936   }
2937 }
2938 
2939 // Determines if an attribute has a Pragma spelling.
2940 static bool AttrHasPragmaSpelling(const Record *R) {
2941   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2942   return llvm::any_of(Spellings, [](const FlattenedSpelling &S) {
2943     return S.variety() == "Pragma";
2944   });
2945 }
2946 
2947 namespace {
2948 
2949   struct AttrClassDescriptor {
2950     const char * const MacroName;
2951     const char * const TableGenName;
2952   };
2953 
2954 } // end anonymous namespace
2955 
2956 static const AttrClassDescriptor AttrClassDescriptors[] = {
2957   { "ATTR", "Attr" },
2958   { "TYPE_ATTR", "TypeAttr" },
2959   { "STMT_ATTR", "StmtAttr" },
2960   { "DECL_OR_STMT_ATTR", "DeclOrStmtAttr" },
2961   { "INHERITABLE_ATTR", "InheritableAttr" },
2962   { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
2963   { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2964   { "PARAMETER_ABI_ATTR", "ParameterABIAttr" },
2965   { "HLSL_ANNOTATION_ATTR", "HLSLAnnotationAttr"}
2966 };
2967 
2968 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2969                               const char *superName) {
2970   OS << "#ifndef " << name << "\n";
2971   OS << "#define " << name << "(NAME) ";
2972   if (superName) OS << superName << "(NAME)";
2973   OS << "\n#endif\n\n";
2974 }
2975 
2976 namespace {
2977 
2978   /// A class of attributes.
2979   struct AttrClass {
2980     const AttrClassDescriptor &Descriptor;
2981     Record *TheRecord;
2982     AttrClass *SuperClass = nullptr;
2983     std::vector<AttrClass*> SubClasses;
2984     std::vector<Record*> Attrs;
2985 
2986     AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2987       : Descriptor(Descriptor), TheRecord(R) {}
2988 
2989     void emitDefaultDefines(raw_ostream &OS) const {
2990       // Default the macro unless this is a root class (i.e. Attr).
2991       if (SuperClass) {
2992         emitDefaultDefine(OS, Descriptor.MacroName,
2993                           SuperClass->Descriptor.MacroName);
2994       }
2995     }
2996 
2997     void emitUndefs(raw_ostream &OS) const {
2998       OS << "#undef " << Descriptor.MacroName << "\n";
2999     }
3000 
3001     void emitAttrList(raw_ostream &OS) const {
3002       for (auto SubClass : SubClasses) {
3003         SubClass->emitAttrList(OS);
3004       }
3005 
3006       ::emitAttrList(OS, Descriptor.MacroName, Attrs);
3007     }
3008 
3009     void classifyAttrOnRoot(Record *Attr) {
3010       bool result = classifyAttr(Attr);
3011       assert(result && "failed to classify on root"); (void) result;
3012     }
3013 
3014     void emitAttrRange(raw_ostream &OS) const {
3015       OS << "ATTR_RANGE(" << Descriptor.TableGenName
3016          << ", " << getFirstAttr()->getName()
3017          << ", " << getLastAttr()->getName() << ")\n";
3018     }
3019 
3020   private:
3021     bool classifyAttr(Record *Attr) {
3022       // Check all the subclasses.
3023       for (auto SubClass : SubClasses) {
3024         if (SubClass->classifyAttr(Attr))
3025           return true;
3026       }
3027 
3028       // It's not more specific than this class, but it might still belong here.
3029       if (Attr->isSubClassOf(TheRecord)) {
3030         Attrs.push_back(Attr);
3031         return true;
3032       }
3033 
3034       return false;
3035     }
3036 
3037     Record *getFirstAttr() const {
3038       if (!SubClasses.empty())
3039         return SubClasses.front()->getFirstAttr();
3040       return Attrs.front();
3041     }
3042 
3043     Record *getLastAttr() const {
3044       if (!Attrs.empty())
3045         return Attrs.back();
3046       return SubClasses.back()->getLastAttr();
3047     }
3048   };
3049 
3050   /// The entire hierarchy of attribute classes.
3051   class AttrClassHierarchy {
3052     std::vector<std::unique_ptr<AttrClass>> Classes;
3053 
3054   public:
3055     AttrClassHierarchy(RecordKeeper &Records) {
3056       // Find records for all the classes.
3057       for (auto &Descriptor : AttrClassDescriptors) {
3058         Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
3059         AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
3060         Classes.emplace_back(Class);
3061       }
3062 
3063       // Link up the hierarchy.
3064       for (auto &Class : Classes) {
3065         if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
3066           Class->SuperClass = SuperClass;
3067           SuperClass->SubClasses.push_back(Class.get());
3068         }
3069       }
3070 
3071 #ifndef NDEBUG
3072       for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
3073         assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
3074                "only the first class should be a root class!");
3075       }
3076 #endif
3077     }
3078 
3079     void emitDefaultDefines(raw_ostream &OS) const {
3080       for (auto &Class : Classes) {
3081         Class->emitDefaultDefines(OS);
3082       }
3083     }
3084 
3085     void emitUndefs(raw_ostream &OS) const {
3086       for (auto &Class : Classes) {
3087         Class->emitUndefs(OS);
3088       }
3089     }
3090 
3091     void emitAttrLists(raw_ostream &OS) const {
3092       // Just start from the root class.
3093       Classes[0]->emitAttrList(OS);
3094     }
3095 
3096     void emitAttrRanges(raw_ostream &OS) const {
3097       for (auto &Class : Classes)
3098         Class->emitAttrRange(OS);
3099     }
3100 
3101     void classifyAttr(Record *Attr) {
3102       // Add the attribute to the root class.
3103       Classes[0]->classifyAttrOnRoot(Attr);
3104     }
3105 
3106   private:
3107     AttrClass *findClassByRecord(Record *R) const {
3108       for (auto &Class : Classes) {
3109         if (Class->TheRecord == R)
3110           return Class.get();
3111       }
3112       return nullptr;
3113     }
3114 
3115     AttrClass *findSuperClass(Record *R) const {
3116       // TableGen flattens the superclass list, so we just need to walk it
3117       // in reverse.
3118       auto SuperClasses = R->getSuperClasses();
3119       for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
3120         auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
3121         if (SuperClass) return SuperClass;
3122       }
3123       return nullptr;
3124     }
3125   };
3126 
3127 } // end anonymous namespace
3128 
3129 namespace clang {
3130 
3131 // Emits the enumeration list for attributes.
3132 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
3133   emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3134 
3135   AttrClassHierarchy Hierarchy(Records);
3136 
3137   // Add defaulting macro definitions.
3138   Hierarchy.emitDefaultDefines(OS);
3139   emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
3140 
3141   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3142   std::vector<Record *> PragmaAttrs;
3143   for (auto *Attr : Attrs) {
3144     if (!Attr->getValueAsBit("ASTNode"))
3145       continue;
3146 
3147     // Add the attribute to the ad-hoc groups.
3148     if (AttrHasPragmaSpelling(Attr))
3149       PragmaAttrs.push_back(Attr);
3150 
3151     // Place it in the hierarchy.
3152     Hierarchy.classifyAttr(Attr);
3153   }
3154 
3155   // Emit the main attribute list.
3156   Hierarchy.emitAttrLists(OS);
3157 
3158   // Emit the ad hoc groups.
3159   emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
3160 
3161   // Emit the attribute ranges.
3162   OS << "#ifdef ATTR_RANGE\n";
3163   Hierarchy.emitAttrRanges(OS);
3164   OS << "#undef ATTR_RANGE\n";
3165   OS << "#endif\n";
3166 
3167   Hierarchy.emitUndefs(OS);
3168   OS << "#undef PRAGMA_SPELLING_ATTR\n";
3169 }
3170 
3171 // Emits the enumeration list for attributes.
3172 void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
3173   emitSourceFileHeader(
3174       "List of all attribute subject matching rules that Clang recognizes", OS);
3175   PragmaClangAttributeSupport &PragmaAttributeSupport =
3176       getPragmaAttributeSupport(Records);
3177   emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
3178   PragmaAttributeSupport.emitMatchRuleList(OS);
3179   OS << "#undef ATTR_MATCH_RULE\n";
3180 }
3181 
3182 // Emits the code to read an attribute from a precompiled header.
3183 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
3184   emitSourceFileHeader("Attribute deserialization code", OS);
3185 
3186   Record *InhClass = Records.getClass("InheritableAttr");
3187   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
3188                        ArgRecords;
3189   std::vector<std::unique_ptr<Argument>> Args;
3190   std::unique_ptr<VariadicExprArgument> DelayedArgs;
3191 
3192   OS << "  switch (Kind) {\n";
3193   for (const auto *Attr : Attrs) {
3194     const Record &R = *Attr;
3195     if (!R.getValueAsBit("ASTNode"))
3196       continue;
3197 
3198     OS << "  case attr::" << R.getName() << ": {\n";
3199     if (R.isSubClassOf(InhClass))
3200       OS << "    bool isInherited = Record.readInt();\n";
3201     OS << "    bool isImplicit = Record.readInt();\n";
3202     OS << "    bool isPackExpansion = Record.readInt();\n";
3203     DelayedArgs = nullptr;
3204     if (Attr->getValueAsBit("AcceptsExprPack")) {
3205       DelayedArgs =
3206           std::make_unique<VariadicExprArgument>("DelayedArgs", R.getName());
3207       DelayedArgs->writePCHReadDecls(OS);
3208     }
3209     ArgRecords = R.getValueAsListOfDefs("Args");
3210     Args.clear();
3211     for (const auto *Arg : ArgRecords) {
3212       Args.emplace_back(createArgument(*Arg, R.getName()));
3213       Args.back()->writePCHReadDecls(OS);
3214     }
3215     OS << "    New = new (Context) " << R.getName() << "Attr(Context, Info";
3216     for (auto const &ri : Args) {
3217       OS << ", ";
3218       ri->writePCHReadArgs(OS);
3219     }
3220     OS << ");\n";
3221     if (R.isSubClassOf(InhClass))
3222       OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
3223     OS << "    New->setImplicit(isImplicit);\n";
3224     OS << "    New->setPackExpansion(isPackExpansion);\n";
3225     if (DelayedArgs) {
3226       OS << "    cast<" << R.getName()
3227          << "Attr>(New)->setDelayedArgs(Context, ";
3228       DelayedArgs->writePCHReadArgs(OS);
3229       OS << ");\n";
3230     }
3231     OS << "    break;\n";
3232     OS << "  }\n";
3233   }
3234   OS << "  }\n";
3235 }
3236 
3237 // Emits the code to write an attribute to a precompiled header.
3238 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
3239   emitSourceFileHeader("Attribute serialization code", OS);
3240 
3241   Record *InhClass = Records.getClass("InheritableAttr");
3242   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3243 
3244   OS << "  switch (A->getKind()) {\n";
3245   for (const auto *Attr : Attrs) {
3246     const Record &R = *Attr;
3247     if (!R.getValueAsBit("ASTNode"))
3248       continue;
3249     OS << "  case attr::" << R.getName() << ": {\n";
3250     Args = R.getValueAsListOfDefs("Args");
3251     if (R.isSubClassOf(InhClass) || !Args.empty())
3252       OS << "    const auto *SA = cast<" << R.getName()
3253          << "Attr>(A);\n";
3254     if (R.isSubClassOf(InhClass))
3255       OS << "    Record.push_back(SA->isInherited());\n";
3256     OS << "    Record.push_back(A->isImplicit());\n";
3257     OS << "    Record.push_back(A->isPackExpansion());\n";
3258     if (Attr->getValueAsBit("AcceptsExprPack"))
3259       VariadicExprArgument("DelayedArgs", R.getName()).writePCHWrite(OS);
3260 
3261     for (const auto *Arg : Args)
3262       createArgument(*Arg, R.getName())->writePCHWrite(OS);
3263     OS << "    break;\n";
3264     OS << "  }\n";
3265   }
3266   OS << "  }\n";
3267 }
3268 
3269 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
3270 // parameter with only a single check type, if applicable.
3271 static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
3272                                             std::string *FnName,
3273                                             StringRef ListName,
3274                                             StringRef CheckAgainst,
3275                                             StringRef Scope) {
3276   if (!R->isValueUnset(ListName)) {
3277     Test += " && (";
3278     std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
3279     for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
3280       StringRef Part = *I;
3281       Test += CheckAgainst;
3282       Test += " == ";
3283       Test += Scope;
3284       Test += Part;
3285       if (I + 1 != E)
3286         Test += " || ";
3287       if (FnName)
3288         *FnName += Part;
3289     }
3290     Test += ")";
3291     return true;
3292   }
3293   return false;
3294 }
3295 
3296 // Generate a conditional expression to check if the current target satisfies
3297 // the conditions for a TargetSpecificAttr record, and append the code for
3298 // those checks to the Test string. If the FnName string pointer is non-null,
3299 // append a unique suffix to distinguish this set of target checks from other
3300 // TargetSpecificAttr records.
3301 static bool GenerateTargetSpecificAttrChecks(const Record *R,
3302                                              std::vector<StringRef> &Arches,
3303                                              std::string &Test,
3304                                              std::string *FnName) {
3305   bool AnyTargetChecks = false;
3306 
3307   // It is assumed that there will be an llvm::Triple object
3308   // named "T" and a TargetInfo object named "Target" within
3309   // scope that can be used to determine whether the attribute exists in
3310   // a given target.
3311   Test += "true";
3312   // If one or more architectures is specified, check those.  Arches are handled
3313   // differently because GenerateTargetRequirements needs to combine the list
3314   // with ParseKind.
3315   if (!Arches.empty()) {
3316     AnyTargetChecks = true;
3317     Test += " && (";
3318     for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3319       StringRef Part = *I;
3320       Test += "T.getArch() == llvm::Triple::";
3321       Test += Part;
3322       if (I + 1 != E)
3323         Test += " || ";
3324       if (FnName)
3325         *FnName += Part;
3326     }
3327     Test += ")";
3328   }
3329 
3330   // If the attribute is specific to particular OSes, check those.
3331   AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3332       R, Test, FnName, "OSes", "T.getOS()", "llvm::Triple::");
3333 
3334   // If one or more object formats is specified, check those.
3335   AnyTargetChecks |=
3336       GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
3337                                       "T.getObjectFormat()", "llvm::Triple::");
3338 
3339   // If custom code is specified, emit it.
3340   StringRef Code = R->getValueAsString("CustomCode");
3341   if (!Code.empty()) {
3342     AnyTargetChecks = true;
3343     Test += " && (";
3344     Test += Code;
3345     Test += ")";
3346   }
3347 
3348   return AnyTargetChecks;
3349 }
3350 
3351 static void GenerateHasAttrSpellingStringSwitch(
3352     const std::vector<Record *> &Attrs, raw_ostream &OS,
3353     const std::string &Variety = "", const std::string &Scope = "") {
3354   for (const auto *Attr : Attrs) {
3355     // C++11-style attributes have specific version information associated with
3356     // them. If the attribute has no scope, the version information must not
3357     // have the default value (1), as that's incorrect. Instead, the unscoped
3358     // attribute version information should be taken from the SD-6 standing
3359     // document, which can be found at:
3360     // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3361     //
3362     // C2x-style attributes have the same kind of version information
3363     // associated with them. The unscoped attribute version information should
3364     // be taken from the specification of the attribute in the C Standard.
3365     //
3366     // Clang-specific attributes have the same kind of version information
3367     // associated with them. This version is typically the default value (1).
3368     // These version values are clang-specific and should typically be
3369     // incremented once the attribute changes its syntax and/or semantics in a
3370     // a way that is impactful to the end user.
3371     int Version = 1;
3372 
3373     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
3374     for (const auto &Spelling : Spellings) {
3375       if (Spelling.variety() == Variety &&
3376           (Spelling.nameSpace().empty() || Scope == Spelling.nameSpace())) {
3377         Version = static_cast<int>(
3378             Spelling.getSpellingRecord().getValueAsInt("Version"));
3379         // Verify that explicitly specified CXX11 and C2x spellings (i.e.
3380         // not inferred from Clang/GCC spellings) have a version that's
3381         // different than the default (1).
3382         bool RequiresValidVersion =
3383             (Variety == "CXX11" || Variety == "C2x") &&
3384             Spelling.getSpellingRecord().getValueAsString("Variety") == Variety;
3385         if (RequiresValidVersion && Scope.empty() && Version == 1)
3386           PrintError(Spelling.getSpellingRecord().getLoc(),
3387                      "Standard attributes must have "
3388                      "valid version information.");
3389         break;
3390       }
3391     }
3392 
3393     std::string Test;
3394     if (Attr->isSubClassOf("TargetSpecificAttr")) {
3395       const Record *R = Attr->getValueAsDef("Target");
3396       std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3397       GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
3398 
3399       // If this is the C++11 variety, also add in the LangOpts test.
3400       if (Variety == "CXX11")
3401         Test += " && LangOpts.CPlusPlus11";
3402     } else if (Variety == "CXX11")
3403       // C++11 mode should be checked against LangOpts, which is presumed to be
3404       // present in the caller.
3405       Test = "LangOpts.CPlusPlus11";
3406 
3407     std::string TestStr = !Test.empty()
3408                               ? Test + " ? " + llvm::itostr(Version) + " : 0"
3409                               : llvm::itostr(Version);
3410     for (const auto &S : Spellings)
3411       if (Variety.empty() || (Variety == S.variety() &&
3412                               (Scope.empty() || Scope == S.nameSpace())))
3413         OS << "    .Case(\"" << S.name() << "\", " << TestStr << ")\n";
3414   }
3415   OS << "    .Default(0);\n";
3416 }
3417 
3418 // Emits the list of tokens for regular keyword attributes.
3419 void EmitClangAttrTokenKinds(RecordKeeper &Records, raw_ostream &OS) {
3420   emitSourceFileHeader("A list of tokens generated from the attribute"
3421                        " definitions",
3422                        OS);
3423   // Assume for now that the same token is not used in multiple regular
3424   // keyword attributes.
3425   for (auto *R : Records.getAllDerivedDefinitions("Attr"))
3426     for (const auto &S : GetFlattenedSpellings(*R))
3427       if (isRegularKeywordAttribute(S)) {
3428         if (!R->getValueAsListOfDefs("Args").empty())
3429           PrintError(R->getLoc(),
3430                      "RegularKeyword attributes with arguments are not "
3431                      "yet supported");
3432         OS << "KEYWORD_ATTRIBUTE("
3433            << S.getSpellingRecord().getValueAsString("Name") << ")\n";
3434       }
3435   OS << "#undef KEYWORD_ATTRIBUTE\n";
3436 }
3437 
3438 // Emits the list of spellings for attributes.
3439 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3440   emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
3441 
3442   // Separate all of the attributes out into four group: generic, C++11, GNU,
3443   // and declspecs. Then generate a big switch statement for each of them.
3444   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3445   std::vector<Record *> Declspec, Microsoft, GNU, Pragma, HLSLSemantic;
3446   std::map<std::string, std::vector<Record *>> CXX, C2x;
3447 
3448   // Walk over the list of all attributes, and split them out based on the
3449   // spelling variety.
3450   for (auto *R : Attrs) {
3451     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
3452     for (const auto &SI : Spellings) {
3453       const std::string &Variety = SI.variety();
3454       if (Variety == "GNU")
3455         GNU.push_back(R);
3456       else if (Variety == "Declspec")
3457         Declspec.push_back(R);
3458       else if (Variety == "Microsoft")
3459         Microsoft.push_back(R);
3460       else if (Variety == "CXX11")
3461         CXX[SI.nameSpace()].push_back(R);
3462       else if (Variety == "C2x")
3463         C2x[SI.nameSpace()].push_back(R);
3464       else if (Variety == "Pragma")
3465         Pragma.push_back(R);
3466       else if (Variety == "HLSLSemantic")
3467         HLSLSemantic.push_back(R);
3468     }
3469   }
3470 
3471   OS << "const llvm::Triple &T = Target.getTriple();\n";
3472   OS << "switch (Syntax) {\n";
3473   OS << "case AttributeCommonInfo::Syntax::AS_GNU:\n";
3474   OS << "  return llvm::StringSwitch<int>(Name)\n";
3475   GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
3476   OS << "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
3477   OS << "  return llvm::StringSwitch<int>(Name)\n";
3478   GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
3479   OS << "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
3480   OS << "  return llvm::StringSwitch<int>(Name)\n";
3481   GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
3482   OS << "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
3483   OS << "  return llvm::StringSwitch<int>(Name)\n";
3484   GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
3485   OS << "case AttributeCommonInfo::Syntax::AS_HLSLSemantic:\n";
3486   OS << "  return llvm::StringSwitch<int>(Name)\n";
3487   GenerateHasAttrSpellingStringSwitch(HLSLSemantic, OS, "HLSLSemantic");
3488   auto fn = [&OS](const char *Spelling,
3489                   const std::map<std::string, std::vector<Record *>> &List) {
3490     OS << "case AttributeCommonInfo::Syntax::AS_" << Spelling << ": {\n";
3491     // C++11-style attributes are further split out based on the Scope.
3492     for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
3493       if (I != List.cbegin())
3494         OS << " else ";
3495       if (I->first.empty())
3496         OS << "if (ScopeName == \"\") {\n";
3497       else
3498         OS << "if (ScopeName == \"" << I->first << "\") {\n";
3499       OS << "  return llvm::StringSwitch<int>(Name)\n";
3500       GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
3501       OS << "}";
3502     }
3503     OS << "\n} break;\n";
3504   };
3505   fn("CXX11", CXX);
3506   fn("C2x", C2x);
3507   OS << "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
3508   OS << "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
3509   OS << "  llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
3510   OS << "  return 0;\n";
3511   OS << "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
3512   OS << "  llvm_unreachable (\"hasAttribute not supported for "
3513         "AS_Implicit\");\n";
3514   OS << "  return 0;\n";
3515 
3516   OS << "}\n";
3517 }
3518 
3519 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
3520   emitSourceFileHeader("Code to translate different attribute spellings "
3521                        "into internal identifiers", OS);
3522 
3523   OS << "  switch (getParsedKind()) {\n";
3524   OS << "    case IgnoredAttribute:\n";
3525   OS << "    case UnknownAttribute:\n";
3526   OS << "    case NoSemaHandlerAttribute:\n";
3527   OS << "      llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3528 
3529   ParsedAttrMap Attrs = getParsedAttrList(Records);
3530   for (const auto &I : Attrs) {
3531     const Record &R = *I.second;
3532     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3533     OS << "  case AT_" << I.first << ": {\n";
3534     for (unsigned I = 0; I < Spellings.size(); ++ I) {
3535       OS << "    if (Name == \"" << Spellings[I].name() << "\" && "
3536          << "getSyntax() == AttributeCommonInfo::AS_" << Spellings[I].variety()
3537          << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
3538          << "        return " << I << ";\n";
3539     }
3540 
3541     OS << "    break;\n";
3542     OS << "  }\n";
3543   }
3544 
3545   OS << "  }\n";
3546   OS << "  return 0;\n";
3547 }
3548 
3549 // Emits code used by RecursiveASTVisitor to visit attributes
3550 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
3551   emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
3552 
3553   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3554 
3555   // Write method declarations for Traverse* methods.
3556   // We emit this here because we only generate methods for attributes that
3557   // are declared as ASTNodes.
3558   OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3559   for (const auto *Attr : Attrs) {
3560     const Record &R = *Attr;
3561     if (!R.getValueAsBit("ASTNode"))
3562       continue;
3563     OS << "  bool Traverse"
3564        << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3565     OS << "  bool Visit"
3566        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3567        << "    return true; \n"
3568        << "  }\n";
3569   }
3570   OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3571 
3572   // Write individual Traverse* methods for each attribute class.
3573   for (const auto *Attr : Attrs) {
3574     const Record &R = *Attr;
3575     if (!R.getValueAsBit("ASTNode"))
3576       continue;
3577 
3578     OS << "template <typename Derived>\n"
3579        << "bool VISITORCLASS<Derived>::Traverse"
3580        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3581        << "  if (!getDerived().VisitAttr(A))\n"
3582        << "    return false;\n"
3583        << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3584        << "    return false;\n";
3585 
3586     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3587     for (const auto *Arg : ArgRecords)
3588       createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3589 
3590     if (Attr->getValueAsBit("AcceptsExprPack"))
3591       VariadicExprArgument("DelayedArgs", R.getName())
3592           .writeASTVisitorTraversal(OS);
3593 
3594     OS << "  return true;\n";
3595     OS << "}\n\n";
3596   }
3597 
3598   // Write generic Traverse routine
3599   OS << "template <typename Derived>\n"
3600      << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3601      << "  if (!A)\n"
3602      << "    return true;\n"
3603      << "\n"
3604      << "  switch (A->getKind()) {\n";
3605 
3606   for (const auto *Attr : Attrs) {
3607     const Record &R = *Attr;
3608     if (!R.getValueAsBit("ASTNode"))
3609       continue;
3610 
3611     OS << "    case attr::" << R.getName() << ":\n"
3612        << "      return getDerived().Traverse" << R.getName() << "Attr("
3613        << "cast<" << R.getName() << "Attr>(A));\n";
3614   }
3615   OS << "  }\n";  // end switch
3616   OS << "  llvm_unreachable(\"bad attribute kind\");\n";
3617   OS << "}\n";  // end function
3618   OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
3619 }
3620 
3621 void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3622                                             raw_ostream &OS,
3623                                             bool AppliesToDecl) {
3624 
3625   OS << "  switch (At->getKind()) {\n";
3626   for (const auto *Attr : Attrs) {
3627     const Record &R = *Attr;
3628     if (!R.getValueAsBit("ASTNode"))
3629       continue;
3630     OS << "    case attr::" << R.getName() << ": {\n";
3631     bool ShouldClone = R.getValueAsBit("Clone") &&
3632                        (!AppliesToDecl ||
3633                         R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3634 
3635     if (!ShouldClone) {
3636       OS << "      return nullptr;\n";
3637       OS << "    }\n";
3638       continue;
3639     }
3640 
3641     OS << "      const auto *A = cast<"
3642        << R.getName() << "Attr>(At);\n";
3643     bool TDependent = R.getValueAsBit("TemplateDependent");
3644 
3645     if (!TDependent) {
3646       OS << "      return A->clone(C);\n";
3647       OS << "    }\n";
3648       continue;
3649     }
3650 
3651     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3652     std::vector<std::unique_ptr<Argument>> Args;
3653     Args.reserve(ArgRecords.size());
3654 
3655     for (const auto *ArgRecord : ArgRecords)
3656       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
3657 
3658     for (auto const &ai : Args)
3659       ai->writeTemplateInstantiation(OS);
3660 
3661     OS << "      return new (C) " << R.getName() << "Attr(C, *A";
3662     for (auto const &ai : Args) {
3663       OS << ", ";
3664       ai->writeTemplateInstantiationArgs(OS);
3665     }
3666     OS << ");\n"
3667        << "    }\n";
3668   }
3669   OS << "  } // end switch\n"
3670      << "  llvm_unreachable(\"Unknown attribute!\");\n"
3671      << "  return nullptr;\n";
3672 }
3673 
3674 // Emits code to instantiate dependent attributes on templates.
3675 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3676   emitSourceFileHeader("Template instantiation code for attributes", OS);
3677 
3678   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3679 
3680   OS << "namespace clang {\n"
3681      << "namespace sema {\n\n"
3682      << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3683      << "Sema &S,\n"
3684      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3685   EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3686   OS << "}\n\n"
3687      << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3688      << " ASTContext &C, Sema &S,\n"
3689      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3690   EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3691   OS << "}\n\n"
3692      << "} // end namespace sema\n"
3693      << "} // end namespace clang\n";
3694 }
3695 
3696 // Emits the list of parsed attributes.
3697 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3698   emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3699 
3700   OS << "#ifndef PARSED_ATTR\n";
3701   OS << "#define PARSED_ATTR(NAME) NAME\n";
3702   OS << "#endif\n\n";
3703 
3704   ParsedAttrMap Names = getParsedAttrList(Records);
3705   for (const auto &I : Names) {
3706     OS << "PARSED_ATTR(" << I.first << ")\n";
3707   }
3708 }
3709 
3710 static bool isArgVariadic(const Record &R, StringRef AttrName) {
3711   return createArgument(R, AttrName)->isVariadic();
3712 }
3713 
3714 static void emitArgInfo(const Record &R, raw_ostream &OS) {
3715   // This function will count the number of arguments specified for the
3716   // attribute and emit the number of required arguments followed by the
3717   // number of optional arguments.
3718   std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3719   unsigned ArgCount = 0, OptCount = 0, ArgMemberCount = 0;
3720   bool HasVariadic = false;
3721   for (const auto *Arg : Args) {
3722     // If the arg is fake, it's the user's job to supply it: general parsing
3723     // logic shouldn't need to know anything about it.
3724     if (Arg->getValueAsBit("Fake"))
3725       continue;
3726     Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3727     ++ArgMemberCount;
3728     if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3729       HasVariadic = true;
3730   }
3731 
3732   // If there is a variadic argument, we will set the optional argument count
3733   // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3734   OS << "    /*NumArgs=*/" << ArgCount << ",\n";
3735   OS << "    /*OptArgs=*/" << (HasVariadic ? 15 : OptCount) << ",\n";
3736   OS << "    /*NumArgMembers=*/" << ArgMemberCount << ",\n";
3737 }
3738 
3739 static std::string GetDiagnosticSpelling(const Record &R) {
3740   std::string Ret = std::string(R.getValueAsString("DiagSpelling"));
3741   if (!Ret.empty())
3742     return Ret;
3743 
3744   // If we couldn't find the DiagSpelling in this object, we can check to see
3745   // if the object is one that has a base, and if it is, loop up to the Base
3746   // member recursively.
3747   if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
3748     return GetDiagnosticSpelling(*Base);
3749 
3750   return "";
3751 }
3752 
3753 static std::string CalculateDiagnostic(const Record &S) {
3754   // If the SubjectList object has a custom diagnostic associated with it,
3755   // return that directly.
3756   const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3757   if (!CustomDiag.empty())
3758     return ("\"" + Twine(CustomDiag) + "\"").str();
3759 
3760   std::vector<std::string> DiagList;
3761   std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3762   for (const auto *Subject : Subjects) {
3763     const Record &R = *Subject;
3764     // Get the diagnostic text from the Decl or Stmt node given.
3765     std::string V = GetDiagnosticSpelling(R);
3766     if (V.empty()) {
3767       PrintError(R.getLoc(),
3768                  "Could not determine diagnostic spelling for the node: " +
3769                      R.getName() + "; please add one to DeclNodes.td");
3770     } else {
3771       // The node may contain a list of elements itself, so split the elements
3772       // by a comma, and trim any whitespace.
3773       SmallVector<StringRef, 2> Frags;
3774       llvm::SplitString(V, Frags, ",");
3775       for (auto Str : Frags) {
3776         DiagList.push_back(std::string(Str.trim()));
3777       }
3778     }
3779   }
3780 
3781   if (DiagList.empty()) {
3782     PrintFatalError(S.getLoc(),
3783                     "Could not deduce diagnostic argument for Attr subjects");
3784     return "";
3785   }
3786 
3787   // FIXME: this is not particularly good for localization purposes and ideally
3788   // should be part of the diagnostics engine itself with some sort of list
3789   // specifier.
3790 
3791   // A single member of the list can be returned directly.
3792   if (DiagList.size() == 1)
3793     return '"' + DiagList.front() + '"';
3794 
3795   if (DiagList.size() == 2)
3796     return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3797 
3798   // If there are more than two in the list, we serialize the first N - 1
3799   // elements with a comma. This leaves the string in the state: foo, bar,
3800   // baz (but misses quux). We can then add ", and " for the last element
3801   // manually.
3802   std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3803   return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3804 }
3805 
3806 static std::string GetSubjectWithSuffix(const Record *R) {
3807   const std::string &B = std::string(R->getName());
3808   if (B == "DeclBase")
3809     return "Decl";
3810   return B + "Decl";
3811 }
3812 
3813 static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3814   return "is" + Subject.getName().str();
3815 }
3816 
3817 static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
3818   std::string FnName = functionNameForCustomAppertainsTo(Subject);
3819 
3820   // If this code has already been generated, we don't need to do anything.
3821   static std::set<std::string> CustomSubjectSet;
3822   auto I = CustomSubjectSet.find(FnName);
3823   if (I != CustomSubjectSet.end())
3824     return;
3825 
3826   // This only works with non-root Decls.
3827   Record *Base = Subject.getValueAsDef(BaseFieldName);
3828 
3829   // Not currently support custom subjects within custom subjects.
3830   if (Base->isSubClassOf("SubsetSubject")) {
3831     PrintFatalError(Subject.getLoc(),
3832                     "SubsetSubjects within SubsetSubjects is not supported");
3833     return;
3834   }
3835 
3836   OS << "static bool " << FnName << "(const Decl *D) {\n";
3837   OS << "  if (const auto *S = dyn_cast<";
3838   OS << GetSubjectWithSuffix(Base);
3839   OS << ">(D))\n";
3840   OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
3841   OS << "  return false;\n";
3842   OS << "}\n\n";
3843 
3844   CustomSubjectSet.insert(FnName);
3845 }
3846 
3847 static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3848   // If the attribute does not contain a Subjects definition, then use the
3849   // default appertainsTo logic.
3850   if (Attr.isValueUnset("Subjects"))
3851     return;
3852 
3853   const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3854   std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3855 
3856   // If the list of subjects is empty, it is assumed that the attribute
3857   // appertains to everything.
3858   if (Subjects.empty())
3859     return;
3860 
3861   bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3862 
3863   // Split the subjects into declaration subjects and statement subjects.
3864   // FIXME: subset subjects are added to the declaration list until there are
3865   // enough statement attributes with custom subject needs to warrant
3866   // the implementation effort.
3867   std::vector<Record *> DeclSubjects, StmtSubjects;
3868   llvm::copy_if(
3869       Subjects, std::back_inserter(DeclSubjects), [](const Record *R) {
3870         return R->isSubClassOf("SubsetSubject") || !R->isSubClassOf("StmtNode");
3871       });
3872   llvm::copy_if(Subjects, std::back_inserter(StmtSubjects),
3873                 [](const Record *R) { return R->isSubClassOf("StmtNode"); });
3874 
3875   // We should have sorted all of the subjects into two lists.
3876   // FIXME: this assertion will be wrong if we ever add type attribute subjects.
3877   assert(DeclSubjects.size() + StmtSubjects.size() == Subjects.size());
3878 
3879   if (DeclSubjects.empty()) {
3880     // If there are no decl subjects but there are stmt subjects, diagnose
3881     // trying to apply a statement attribute to a declaration.
3882     if (!StmtSubjects.empty()) {
3883       OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
3884       OS << "const Decl *D) const override {\n";
3885       OS << "  S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
3886       OS << "    << AL << AL.isRegularKeywordAttribute() << "
3887             "D->getLocation();\n";
3888       OS << "  return false;\n";
3889       OS << "}\n\n";
3890     }
3891   } else {
3892     // Otherwise, generate an appertainsTo check specific to this attribute
3893     // which checks all of the given subjects against the Decl passed in.
3894     OS << "bool diagAppertainsToDecl(Sema &S, ";
3895     OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
3896     OS << "  if (";
3897     for (auto I = DeclSubjects.begin(), E = DeclSubjects.end(); I != E; ++I) {
3898       // If the subject has custom code associated with it, use the generated
3899       // function for it. The function cannot be inlined into this check (yet)
3900       // because it requires the subject to be of a specific type, and were that
3901       // information inlined here, it would not support an attribute with
3902       // multiple custom subjects.
3903       if ((*I)->isSubClassOf("SubsetSubject"))
3904         OS << "!" << functionNameForCustomAppertainsTo(**I) << "(D)";
3905       else
3906         OS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3907 
3908       if (I + 1 != E)
3909         OS << " && ";
3910     }
3911     OS << ") {\n";
3912     OS << "    S.Diag(Attr.getLoc(), diag::";
3913     OS << (Warn ? "warn_attribute_wrong_decl_type_str"
3914                 : "err_attribute_wrong_decl_type_str");
3915     OS << ")\n";
3916     OS << "      << Attr << Attr.isRegularKeywordAttribute() << ";
3917     OS << CalculateDiagnostic(*SubjectObj) << ";\n";
3918     OS << "    return false;\n";
3919     OS << "  }\n";
3920     OS << "  return true;\n";
3921     OS << "}\n\n";
3922   }
3923 
3924   if (StmtSubjects.empty()) {
3925     // If there are no stmt subjects but there are decl subjects, diagnose
3926     // trying to apply a declaration attribute to a statement.
3927     if (!DeclSubjects.empty()) {
3928       OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
3929       OS << "const Stmt *St) const override {\n";
3930       OS << "  S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
3931       OS << "    << AL << AL.isRegularKeywordAttribute() << "
3932             "St->getBeginLoc();\n";
3933       OS << "  return false;\n";
3934       OS << "}\n\n";
3935     }
3936   } else {
3937     // Now, do the same for statements.
3938     OS << "bool diagAppertainsToStmt(Sema &S, ";
3939     OS << "const ParsedAttr &Attr, const Stmt *St) const override {\n";
3940     OS << "  if (";
3941     for (auto I = StmtSubjects.begin(), E = StmtSubjects.end(); I != E; ++I) {
3942       OS << "!isa<" << (*I)->getName() << ">(St)";
3943       if (I + 1 != E)
3944         OS << " && ";
3945     }
3946     OS << ") {\n";
3947     OS << "    S.Diag(Attr.getLoc(), diag::";
3948     OS << (Warn ? "warn_attribute_wrong_decl_type_str"
3949                 : "err_attribute_wrong_decl_type_str");
3950     OS << ")\n";
3951     OS << "      << Attr << Attr.isRegularKeywordAttribute() << ";
3952     OS << CalculateDiagnostic(*SubjectObj) << ";\n";
3953     OS << "    return false;\n";
3954     OS << "  }\n";
3955     OS << "  return true;\n";
3956     OS << "}\n\n";
3957   }
3958 }
3959 
3960 // Generates the mutual exclusion checks. The checks for parsed attributes are
3961 // written into OS and the checks for merging declaration attributes are
3962 // written into MergeOS.
3963 static void GenerateMutualExclusionsChecks(const Record &Attr,
3964                                            const RecordKeeper &Records,
3965                                            raw_ostream &OS,
3966                                            raw_ostream &MergeDeclOS,
3967                                            raw_ostream &MergeStmtOS) {
3968   // Find all of the definitions that inherit from MutualExclusions and include
3969   // the given attribute in the list of exclusions to generate the
3970   // diagMutualExclusion() check.
3971   std::vector<Record *> ExclusionsList =
3972       Records.getAllDerivedDefinitions("MutualExclusions");
3973 
3974   // We don't do any of this magic for type attributes yet.
3975   if (Attr.isSubClassOf("TypeAttr"))
3976     return;
3977 
3978   // This means the attribute is either a statement attribute, a decl
3979   // attribute, or both; find out which.
3980   bool CurAttrIsStmtAttr =
3981       Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr");
3982   bool CurAttrIsDeclAttr =
3983       !CurAttrIsStmtAttr || Attr.isSubClassOf("DeclOrStmtAttr");
3984 
3985   std::vector<std::string> DeclAttrs, StmtAttrs;
3986 
3987   for (const Record *Exclusion : ExclusionsList) {
3988     std::vector<Record *> MutuallyExclusiveAttrs =
3989         Exclusion->getValueAsListOfDefs("Exclusions");
3990     auto IsCurAttr = [Attr](const Record *R) {
3991       return R->getName() == Attr.getName();
3992     };
3993     if (llvm::any_of(MutuallyExclusiveAttrs, IsCurAttr)) {
3994       // This list of exclusions includes the attribute we're looking for, so
3995       // add the exclusive attributes to the proper list for checking.
3996       for (const Record *AttrToExclude : MutuallyExclusiveAttrs) {
3997         if (IsCurAttr(AttrToExclude))
3998           continue;
3999 
4000         if (CurAttrIsStmtAttr)
4001           StmtAttrs.push_back((AttrToExclude->getName() + "Attr").str());
4002         if (CurAttrIsDeclAttr)
4003           DeclAttrs.push_back((AttrToExclude->getName() + "Attr").str());
4004       }
4005     }
4006   }
4007 
4008   // If there are any decl or stmt attributes, silence -Woverloaded-virtual
4009   // warnings for them both.
4010   if (!DeclAttrs.empty() || !StmtAttrs.empty())
4011     OS << "  using ParsedAttrInfo::diagMutualExclusion;\n\n";
4012 
4013   // If we discovered any decl or stmt attributes to test for, generate the
4014   // predicates for them now.
4015   if (!DeclAttrs.empty()) {
4016     // Generate the ParsedAttrInfo subclass logic for declarations.
4017     OS << "  bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
4018        << "const Decl *D) const override {\n";
4019     for (const std::string &A : DeclAttrs) {
4020       OS << "    if (const auto *A = D->getAttr<" << A << ">()) {\n";
4021       OS << "      S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
4022          << " << AL << A << (AL.isRegularKeywordAttribute() ||"
4023          << " A->isRegularKeywordAttribute());\n";
4024       OS << "      S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
4025       OS << "      \nreturn false;\n";
4026       OS << "    }\n";
4027     }
4028     OS << "    return true;\n";
4029     OS << "  }\n\n";
4030 
4031     // Also generate the declaration attribute merging logic if the current
4032     // attribute is one that can be inheritted on a declaration. It is assumed
4033     // this code will be executed in the context of a function with parameters:
4034     // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
4035     // true on success).
4036     if (Attr.isSubClassOf("InheritableAttr")) {
4037       MergeDeclOS << "  if (const auto *Second = dyn_cast<"
4038                   << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4039       for (const std::string &A : DeclAttrs) {
4040         MergeDeclOS << "    if (const auto *First = D->getAttr<" << A
4041                     << ">()) {\n";
4042         MergeDeclOS << "      S.Diag(First->getLocation(), "
4043                     << "diag::err_attributes_are_not_compatible) << First << "
4044                     << "Second << (First->isRegularKeywordAttribute() || "
4045                     << "Second->isRegularKeywordAttribute());\n";
4046         MergeDeclOS << "      S.Diag(Second->getLocation(), "
4047                     << "diag::note_conflicting_attribute);\n";
4048         MergeDeclOS << "      return false;\n";
4049         MergeDeclOS << "    }\n";
4050       }
4051       MergeDeclOS << "    return true;\n";
4052       MergeDeclOS << "  }\n";
4053     }
4054   }
4055 
4056   // Statement attributes are a bit different from declarations. With
4057   // declarations, each attribute is added to the declaration as it is
4058   // processed, and so you can look on the Decl * itself to see if there is a
4059   // conflicting attribute. Statement attributes are processed as a group
4060   // because AttributedStmt needs to tail-allocate all of the attribute nodes
4061   // at once. This means we cannot check whether the statement already contains
4062   // an attribute to check for the conflict. Instead, we need to check whether
4063   // the given list of semantic attributes contain any conflicts. It is assumed
4064   // this code will be executed in the context of a function with parameters:
4065   // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
4066   // loop which loops over the container C with a loop variable named A to
4067   // represent the current attribute to check for conflicts.
4068   //
4069   // FIXME: it would be nice not to walk over the list of potential attributes
4070   // to apply to the statement more than once, but statements typically don't
4071   // have long lists of attributes on them, so re-walking the list should not
4072   // be an expensive operation.
4073   if (!StmtAttrs.empty()) {
4074     MergeStmtOS << "    if (const auto *Second = dyn_cast<"
4075                 << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4076     MergeStmtOS << "      auto Iter = llvm::find_if(C, [](const Attr *Check) "
4077                 << "{ return isa<";
4078     interleave(
4079         StmtAttrs, [&](const std::string &Name) { MergeStmtOS << Name; },
4080         [&] { MergeStmtOS << ", "; });
4081     MergeStmtOS << ">(Check); });\n";
4082     MergeStmtOS << "      if (Iter != C.end()) {\n";
4083     MergeStmtOS << "        S.Diag((*Iter)->getLocation(), "
4084                 << "diag::err_attributes_are_not_compatible) << *Iter << "
4085                 << "Second << ((*Iter)->isRegularKeywordAttribute() || "
4086                 << "Second->isRegularKeywordAttribute());\n";
4087     MergeStmtOS << "        S.Diag(Second->getLocation(), "
4088                 << "diag::note_conflicting_attribute);\n";
4089     MergeStmtOS << "        return false;\n";
4090     MergeStmtOS << "      }\n";
4091     MergeStmtOS << "    }\n";
4092   }
4093 }
4094 
4095 static void
4096 emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
4097                         raw_ostream &OS) {
4098   OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
4099      << AttributeSubjectMatchRule::EnumName << " rule) {\n";
4100   OS << "  switch (rule) {\n";
4101   for (const auto &Rule : PragmaAttributeSupport.Rules) {
4102     if (Rule.isAbstractRule()) {
4103       OS << "  case " << Rule.getEnumValue() << ":\n";
4104       OS << "    assert(false && \"Abstract matcher rule isn't allowed\");\n";
4105       OS << "    return false;\n";
4106       continue;
4107     }
4108     std::vector<Record *> Subjects = Rule.getSubjects();
4109     assert(!Subjects.empty() && "Missing subjects");
4110     OS << "  case " << Rule.getEnumValue() << ":\n";
4111     OS << "    return ";
4112     for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
4113       // If the subject has custom code associated with it, use the function
4114       // that was generated for GenerateAppertainsTo to check if the declaration
4115       // is valid.
4116       if ((*I)->isSubClassOf("SubsetSubject"))
4117         OS << functionNameForCustomAppertainsTo(**I) << "(D)";
4118       else
4119         OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
4120 
4121       if (I + 1 != E)
4122         OS << " || ";
4123     }
4124     OS << ";\n";
4125   }
4126   OS << "  }\n";
4127   OS << "  llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
4128   OS << "}\n\n";
4129 }
4130 
4131 static void GenerateLangOptRequirements(const Record &R,
4132                                         raw_ostream &OS) {
4133   // If the attribute has an empty or unset list of language requirements,
4134   // use the default handler.
4135   std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
4136   if (LangOpts.empty())
4137     return;
4138 
4139   OS << "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
4140   OS << "  return " << GenerateTestExpression(LangOpts) << ";\n";
4141   OS << "}\n\n";
4142 }
4143 
4144 static void GenerateTargetRequirements(const Record &Attr,
4145                                        const ParsedAttrMap &Dupes,
4146                                        raw_ostream &OS) {
4147   // If the attribute is not a target specific attribute, use the default
4148   // target handler.
4149   if (!Attr.isSubClassOf("TargetSpecificAttr"))
4150     return;
4151 
4152   // Get the list of architectures to be tested for.
4153   const Record *R = Attr.getValueAsDef("Target");
4154   std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
4155 
4156   // If there are other attributes which share the same parsed attribute kind,
4157   // such as target-specific attributes with a shared spelling, collapse the
4158   // duplicate architectures. This is required because a shared target-specific
4159   // attribute has only one ParsedAttr::Kind enumeration value, but it
4160   // applies to multiple target architectures. In order for the attribute to be
4161   // considered valid, all of its architectures need to be included.
4162   if (!Attr.isValueUnset("ParseKind")) {
4163     const StringRef APK = Attr.getValueAsString("ParseKind");
4164     for (const auto &I : Dupes) {
4165       if (I.first == APK) {
4166         std::vector<StringRef> DA =
4167             I.second->getValueAsDef("Target")->getValueAsListOfStrings(
4168                 "Arches");
4169         Arches.insert(Arches.end(), DA.begin(), DA.end());
4170       }
4171     }
4172   }
4173 
4174   std::string FnName = "isTarget";
4175   std::string Test;
4176   bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
4177 
4178   OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
4179   if (UsesT)
4180     OS << "  const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4181   OS << "  return " << Test << ";\n";
4182   OS << "}\n\n";
4183 }
4184 
4185 static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
4186                                                     raw_ostream &OS) {
4187   // If the attribute does not have a semantic form, we can bail out early.
4188   if (!Attr.getValueAsBit("ASTNode"))
4189     return;
4190 
4191   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4192 
4193   // If there are zero or one spellings, or all of the spellings share the same
4194   // name, we can also bail out early.
4195   if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
4196     return;
4197 
4198   // Generate the enumeration we will use for the mapping.
4199   SemanticSpellingMap SemanticToSyntacticMap;
4200   std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
4201   std::string Name = Attr.getName().str() + "AttrSpellingMap";
4202 
4203   OS << "unsigned spellingIndexToSemanticSpelling(";
4204   OS << "const ParsedAttr &Attr) const override {\n";
4205   OS << Enum;
4206   OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
4207   WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
4208   OS << "}\n\n";
4209 }
4210 
4211 static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
4212   // Only generate if Attr can be handled simply.
4213   if (!Attr.getValueAsBit("SimpleHandler"))
4214     return;
4215 
4216   // Generate a function which just converts from ParsedAttr to the Attr type.
4217   OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
4218   OS << "const ParsedAttr &Attr) const override {\n";
4219   OS << "  D->addAttr(::new (S.Context) " << Attr.getName();
4220   OS << "Attr(S.Context, Attr));\n";
4221   OS << "  return AttributeApplied;\n";
4222   OS << "}\n\n";
4223 }
4224 
4225 static bool isParamExpr(const Record *Arg) {
4226   return !Arg->getSuperClasses().empty() &&
4227          llvm::StringSwitch<bool>(
4228              Arg->getSuperClasses().back().first->getName())
4229              .Case("ExprArgument", true)
4230              .Case("VariadicExprArgument", true)
4231              .Default(false);
4232 }
4233 
4234 void GenerateIsParamExpr(const Record &Attr, raw_ostream &OS) {
4235   OS << "bool isParamExpr(size_t N) const override {\n";
4236   OS << "  return ";
4237   auto Args = Attr.getValueAsListOfDefs("Args");
4238   for (size_t I = 0; I < Args.size(); ++I)
4239     if (isParamExpr(Args[I]))
4240       OS << "(N == " << I << ") || ";
4241   OS << "false;\n";
4242   OS << "}\n\n";
4243 }
4244 
4245 void GenerateHandleAttrWithDelayedArgs(RecordKeeper &Records, raw_ostream &OS) {
4246   OS << "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
4247   OS << "const ParsedAttr &Attr) {\n";
4248   OS << "  SmallVector<Expr *, 4> ArgExprs;\n";
4249   OS << "  ArgExprs.reserve(Attr.getNumArgs());\n";
4250   OS << "  for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
4251   OS << "    assert(!Attr.isArgIdent(I));\n";
4252   OS << "    ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
4253   OS << "  }\n";
4254   OS << "  clang::Attr *CreatedAttr = nullptr;\n";
4255   OS << "  switch (Attr.getKind()) {\n";
4256   OS << "  default:\n";
4257   OS << "    llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
4258   ParsedAttrMap Attrs = getParsedAttrList(Records);
4259   for (const auto &I : Attrs) {
4260     const Record &R = *I.second;
4261     if (!R.getValueAsBit("AcceptsExprPack"))
4262       continue;
4263     OS << "  case ParsedAttr::AT_" << I.first << ": {\n";
4264     OS << "    CreatedAttr = " << R.getName() << "Attr::CreateWithDelayedArgs";
4265     OS << "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
4266     OS << "    break;\n";
4267     OS << "  }\n";
4268   }
4269   OS << "  }\n";
4270   OS << "  D->addAttr(CreatedAttr);\n";
4271   OS << "}\n\n";
4272 }
4273 
4274 static bool IsKnownToGCC(const Record &Attr) {
4275   // Look at the spellings for this subject; if there are any spellings which
4276   // claim to be known to GCC, the attribute is known to GCC.
4277   return llvm::any_of(
4278       GetFlattenedSpellings(Attr),
4279       [](const FlattenedSpelling &S) { return S.knownToGCC(); });
4280 }
4281 
4282 /// Emits the parsed attribute helpers
4283 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
4284   emitSourceFileHeader("Parsed attribute helpers", OS);
4285 
4286   OS << "#if !defined(WANT_DECL_MERGE_LOGIC) && "
4287      << "!defined(WANT_STMT_MERGE_LOGIC)\n";
4288   PragmaClangAttributeSupport &PragmaAttributeSupport =
4289       getPragmaAttributeSupport(Records);
4290 
4291   // Get the list of parsed attributes, and accept the optional list of
4292   // duplicates due to the ParseKind.
4293   ParsedAttrMap Dupes;
4294   ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
4295 
4296   // Generate all of the custom appertainsTo functions that the attributes
4297   // will be using.
4298   for (const auto &I : Attrs) {
4299     const Record &Attr = *I.second;
4300     if (Attr.isValueUnset("Subjects"))
4301       continue;
4302     const Record *SubjectObj = Attr.getValueAsDef("Subjects");
4303     for (auto Subject : SubjectObj->getValueAsListOfDefs("Subjects"))
4304       if (Subject->isSubClassOf("SubsetSubject"))
4305         GenerateCustomAppertainsTo(*Subject, OS);
4306   }
4307 
4308   // This stream is used to collect all of the declaration attribute merging
4309   // logic for performing mutual exclusion checks. This gets emitted at the
4310   // end of the file in a helper function of its own.
4311   std::string DeclMergeChecks, StmtMergeChecks;
4312   raw_string_ostream MergeDeclOS(DeclMergeChecks), MergeStmtOS(StmtMergeChecks);
4313 
4314   // Generate a ParsedAttrInfo struct for each of the attributes.
4315   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4316     // TODO: If the attribute's kind appears in the list of duplicates, that is
4317     // because it is a target-specific attribute that appears multiple times.
4318     // It would be beneficial to test whether the duplicates are "similar
4319     // enough" to each other to not cause problems. For instance, check that
4320     // the spellings are identical, and custom parsing rules match, etc.
4321 
4322     // We need to generate struct instances based off ParsedAttrInfo from
4323     // ParsedAttr.cpp.
4324     const std::string &AttrName = I->first;
4325     const Record &Attr = *I->second;
4326     auto Spellings = GetFlattenedSpellings(Attr);
4327     if (!Spellings.empty()) {
4328       OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
4329          << "Spellings[] = {\n";
4330       for (const auto &S : Spellings) {
4331         const std::string &RawSpelling = S.name();
4332         std::string Spelling;
4333         if (!S.nameSpace().empty())
4334           Spelling += S.nameSpace() + "::";
4335         if (S.variety() == "GNU")
4336           Spelling += NormalizeGNUAttrSpelling(RawSpelling);
4337         else
4338           Spelling += RawSpelling;
4339         OS << "  {AttributeCommonInfo::AS_" << S.variety();
4340         OS << ", \"" << Spelling << "\"},\n";
4341       }
4342       OS << "};\n";
4343     }
4344 
4345     std::vector<std::string> ArgNames;
4346     for (const auto &Arg : Attr.getValueAsListOfDefs("Args")) {
4347       bool UnusedUnset;
4348       if (Arg->getValueAsBitOrUnset("Fake", UnusedUnset))
4349         continue;
4350       ArgNames.push_back(Arg->getValueAsString("Name").str());
4351       for (const auto &Class : Arg->getSuperClasses()) {
4352         if (Class.first->getName().startswith("Variadic")) {
4353           ArgNames.back().append("...");
4354           break;
4355         }
4356       }
4357     }
4358     if (!ArgNames.empty()) {
4359       OS << "static constexpr const char *" << I->first << "ArgNames[] = {\n";
4360       for (const auto &N : ArgNames)
4361         OS << '"' << N << "\",";
4362       OS << "};\n";
4363     }
4364 
4365     OS << "struct ParsedAttrInfo" << I->first
4366        << " final : public ParsedAttrInfo {\n";
4367     OS << "  constexpr ParsedAttrInfo" << I->first << "() : ParsedAttrInfo(\n";
4368     OS << "    /*AttrKind=*/ParsedAttr::AT_" << AttrName << ",\n";
4369     emitArgInfo(Attr, OS);
4370     OS << "    /*HasCustomParsing=*/";
4371     OS << Attr.getValueAsBit("HasCustomParsing") << ",\n";
4372     OS << "    /*AcceptsExprPack=*/";
4373     OS << Attr.getValueAsBit("AcceptsExprPack") << ",\n";
4374     OS << "    /*IsTargetSpecific=*/";
4375     OS << Attr.isSubClassOf("TargetSpecificAttr") << ",\n";
4376     OS << "    /*IsType=*/";
4377     OS << (Attr.isSubClassOf("TypeAttr") || Attr.isSubClassOf("DeclOrTypeAttr"))
4378        << ",\n";
4379     OS << "    /*IsStmt=*/";
4380     OS << (Attr.isSubClassOf("StmtAttr") || Attr.isSubClassOf("DeclOrStmtAttr"))
4381        << ",\n";
4382     OS << "    /*IsKnownToGCC=*/";
4383     OS << IsKnownToGCC(Attr) << ",\n";
4384     OS << "    /*IsSupportedByPragmaAttribute=*/";
4385     OS << PragmaAttributeSupport.isAttributedSupported(*I->second) << ",\n";
4386     if (!Spellings.empty())
4387       OS << "    /*Spellings=*/" << I->first << "Spellings,\n";
4388     else
4389       OS << "    /*Spellings=*/{},\n";
4390     if (!ArgNames.empty())
4391       OS << "    /*ArgNames=*/" << I->first << "ArgNames";
4392     else
4393       OS << "    /*ArgNames=*/{}";
4394     OS << ") {}\n";
4395     GenerateAppertainsTo(Attr, OS);
4396     GenerateMutualExclusionsChecks(Attr, Records, OS, MergeDeclOS, MergeStmtOS);
4397     GenerateLangOptRequirements(Attr, OS);
4398     GenerateTargetRequirements(Attr, Dupes, OS);
4399     GenerateSpellingIndexToSemanticSpelling(Attr, OS);
4400     PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
4401     GenerateHandleDeclAttribute(Attr, OS);
4402     GenerateIsParamExpr(Attr, OS);
4403     OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
4404     OS << "};\n";
4405     OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
4406        << "::Instance;\n";
4407   }
4408 
4409   OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
4410   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4411     OS << "&ParsedAttrInfo" << I->first << "::Instance,\n";
4412   }
4413   OS << "};\n\n";
4414 
4415   // Generate function for handling attributes with delayed arguments
4416   GenerateHandleAttrWithDelayedArgs(Records, OS);
4417 
4418   // Generate the attribute match rules.
4419   emitAttributeMatchRules(PragmaAttributeSupport, OS);
4420 
4421   OS << "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
4422 
4423   // Write out the declaration merging check logic.
4424   OS << "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
4425      << "const Attr *A) {\n";
4426   OS << MergeDeclOS.str();
4427   OS << "  return true;\n";
4428   OS << "}\n\n";
4429 
4430   OS << "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
4431 
4432   // Write out the statement merging check logic.
4433   OS << "static bool DiagnoseMutualExclusions(Sema &S, "
4434      << "const SmallVectorImpl<const Attr *> &C) {\n";
4435   OS << "  for (const Attr *A : C) {\n";
4436   OS << MergeStmtOS.str();
4437   OS << "  }\n";
4438   OS << "  return true;\n";
4439   OS << "}\n\n";
4440 
4441   OS << "#endif\n";
4442 }
4443 
4444 // Emits the kind list of parsed attributes
4445 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
4446   emitSourceFileHeader("Attribute name matcher", OS);
4447 
4448   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4449   std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
4450       Keywords, Pragma, C2x, HLSLSemantic;
4451   std::set<std::string> Seen;
4452   for (const auto *A : Attrs) {
4453     const Record &Attr = *A;
4454 
4455     bool SemaHandler = Attr.getValueAsBit("SemaHandler");
4456     bool Ignored = Attr.getValueAsBit("Ignored");
4457     if (SemaHandler || Ignored) {
4458       // Attribute spellings can be shared between target-specific attributes,
4459       // and can be shared between syntaxes for the same attribute. For
4460       // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
4461       // specific attribute, or MSP430-specific attribute. Additionally, an
4462       // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
4463       // for the same semantic attribute. Ultimately, we need to map each of
4464       // these to a single AttributeCommonInfo::Kind value, but the
4465       // StringMatcher class cannot handle duplicate match strings. So we
4466       // generate a list of string to match based on the syntax, and emit
4467       // multiple string matchers depending on the syntax used.
4468       std::string AttrName;
4469       if (Attr.isSubClassOf("TargetSpecificAttr") &&
4470           !Attr.isValueUnset("ParseKind")) {
4471         AttrName = std::string(Attr.getValueAsString("ParseKind"));
4472         if (!Seen.insert(AttrName).second)
4473           continue;
4474       } else
4475         AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
4476 
4477       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4478       for (const auto &S : Spellings) {
4479         const std::string &RawSpelling = S.name();
4480         std::vector<StringMatcher::StringPair> *Matches = nullptr;
4481         std::string Spelling;
4482         const std::string &Variety = S.variety();
4483         if (Variety == "CXX11") {
4484           Matches = &CXX11;
4485           if (!S.nameSpace().empty())
4486             Spelling += S.nameSpace() + "::";
4487         } else if (Variety == "C2x") {
4488           Matches = &C2x;
4489           if (!S.nameSpace().empty())
4490             Spelling += S.nameSpace() + "::";
4491         } else if (Variety == "GNU")
4492           Matches = &GNU;
4493         else if (Variety == "Declspec")
4494           Matches = &Declspec;
4495         else if (Variety == "Microsoft")
4496           Matches = &Microsoft;
4497         else if (Variety == "Keyword")
4498           Matches = &Keywords;
4499         else if (Variety == "Pragma")
4500           Matches = &Pragma;
4501         else if (Variety == "HLSLSemantic")
4502           Matches = &HLSLSemantic;
4503 
4504         assert(Matches && "Unsupported spelling variety found");
4505 
4506         if (Variety == "GNU")
4507           Spelling += NormalizeGNUAttrSpelling(RawSpelling);
4508         else
4509           Spelling += RawSpelling;
4510 
4511         if (SemaHandler)
4512           Matches->push_back(StringMatcher::StringPair(
4513               Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
4514         else
4515           Matches->push_back(StringMatcher::StringPair(
4516               Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
4517       }
4518     }
4519   }
4520 
4521   OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
4522   OS << "AttributeCommonInfo::Syntax Syntax) {\n";
4523   OS << "  if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
4524   StringMatcher("Name", GNU, OS).Emit();
4525   OS << "  } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
4526   StringMatcher("Name", Declspec, OS).Emit();
4527   OS << "  } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
4528   StringMatcher("Name", Microsoft, OS).Emit();
4529   OS << "  } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
4530   StringMatcher("Name", CXX11, OS).Emit();
4531   OS << "  } else if (AttributeCommonInfo::AS_C2x == Syntax) {\n";
4532   StringMatcher("Name", C2x, OS).Emit();
4533   OS << "  } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
4534   OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
4535   StringMatcher("Name", Keywords, OS).Emit();
4536   OS << "  } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
4537   StringMatcher("Name", Pragma, OS).Emit();
4538   OS << "  } else if (AttributeCommonInfo::AS_HLSLSemantic == Syntax) {\n";
4539   StringMatcher("Name", HLSLSemantic, OS).Emit();
4540   OS << "  }\n";
4541   OS << "  return AttributeCommonInfo::UnknownAttribute;\n"
4542      << "}\n";
4543 }
4544 
4545 // Emits the code to dump an attribute.
4546 void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
4547   emitSourceFileHeader("Attribute text node dumper", OS);
4548 
4549   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
4550   for (const auto *Attr : Attrs) {
4551     const Record &R = *Attr;
4552     if (!R.getValueAsBit("ASTNode"))
4553       continue;
4554 
4555     // If the attribute has a semantically-meaningful name (which is determined
4556     // by whether there is a Spelling enumeration for it), then write out the
4557     // spelling used for the attribute.
4558 
4559     std::string FunctionContent;
4560     llvm::raw_string_ostream SS(FunctionContent);
4561 
4562     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
4563     if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
4564       SS << "    OS << \" \" << A->getSpelling();\n";
4565 
4566     Args = R.getValueAsListOfDefs("Args");
4567     for (const auto *Arg : Args)
4568       createArgument(*Arg, R.getName())->writeDump(SS);
4569 
4570     if (Attr->getValueAsBit("AcceptsExprPack"))
4571       VariadicExprArgument("DelayedArgs", R.getName()).writeDump(OS);
4572 
4573     if (SS.tell()) {
4574       OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
4575          << "Attr *A) {\n";
4576       if (!Args.empty())
4577         OS << "    const auto *SA = cast<" << R.getName()
4578            << "Attr>(A); (void)SA;\n";
4579       OS << SS.str();
4580       OS << "  }\n";
4581     }
4582   }
4583 }
4584 
4585 void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
4586   emitSourceFileHeader("Attribute text node traverser", OS);
4587 
4588   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
4589   for (const auto *Attr : Attrs) {
4590     const Record &R = *Attr;
4591     if (!R.getValueAsBit("ASTNode"))
4592       continue;
4593 
4594     std::string FunctionContent;
4595     llvm::raw_string_ostream SS(FunctionContent);
4596 
4597     Args = R.getValueAsListOfDefs("Args");
4598     for (const auto *Arg : Args)
4599       createArgument(*Arg, R.getName())->writeDumpChildren(SS);
4600     if (Attr->getValueAsBit("AcceptsExprPack"))
4601       VariadicExprArgument("DelayedArgs", R.getName()).writeDumpChildren(SS);
4602     if (SS.tell()) {
4603       OS << "  void Visit" << R.getName() << "Attr(const " << R.getName()
4604          << "Attr *A) {\n";
4605       if (!Args.empty())
4606         OS << "    const auto *SA = cast<" << R.getName()
4607            << "Attr>(A); (void)SA;\n";
4608       OS << SS.str();
4609       OS << "  }\n";
4610     }
4611   }
4612 }
4613 
4614 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
4615                                        raw_ostream &OS) {
4616   emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
4617   emitClangAttrArgContextList(Records, OS);
4618   emitClangAttrIdentifierArgList(Records, OS);
4619   emitClangAttrVariadicIdentifierArgList(Records, OS);
4620   emitClangAttrThisIsaIdentifierArgList(Records, OS);
4621   emitClangAttrAcceptsExprPack(Records, OS);
4622   emitClangAttrTypeArgList(Records, OS);
4623   emitClangAttrLateParsedList(Records, OS);
4624 }
4625 
4626 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
4627                                                         raw_ostream &OS) {
4628   getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
4629 }
4630 
4631 void EmitClangAttrDocTable(RecordKeeper &Records, raw_ostream &OS) {
4632   emitSourceFileHeader("Clang attribute documentation", OS);
4633 
4634   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4635   for (const auto *A : Attrs) {
4636     if (!A->getValueAsBit("ASTNode"))
4637       continue;
4638     std::vector<Record *> Docs = A->getValueAsListOfDefs("Documentation");
4639     assert(!Docs.empty());
4640     // Only look at the first documentation if there are several.
4641     // (Currently there's only one such attr, revisit if this becomes common).
4642     StringRef Text =
4643         Docs.front()->getValueAsOptionalString("Content").value_or("");
4644     OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
4645        << "R\"reST(" << Text.trim() << ")reST\";\n";
4646   }
4647 }
4648 
4649 enum class SpellingKind : size_t {
4650   GNU,
4651   CXX11,
4652   C2x,
4653   Declspec,
4654   Microsoft,
4655   Keyword,
4656   Pragma,
4657   HLSLSemantic,
4658   NumSpellingKinds
4659 };
4660 static const size_t NumSpellingKinds = (size_t)SpellingKind::NumSpellingKinds;
4661 
4662 class SpellingList {
4663   std::vector<std::string> Spellings[NumSpellingKinds];
4664 
4665 public:
4666   ArrayRef<std::string> operator[](SpellingKind K) const {
4667     return Spellings[(size_t)K];
4668   }
4669 
4670   void add(const Record &Attr, FlattenedSpelling Spelling) {
4671     SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
4672                             .Case("GNU", SpellingKind::GNU)
4673                             .Case("CXX11", SpellingKind::CXX11)
4674                             .Case("C2x", SpellingKind::C2x)
4675                             .Case("Declspec", SpellingKind::Declspec)
4676                             .Case("Microsoft", SpellingKind::Microsoft)
4677                             .Case("Keyword", SpellingKind::Keyword)
4678                             .Case("Pragma", SpellingKind::Pragma)
4679                             .Case("HLSLSemantic", SpellingKind::HLSLSemantic);
4680     std::string Name;
4681     if (!Spelling.nameSpace().empty()) {
4682       switch (Kind) {
4683       case SpellingKind::CXX11:
4684       case SpellingKind::C2x:
4685         Name = Spelling.nameSpace() + "::";
4686         break;
4687       case SpellingKind::Pragma:
4688         Name = Spelling.nameSpace() + " ";
4689         break;
4690       default:
4691         PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
4692       }
4693     }
4694     Name += Spelling.name();
4695 
4696     Spellings[(size_t)Kind].push_back(Name);
4697   }
4698 };
4699 
4700 class DocumentationData {
4701 public:
4702   const Record *Documentation;
4703   const Record *Attribute;
4704   std::string Heading;
4705   SpellingList SupportedSpellings;
4706 
4707   DocumentationData(const Record &Documentation, const Record &Attribute,
4708                     std::pair<std::string, SpellingList> HeadingAndSpellings)
4709       : Documentation(&Documentation), Attribute(&Attribute),
4710         Heading(std::move(HeadingAndSpellings.first)),
4711         SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
4712 };
4713 
4714 static void WriteCategoryHeader(const Record *DocCategory,
4715                                 raw_ostream &OS) {
4716   const StringRef Name = DocCategory->getValueAsString("Name");
4717   OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
4718 
4719   // If there is content, print that as well.
4720   const StringRef ContentStr = DocCategory->getValueAsString("Content");
4721   // Trim leading and trailing newlines and spaces.
4722   OS << ContentStr.trim();
4723 
4724   OS << "\n\n";
4725 }
4726 
4727 static std::pair<std::string, SpellingList>
4728 GetAttributeHeadingAndSpellings(const Record &Documentation,
4729                                 const Record &Attribute,
4730                                 StringRef Cat) {
4731   // FIXME: there is no way to have a per-spelling category for the attribute
4732   // documentation. This may not be a limiting factor since the spellings
4733   // should generally be consistently applied across the category.
4734 
4735   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
4736   if (Spellings.empty())
4737     PrintFatalError(Attribute.getLoc(),
4738                     "Attribute has no supported spellings; cannot be "
4739                     "documented");
4740 
4741   // Determine the heading to be used for this attribute.
4742   std::string Heading = std::string(Documentation.getValueAsString("Heading"));
4743   if (Heading.empty()) {
4744     // If there's only one spelling, we can simply use that.
4745     if (Spellings.size() == 1)
4746       Heading = Spellings.begin()->name();
4747     else {
4748       std::set<std::string> Uniques;
4749       for (auto I = Spellings.begin(), E = Spellings.end();
4750            I != E; ++I) {
4751         std::string Spelling =
4752             std::string(NormalizeNameForSpellingComparison(I->name()));
4753         Uniques.insert(Spelling);
4754       }
4755       // If the semantic map has only one spelling, that is sufficient for our
4756       // needs.
4757       if (Uniques.size() == 1)
4758         Heading = *Uniques.begin();
4759       // If it's in the undocumented category, just construct a header by
4760       // concatenating all the spellings. Might not be great, but better than
4761       // nothing.
4762       else if (Cat == "Undocumented")
4763         Heading = llvm::join(Uniques.begin(), Uniques.end(), ", ");
4764     }
4765   }
4766 
4767   // If the heading is still empty, it is an error.
4768   if (Heading.empty())
4769     PrintFatalError(Attribute.getLoc(),
4770                     "This attribute requires a heading to be specified");
4771 
4772   SpellingList SupportedSpellings;
4773   for (const auto &I : Spellings)
4774     SupportedSpellings.add(Attribute, I);
4775 
4776   return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
4777 }
4778 
4779 static void WriteDocumentation(RecordKeeper &Records,
4780                                const DocumentationData &Doc, raw_ostream &OS) {
4781   OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
4782 
4783   // List what spelling syntaxes the attribute supports.
4784   // Note: "#pragma clang attribute" is handled outside the spelling kinds loop
4785   // so it must be last.
4786   OS << ".. csv-table:: Supported Syntaxes\n";
4787   OS << "   :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
4788   OS << " \"Keyword\", \"``#pragma``\", \"HLSL Semantic\", \"``#pragma clang ";
4789   OS << "attribute``\"\n\n   \"";
4790   for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
4791     SpellingKind K = (SpellingKind)Kind;
4792     // TODO: List Microsoft (IDL-style attribute) spellings once we fully
4793     // support them.
4794     if (K == SpellingKind::Microsoft)
4795       continue;
4796 
4797     bool PrintedAny = false;
4798     for (StringRef Spelling : Doc.SupportedSpellings[K]) {
4799       if (PrintedAny)
4800         OS << " |br| ";
4801       OS << "``" << Spelling << "``";
4802       PrintedAny = true;
4803     }
4804 
4805     OS << "\",\"";
4806   }
4807 
4808   if (getPragmaAttributeSupport(Records).isAttributedSupported(
4809           *Doc.Attribute))
4810     OS << "Yes";
4811   OS << "\"\n\n";
4812 
4813   // If the attribute is deprecated, print a message about it, and possibly
4814   // provide a replacement attribute.
4815   if (!Doc.Documentation->isValueUnset("Deprecated")) {
4816     OS << "This attribute has been deprecated, and may be removed in a future "
4817        << "version of Clang.";
4818     const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
4819     const StringRef Replacement = Deprecated.getValueAsString("Replacement");
4820     if (!Replacement.empty())
4821       OS << "  This attribute has been superseded by ``" << Replacement
4822          << "``.";
4823     OS << "\n\n";
4824   }
4825 
4826   const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
4827   // Trim leading and trailing newlines and spaces.
4828   OS << ContentStr.trim();
4829 
4830   OS << "\n\n\n";
4831 }
4832 
4833 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
4834   // Get the documentation introduction paragraph.
4835   const Record *Documentation = Records.getDef("GlobalDocumentation");
4836   if (!Documentation) {
4837     PrintFatalError("The Documentation top-level definition is missing, "
4838                     "no documentation will be generated.");
4839     return;
4840   }
4841 
4842   OS << Documentation->getValueAsString("Intro") << "\n";
4843 
4844   // Gather the Documentation lists from each of the attributes, based on the
4845   // category provided.
4846   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
4847   struct CategoryLess {
4848     bool operator()(const Record *L, const Record *R) const {
4849       return L->getValueAsString("Name") < R->getValueAsString("Name");
4850     }
4851   };
4852   std::map<const Record *, std::vector<DocumentationData>, CategoryLess>
4853       SplitDocs;
4854   for (const auto *A : Attrs) {
4855     const Record &Attr = *A;
4856     std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
4857     for (const auto *D : Docs) {
4858       const Record &Doc = *D;
4859       const Record *Category = Doc.getValueAsDef("Category");
4860       // If the category is "InternalOnly", then there cannot be any other
4861       // documentation categories (otherwise, the attribute would be
4862       // emitted into the docs).
4863       const StringRef Cat = Category->getValueAsString("Name");
4864       bool InternalOnly = Cat == "InternalOnly";
4865       if (InternalOnly && Docs.size() > 1)
4866         PrintFatalError(Doc.getLoc(),
4867                         "Attribute is \"InternalOnly\", but has multiple "
4868                         "documentation categories");
4869 
4870       if (!InternalOnly)
4871         SplitDocs[Category].push_back(DocumentationData(
4872             Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr, Cat)));
4873     }
4874   }
4875 
4876   // Having split the attributes out based on what documentation goes where,
4877   // we can begin to generate sections of documentation.
4878   for (auto &I : SplitDocs) {
4879     WriteCategoryHeader(I.first, OS);
4880 
4881     llvm::sort(I.second,
4882                [](const DocumentationData &D1, const DocumentationData &D2) {
4883                  return D1.Heading < D2.Heading;
4884                });
4885 
4886     // Walk over each of the attributes in the category and write out their
4887     // documentation.
4888     for (const auto &Doc : I.second)
4889       WriteDocumentation(Records, Doc, OS);
4890   }
4891 }
4892 
4893 void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4894                                                 raw_ostream &OS) {
4895   PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4896   ParsedAttrMap Attrs = getParsedAttrList(Records);
4897   OS << "#pragma clang attribute supports the following attributes:\n";
4898   for (const auto &I : Attrs) {
4899     if (!Support.isAttributedSupported(*I.second))
4900       continue;
4901     OS << I.first;
4902     if (I.second->isValueUnset("Subjects")) {
4903       OS << " ()\n";
4904       continue;
4905     }
4906     const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4907     std::vector<Record *> Subjects =
4908         SubjectObj->getValueAsListOfDefs("Subjects");
4909     OS << " (";
4910     bool PrintComma = false;
4911     for (const auto &Subject : llvm::enumerate(Subjects)) {
4912       if (!isSupportedPragmaClangAttributeSubject(*Subject.value()))
4913         continue;
4914       if (PrintComma)
4915         OS << ", ";
4916       PrintComma = true;
4917       PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4918           Support.SubjectsToRules.find(Subject.value())->getSecond();
4919       if (RuleSet.isRule()) {
4920         OS << RuleSet.getRule().getEnumValueName();
4921         continue;
4922       }
4923       OS << "(";
4924       for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4925         if (Rule.index())
4926           OS << ", ";
4927         OS << Rule.value().getEnumValueName();
4928       }
4929       OS << ")";
4930     }
4931     OS << ")\n";
4932   }
4933   OS << "End of supported attributes.\n";
4934 }
4935 
4936 } // end namespace clang
4937