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