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