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