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/SmallString.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/StringMatcher.h"
22 #include "llvm/TableGen/TableGenBackend.h"
23 #include <algorithm>
24 #include <cctype>
25 #include <memory>
26 #include <set>
27 #include <sstream>
28 
29 using namespace llvm;
30 
31 namespace {
32 class FlattenedSpelling {
33   std::string V, N, NS;
34   bool K;
35 
36 public:
37   FlattenedSpelling(const std::string &Variety, const std::string &Name,
38                     const std::string &Namespace, bool KnownToGCC) :
39     V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
40   explicit FlattenedSpelling(const Record &Spelling) :
41     V(Spelling.getValueAsString("Variety")),
42     N(Spelling.getValueAsString("Name")) {
43 
44     assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
45            "flattened!");
46     if (V == "CXX11" || V == "Pragma")
47       NS = Spelling.getValueAsString("Namespace");
48     bool Unset;
49     K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
50   }
51 
52   const std::string &variety() const { return V; }
53   const std::string &name() const { return N; }
54   const std::string &nameSpace() const { return NS; }
55   bool knownToGCC() const { return K; }
56 };
57 } // end anonymous namespace
58 
59 static std::vector<FlattenedSpelling>
60 GetFlattenedSpellings(const Record &Attr) {
61   std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
62   std::vector<FlattenedSpelling> Ret;
63 
64   for (const auto &Spelling : Spellings) {
65     if (Spelling->getValueAsString("Variety") == "GCC") {
66       // Gin up two new spelling objects to add into the list.
67       Ret.emplace_back("GNU", Spelling->getValueAsString("Name"), "", true);
68       Ret.emplace_back("CXX11", Spelling->getValueAsString("Name"), "gnu",
69                        true);
70     } else
71       Ret.push_back(FlattenedSpelling(*Spelling));
72   }
73 
74   return Ret;
75 }
76 
77 static std::string ReadPCHRecord(StringRef type) {
78   return StringSwitch<std::string>(type)
79     .EndsWith("Decl *", "GetLocalDeclAs<"
80               + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
81     .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
82     .Case("Expr *", "ReadExpr(F)")
83     .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
84     .Case("std::string", "ReadString(Record, Idx)")
85     .Default("Record[Idx++]");
86 }
87 
88 // Assumes that the way to get the value is SA->getname()
89 static std::string WritePCHRecord(StringRef type, StringRef name) {
90   return StringSwitch<std::string>(type)
91     .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
92                         ", Record);\n")
93     .Case("TypeSourceInfo *",
94           "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
95     .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
96     .Case("IdentifierInfo *",
97           "AddIdentifierRef(" + std::string(name) + ", Record);\n")
98     .Case("std::string", "AddString(" + std::string(name) + ", Record);\n")
99     .Default("Record.push_back(" + std::string(name) + ");\n");
100 }
101 
102 // Normalize attribute name by removing leading and trailing
103 // underscores. For example, __foo, foo__, __foo__ would
104 // become foo.
105 static StringRef NormalizeAttrName(StringRef AttrName) {
106   if (AttrName.startswith("__"))
107     AttrName = AttrName.substr(2, AttrName.size());
108 
109   if (AttrName.endswith("__"))
110     AttrName = AttrName.substr(0, AttrName.size() - 2);
111 
112   return AttrName;
113 }
114 
115 // Normalize the name by removing any and all leading and trailing underscores.
116 // This is different from NormalizeAttrName in that it also handles names like
117 // _pascal and __pascal.
118 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
119   return Name.trim("_");
120 }
121 
122 // Normalize attribute spelling only if the spelling has both leading
123 // and trailing underscores. For example, __ms_struct__ will be
124 // normalized to "ms_struct"; __cdecl will remain intact.
125 static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
126   if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
127     AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
128   }
129 
130   return AttrSpelling;
131 }
132 
133 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
134 
135 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
136                                        ParsedAttrMap *Dupes = nullptr) {
137   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
138   std::set<std::string> Seen;
139   ParsedAttrMap R;
140   for (const auto *Attr : Attrs) {
141     if (Attr->getValueAsBit("SemaHandler")) {
142       std::string AN;
143       if (Attr->isSubClassOf("TargetSpecificAttr") &&
144           !Attr->isValueUnset("ParseKind")) {
145         AN = Attr->getValueAsString("ParseKind");
146 
147         // If this attribute has already been handled, it does not need to be
148         // handled again.
149         if (Seen.find(AN) != Seen.end()) {
150           if (Dupes)
151             Dupes->push_back(std::make_pair(AN, Attr));
152           continue;
153         }
154         Seen.insert(AN);
155       } else
156         AN = NormalizeAttrName(Attr->getName()).str();
157 
158       R.push_back(std::make_pair(AN, Attr));
159     }
160   }
161   return R;
162 }
163 
164 namespace {
165   class Argument {
166     std::string lowerName, upperName;
167     StringRef attrName;
168     bool isOpt;
169 
170   public:
171     Argument(const Record &Arg, StringRef Attr)
172       : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
173         attrName(Attr), isOpt(false) {
174       if (!lowerName.empty()) {
175         lowerName[0] = std::tolower(lowerName[0]);
176         upperName[0] = std::toupper(upperName[0]);
177       }
178     }
179     virtual ~Argument() = default;
180 
181     StringRef getLowerName() const { return lowerName; }
182     StringRef getUpperName() const { return upperName; }
183     StringRef getAttrName() const { return attrName; }
184 
185     bool isOptional() const { return isOpt; }
186     void setOptional(bool set) { isOpt = set; }
187 
188     // These functions print the argument contents formatted in different ways.
189     virtual void writeAccessors(raw_ostream &OS) const = 0;
190     virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
191     virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
192     virtual void writeCloneArgs(raw_ostream &OS) const = 0;
193     virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
194     virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
195     virtual void writeCtorBody(raw_ostream &OS) const {}
196     virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
197     virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
198     virtual void writeCtorParameters(raw_ostream &OS) const = 0;
199     virtual void writeDeclarations(raw_ostream &OS) const = 0;
200     virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
201     virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
202     virtual void writePCHWrite(raw_ostream &OS) const = 0;
203     virtual void writeValue(raw_ostream &OS) const = 0;
204     virtual void writeDump(raw_ostream &OS) const = 0;
205     virtual void writeDumpChildren(raw_ostream &OS) const {}
206     virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
207 
208     virtual bool isEnumArg() const { return false; }
209     virtual bool isVariadicEnumArg() const { return false; }
210     virtual bool isVariadic() const { return false; }
211 
212     virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
213       OS << getUpperName();
214     }
215   };
216 
217   class SimpleArgument : public Argument {
218     std::string type;
219 
220   public:
221     SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
222       : Argument(Arg, Attr), type(T)
223     {}
224 
225     std::string getType() const { return type; }
226 
227     void writeAccessors(raw_ostream &OS) const override {
228       OS << "  " << type << " get" << getUpperName() << "() const {\n";
229       OS << "    return " << getLowerName() << ";\n";
230       OS << "  }";
231     }
232     void writeCloneArgs(raw_ostream &OS) const override {
233       OS << getLowerName();
234     }
235     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
236       OS << "A->get" << getUpperName() << "()";
237     }
238     void writeCtorInitializers(raw_ostream &OS) const override {
239       OS << getLowerName() << "(" << getUpperName() << ")";
240     }
241     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
242       OS << getLowerName() << "()";
243     }
244     void writeCtorParameters(raw_ostream &OS) const override {
245       OS << type << " " << getUpperName();
246     }
247     void writeDeclarations(raw_ostream &OS) const override {
248       OS << type << " " << getLowerName() << ";";
249     }
250     void writePCHReadDecls(raw_ostream &OS) const override {
251       std::string read = ReadPCHRecord(type);
252       OS << "    " << type << " " << getLowerName() << " = " << read << ";\n";
253     }
254     void writePCHReadArgs(raw_ostream &OS) const override {
255       OS << getLowerName();
256     }
257     void writePCHWrite(raw_ostream &OS) const override {
258       OS << "    " << WritePCHRecord(type, "SA->get" +
259                                            std::string(getUpperName()) + "()");
260     }
261     void writeValue(raw_ostream &OS) const override {
262       if (type == "FunctionDecl *") {
263         OS << "\" << get" << getUpperName()
264            << "()->getNameInfo().getAsString() << \"";
265       } else if (type == "IdentifierInfo *") {
266         OS << "\" << get" << getUpperName() << "()->getName() << \"";
267       } else if (type == "TypeSourceInfo *") {
268         OS << "\" << get" << getUpperName() << "().getAsString() << \"";
269       } else {
270         OS << "\" << get" << getUpperName() << "() << \"";
271       }
272     }
273     void writeDump(raw_ostream &OS) const override {
274       if (type == "FunctionDecl *") {
275         OS << "    OS << \" \";\n";
276         OS << "    dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
277       } else if (type == "IdentifierInfo *") {
278         OS << "    OS << \" \" << SA->get" << getUpperName()
279            << "()->getName();\n";
280       } else if (type == "TypeSourceInfo *") {
281         OS << "    OS << \" \" << SA->get" << getUpperName()
282            << "().getAsString();\n";
283       } else if (type == "bool") {
284         OS << "    if (SA->get" << getUpperName() << "()) OS << \" "
285            << getUpperName() << "\";\n";
286       } else if (type == "int" || type == "unsigned") {
287         OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
288       } else {
289         llvm_unreachable("Unknown SimpleArgument type!");
290       }
291     }
292   };
293 
294   class DefaultSimpleArgument : public SimpleArgument {
295     int64_t Default;
296 
297   public:
298     DefaultSimpleArgument(const Record &Arg, StringRef Attr,
299                           std::string T, int64_t Default)
300       : SimpleArgument(Arg, Attr, T), Default(Default) {}
301 
302     void writeAccessors(raw_ostream &OS) const override {
303       SimpleArgument::writeAccessors(OS);
304 
305       OS << "\n\n  static const " << getType() << " Default" << getUpperName()
306          << " = " << Default << ";";
307     }
308   };
309 
310   class StringArgument : public Argument {
311   public:
312     StringArgument(const Record &Arg, StringRef Attr)
313       : Argument(Arg, Attr)
314     {}
315 
316     void writeAccessors(raw_ostream &OS) const override {
317       OS << "  llvm::StringRef get" << getUpperName() << "() const {\n";
318       OS << "    return llvm::StringRef(" << getLowerName() << ", "
319          << getLowerName() << "Length);\n";
320       OS << "  }\n";
321       OS << "  unsigned get" << getUpperName() << "Length() const {\n";
322       OS << "    return " << getLowerName() << "Length;\n";
323       OS << "  }\n";
324       OS << "  void set" << getUpperName()
325          << "(ASTContext &C, llvm::StringRef S) {\n";
326       OS << "    " << getLowerName() << "Length = S.size();\n";
327       OS << "    this->" << getLowerName() << " = new (C, 1) char ["
328          << getLowerName() << "Length];\n";
329       OS << "    if (!S.empty())\n";
330       OS << "      std::memcpy(this->" << getLowerName() << ", S.data(), "
331          << getLowerName() << "Length);\n";
332       OS << "  }";
333     }
334     void writeCloneArgs(raw_ostream &OS) const override {
335       OS << "get" << getUpperName() << "()";
336     }
337     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
338       OS << "A->get" << getUpperName() << "()";
339     }
340     void writeCtorBody(raw_ostream &OS) const override {
341       OS << "      if (!" << getUpperName() << ".empty())\n";
342       OS << "        std::memcpy(" << getLowerName() << ", " << getUpperName()
343          << ".data(), " << getLowerName() << "Length);";
344     }
345     void writeCtorInitializers(raw_ostream &OS) const override {
346       OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
347          << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
348          << "Length])";
349     }
350     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
351       OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
352     }
353     void writeCtorParameters(raw_ostream &OS) const override {
354       OS << "llvm::StringRef " << getUpperName();
355     }
356     void writeDeclarations(raw_ostream &OS) const override {
357       OS << "unsigned " << getLowerName() << "Length;\n";
358       OS << "char *" << getLowerName() << ";";
359     }
360     void writePCHReadDecls(raw_ostream &OS) const override {
361       OS << "    std::string " << getLowerName()
362          << "= ReadString(Record, Idx);\n";
363     }
364     void writePCHReadArgs(raw_ostream &OS) const override {
365       OS << getLowerName();
366     }
367     void writePCHWrite(raw_ostream &OS) const override {
368       OS << "    AddString(SA->get" << getUpperName() << "(), Record);\n";
369     }
370     void writeValue(raw_ostream &OS) const override {
371       OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
372     }
373     void writeDump(raw_ostream &OS) const override {
374       OS << "    OS << \" \\\"\" << SA->get" << getUpperName()
375          << "() << \"\\\"\";\n";
376     }
377   };
378 
379   class AlignedArgument : public Argument {
380   public:
381     AlignedArgument(const Record &Arg, StringRef Attr)
382       : Argument(Arg, Attr)
383     {}
384 
385     void writeAccessors(raw_ostream &OS) const override {
386       OS << "  bool is" << getUpperName() << "Dependent() const;\n";
387 
388       OS << "  unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
389 
390       OS << "  bool is" << getUpperName() << "Expr() const {\n";
391       OS << "    return is" << getLowerName() << "Expr;\n";
392       OS << "  }\n";
393 
394       OS << "  Expr *get" << getUpperName() << "Expr() const {\n";
395       OS << "    assert(is" << getLowerName() << "Expr);\n";
396       OS << "    return " << getLowerName() << "Expr;\n";
397       OS << "  }\n";
398 
399       OS << "  TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
400       OS << "    assert(!is" << getLowerName() << "Expr);\n";
401       OS << "    return " << getLowerName() << "Type;\n";
402       OS << "  }";
403     }
404     void writeAccessorDefinitions(raw_ostream &OS) const override {
405       OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
406          << "Dependent() const {\n";
407       OS << "  if (is" << getLowerName() << "Expr)\n";
408       OS << "    return " << getLowerName() << "Expr && (" << getLowerName()
409          << "Expr->isValueDependent() || " << getLowerName()
410          << "Expr->isTypeDependent());\n";
411       OS << "  else\n";
412       OS << "    return " << getLowerName()
413          << "Type->getType()->isDependentType();\n";
414       OS << "}\n";
415 
416       // FIXME: Do not do the calculation here
417       // FIXME: Handle types correctly
418       // A null pointer means maximum alignment
419       OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
420          << "(ASTContext &Ctx) const {\n";
421       OS << "  assert(!is" << getUpperName() << "Dependent());\n";
422       OS << "  if (is" << getLowerName() << "Expr)\n";
423       OS << "    return " << getLowerName() << "Expr ? " << getLowerName()
424          << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
425          << " * Ctx.getCharWidth() : "
426          << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
427       OS << "  else\n";
428       OS << "    return 0; // FIXME\n";
429       OS << "}\n";
430     }
431     void writeCloneArgs(raw_ostream &OS) const override {
432       OS << "is" << getLowerName() << "Expr, is" << getLowerName()
433          << "Expr ? static_cast<void*>(" << getLowerName()
434          << "Expr) : " << getLowerName()
435          << "Type";
436     }
437     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
438       // FIXME: move the definition in Sema::InstantiateAttrs to here.
439       // In the meantime, aligned attributes are cloned.
440     }
441     void writeCtorBody(raw_ostream &OS) const override {
442       OS << "    if (is" << getLowerName() << "Expr)\n";
443       OS << "       " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
444          << getUpperName() << ");\n";
445       OS << "    else\n";
446       OS << "       " << getLowerName()
447          << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
448          << ");";
449     }
450     void writeCtorInitializers(raw_ostream &OS) const override {
451       OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
452     }
453     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
454       OS << "is" << getLowerName() << "Expr(false)";
455     }
456     void writeCtorParameters(raw_ostream &OS) const override {
457       OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
458     }
459     void writeImplicitCtorArgs(raw_ostream &OS) const override {
460       OS << "Is" << getUpperName() << "Expr, " << getUpperName();
461     }
462     void writeDeclarations(raw_ostream &OS) const override {
463       OS << "bool is" << getLowerName() << "Expr;\n";
464       OS << "union {\n";
465       OS << "Expr *" << getLowerName() << "Expr;\n";
466       OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
467       OS << "};";
468     }
469     void writePCHReadArgs(raw_ostream &OS) const override {
470       OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
471     }
472     void writePCHReadDecls(raw_ostream &OS) const override {
473       OS << "    bool is" << getLowerName() << "Expr = Record[Idx++];\n";
474       OS << "    void *" << getLowerName() << "Ptr;\n";
475       OS << "    if (is" << getLowerName() << "Expr)\n";
476       OS << "      " << getLowerName() << "Ptr = ReadExpr(F);\n";
477       OS << "    else\n";
478       OS << "      " << getLowerName()
479          << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
480     }
481     void writePCHWrite(raw_ostream &OS) const override {
482       OS << "    Record.push_back(SA->is" << getUpperName() << "Expr());\n";
483       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
484       OS << "      AddStmt(SA->get" << getUpperName() << "Expr());\n";
485       OS << "    else\n";
486       OS << "      AddTypeSourceInfo(SA->get" << getUpperName()
487          << "Type(), Record);\n";
488     }
489     void writeValue(raw_ostream &OS) const override {
490       OS << "\";\n";
491       // The aligned attribute argument expression is optional.
492       OS << "    if (is" << getLowerName() << "Expr && "
493          << getLowerName() << "Expr)\n";
494       OS << "      " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n";
495       OS << "    OS << \"";
496     }
497     void writeDump(raw_ostream &OS) const override {
498     }
499     void writeDumpChildren(raw_ostream &OS) const override {
500       OS << "    if (SA->is" << getUpperName() << "Expr())\n";
501       OS << "      dumpStmt(SA->get" << getUpperName() << "Expr());\n";
502       OS << "    else\n";
503       OS << "      dumpType(SA->get" << getUpperName()
504          << "Type()->getType());\n";
505     }
506     void writeHasChildren(raw_ostream &OS) const override {
507       OS << "SA->is" << getUpperName() << "Expr()";
508     }
509   };
510 
511   class VariadicArgument : public Argument {
512     std::string Type, ArgName, ArgSizeName, RangeName;
513 
514   protected:
515     // Assumed to receive a parameter: raw_ostream OS.
516     virtual void writeValueImpl(raw_ostream &OS) const {
517       OS << "    OS << Val;\n";
518     }
519 
520   public:
521     VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
522         : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
523           ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}
524 
525     std::string getType() const { return Type; }
526     bool isVariadic() const override { return true; }
527 
528     void writeAccessors(raw_ostream &OS) const override {
529       std::string IteratorType = getLowerName().str() + "_iterator";
530       std::string BeginFn = getLowerName().str() + "_begin()";
531       std::string EndFn = getLowerName().str() + "_end()";
532 
533       OS << "  typedef " << Type << "* " << IteratorType << ";\n";
534       OS << "  " << IteratorType << " " << BeginFn << " const {"
535          << " return " << ArgName << "; }\n";
536       OS << "  " << IteratorType << " " << EndFn << " const {"
537          << " return " << ArgName << " + " << ArgSizeName << "; }\n";
538       OS << "  unsigned " << getLowerName() << "_size() const {"
539          << " return " << ArgSizeName << "; }\n";
540       OS << "  llvm::iterator_range<" << IteratorType << "> " << RangeName
541          << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
542          << "); }\n";
543     }
544     void writeCloneArgs(raw_ostream &OS) const override {
545       OS << ArgName << ", " << ArgSizeName;
546     }
547     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
548       // This isn't elegant, but we have to go through public methods...
549       OS << "A->" << getLowerName() << "_begin(), "
550          << "A->" << getLowerName() << "_size()";
551     }
552     void writeCtorBody(raw_ostream &OS) const override {
553       OS << "    std::copy(" << getUpperName() << ", " << getUpperName()
554          << " + " << ArgSizeName << ", " << ArgName << ");";
555     }
556     void writeCtorInitializers(raw_ostream &OS) const override {
557       OS << ArgSizeName << "(" << getUpperName() << "Size), "
558          << ArgName << "(new (Ctx, 16) " << getType() << "["
559          << ArgSizeName << "])";
560     }
561     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
562       OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
563     }
564     void writeCtorParameters(raw_ostream &OS) const override {
565       OS << getType() << " *" << getUpperName() << ", unsigned "
566          << getUpperName() << "Size";
567     }
568     void writeImplicitCtorArgs(raw_ostream &OS) const override {
569       OS << getUpperName() << ", " << getUpperName() << "Size";
570     }
571     void writeDeclarations(raw_ostream &OS) const override {
572       OS << "  unsigned " << ArgSizeName << ";\n";
573       OS << "  " << getType() << " *" << ArgName << ";";
574     }
575     void writePCHReadDecls(raw_ostream &OS) const override {
576       OS << "  unsigned " << getLowerName() << "Size = Record[Idx++];\n";
577       OS << "  SmallVector<" << Type << ", 4> " << getLowerName()
578          << ";\n";
579       OS << "  " << getLowerName() << ".reserve(" << getLowerName()
580          << "Size);\n";
581       OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
582 
583       std::string read = ReadPCHRecord(Type);
584       OS << "    " << getLowerName() << ".push_back(" << read << ");\n";
585     }
586     void writePCHReadArgs(raw_ostream &OS) const override {
587       OS << getLowerName() << ".data(), " << getLowerName() << "Size";
588     }
589     void writePCHWrite(raw_ostream &OS) const override {
590       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
591       OS << "    for (auto &Val : SA->" << RangeName << "())\n";
592       OS << "      " << WritePCHRecord(Type, "Val");
593     }
594     void writeValue(raw_ostream &OS) const override {
595       OS << "\";\n";
596       OS << "  bool isFirst = true;\n"
597          << "  for (const auto &Val : " << RangeName << "()) {\n"
598          << "    if (isFirst) isFirst = false;\n"
599          << "    else OS << \", \";\n";
600       writeValueImpl(OS);
601       OS << "  }\n";
602       OS << "  OS << \"";
603     }
604     void writeDump(raw_ostream &OS) const override {
605       OS << "    for (const auto &Val : SA->" << RangeName << "())\n";
606       OS << "      OS << \" \" << Val;\n";
607     }
608   };
609 
610   // Unique the enums, but maintain the original declaration ordering.
611   std::vector<std::string>
612   uniqueEnumsInOrder(const std::vector<std::string> &enums) {
613     std::vector<std::string> uniques;
614     std::set<std::string> unique_set(enums.begin(), enums.end());
615     for (const auto &i : enums) {
616       std::set<std::string>::iterator set_i = unique_set.find(i);
617       if (set_i != unique_set.end()) {
618         uniques.push_back(i);
619         unique_set.erase(set_i);
620       }
621     }
622     return uniques;
623   }
624 
625   class EnumArgument : public Argument {
626     std::string type;
627     std::vector<std::string> values, enums, uniques;
628   public:
629     EnumArgument(const Record &Arg, StringRef Attr)
630       : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
631         values(Arg.getValueAsListOfStrings("Values")),
632         enums(Arg.getValueAsListOfStrings("Enums")),
633         uniques(uniqueEnumsInOrder(enums))
634     {
635       // FIXME: Emit a proper error
636       assert(!uniques.empty());
637     }
638 
639     bool isEnumArg() const override { return true; }
640 
641     void writeAccessors(raw_ostream &OS) const override {
642       OS << "  " << type << " get" << getUpperName() << "() const {\n";
643       OS << "    return " << getLowerName() << ";\n";
644       OS << "  }";
645     }
646     void writeCloneArgs(raw_ostream &OS) const override {
647       OS << getLowerName();
648     }
649     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
650       OS << "A->get" << getUpperName() << "()";
651     }
652     void writeCtorInitializers(raw_ostream &OS) const override {
653       OS << getLowerName() << "(" << getUpperName() << ")";
654     }
655     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
656       OS << getLowerName() << "(" << type << "(0))";
657     }
658     void writeCtorParameters(raw_ostream &OS) const override {
659       OS << type << " " << getUpperName();
660     }
661     void writeDeclarations(raw_ostream &OS) const override {
662       std::vector<std::string>::const_iterator i = uniques.begin(),
663                                                e = uniques.end();
664       // The last one needs to not have a comma.
665       --e;
666 
667       OS << "public:\n";
668       OS << "  enum " << type << " {\n";
669       for (; i != e; ++i)
670         OS << "    " << *i << ",\n";
671       OS << "    " << *e << "\n";
672       OS << "  };\n";
673       OS << "private:\n";
674       OS << "  " << type << " " << getLowerName() << ";";
675     }
676     void writePCHReadDecls(raw_ostream &OS) const override {
677       OS << "    " << getAttrName() << "Attr::" << type << " " << getLowerName()
678          << "(static_cast<" << getAttrName() << "Attr::" << type
679          << ">(Record[Idx++]));\n";
680     }
681     void writePCHReadArgs(raw_ostream &OS) const override {
682       OS << getLowerName();
683     }
684     void writePCHWrite(raw_ostream &OS) const override {
685       OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
686     }
687     void writeValue(raw_ostream &OS) const override {
688       // FIXME: this isn't 100% correct -- some enum arguments require printing
689       // as a string literal, while others require printing as an identifier.
690       // Tablegen currently does not distinguish between the two forms.
691       OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
692          << getUpperName() << "()) << \"\\\"";
693     }
694     void writeDump(raw_ostream &OS) const override {
695       OS << "    switch(SA->get" << getUpperName() << "()) {\n";
696       for (const auto &I : uniques) {
697         OS << "    case " << getAttrName() << "Attr::" << I << ":\n";
698         OS << "      OS << \" " << I << "\";\n";
699         OS << "      break;\n";
700       }
701       OS << "    }\n";
702     }
703 
704     void writeConversion(raw_ostream &OS) const {
705       OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
706       OS << type << " &Out) {\n";
707       OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
708       OS << type << ">>(Val)\n";
709       for (size_t I = 0; I < enums.size(); ++I) {
710         OS << "      .Case(\"" << values[I] << "\", ";
711         OS << getAttrName() << "Attr::" << enums[I] << ")\n";
712       }
713       OS << "      .Default(Optional<" << type << ">());\n";
714       OS << "    if (R) {\n";
715       OS << "      Out = *R;\n      return true;\n    }\n";
716       OS << "    return false;\n";
717       OS << "  }\n\n";
718 
719       // Mapping from enumeration values back to enumeration strings isn't
720       // trivial because some enumeration values have multiple named
721       // enumerators, such as type_visibility(internal) and
722       // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
723       OS << "  static const char *Convert" << type << "ToStr("
724          << type << " Val) {\n"
725          << "    switch(Val) {\n";
726       std::set<std::string> Uniques;
727       for (size_t I = 0; I < enums.size(); ++I) {
728         if (Uniques.insert(enums[I]).second)
729           OS << "    case " << getAttrName() << "Attr::" << enums[I]
730              << ": return \"" << values[I] << "\";\n";
731       }
732       OS << "    }\n"
733          << "    llvm_unreachable(\"No enumerator with that value\");\n"
734          << "  }\n";
735     }
736   };
737 
738   class VariadicEnumArgument: public VariadicArgument {
739     std::string type, QualifiedTypeName;
740     std::vector<std::string> values, enums, uniques;
741 
742   protected:
743     void writeValueImpl(raw_ostream &OS) const override {
744       // FIXME: this isn't 100% correct -- some enum arguments require printing
745       // as a string literal, while others require printing as an identifier.
746       // Tablegen currently does not distinguish between the two forms.
747       OS << "    OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
748          << "ToStr(Val)" << "<< \"\\\"\";\n";
749     }
750 
751   public:
752     VariadicEnumArgument(const Record &Arg, StringRef Attr)
753       : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
754         type(Arg.getValueAsString("Type")),
755         values(Arg.getValueAsListOfStrings("Values")),
756         enums(Arg.getValueAsListOfStrings("Enums")),
757         uniques(uniqueEnumsInOrder(enums))
758     {
759       QualifiedTypeName = getAttrName().str() + "Attr::" + type;
760 
761       // FIXME: Emit a proper error
762       assert(!uniques.empty());
763     }
764 
765     bool isVariadicEnumArg() const override { return true; }
766 
767     void writeDeclarations(raw_ostream &OS) const override {
768       std::vector<std::string>::const_iterator i = uniques.begin(),
769                                                e = uniques.end();
770       // The last one needs to not have a comma.
771       --e;
772 
773       OS << "public:\n";
774       OS << "  enum " << type << " {\n";
775       for (; i != e; ++i)
776         OS << "    " << *i << ",\n";
777       OS << "    " << *e << "\n";
778       OS << "  };\n";
779       OS << "private:\n";
780 
781       VariadicArgument::writeDeclarations(OS);
782     }
783     void writeDump(raw_ostream &OS) const override {
784       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
785          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
786          << getLowerName() << "_end(); I != E; ++I) {\n";
787       OS << "      switch(*I) {\n";
788       for (const auto &UI : uniques) {
789         OS << "    case " << getAttrName() << "Attr::" << UI << ":\n";
790         OS << "      OS << \" " << UI << "\";\n";
791         OS << "      break;\n";
792       }
793       OS << "      }\n";
794       OS << "    }\n";
795     }
796     void writePCHReadDecls(raw_ostream &OS) const override {
797       OS << "    unsigned " << getLowerName() << "Size = Record[Idx++];\n";
798       OS << "    SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
799          << ";\n";
800       OS << "    " << getLowerName() << ".reserve(" << getLowerName()
801          << "Size);\n";
802       OS << "    for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
803       OS << "      " << getLowerName() << ".push_back(" << "static_cast<"
804          << QualifiedTypeName << ">(Record[Idx++]));\n";
805     }
806     void writePCHWrite(raw_ostream &OS) const override {
807       OS << "    Record.push_back(SA->" << getLowerName() << "_size());\n";
808       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
809          << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
810          << getLowerName() << "_end(); i != e; ++i)\n";
811       OS << "      " << WritePCHRecord(QualifiedTypeName, "(*i)");
812     }
813     void writeConversion(raw_ostream &OS) const {
814       OS << "  static bool ConvertStrTo" << type << "(StringRef Val, ";
815       OS << type << " &Out) {\n";
816       OS << "    Optional<" << type << "> R = llvm::StringSwitch<Optional<";
817       OS << type << ">>(Val)\n";
818       for (size_t I = 0; I < enums.size(); ++I) {
819         OS << "      .Case(\"" << values[I] << "\", ";
820         OS << getAttrName() << "Attr::" << enums[I] << ")\n";
821       }
822       OS << "      .Default(Optional<" << type << ">());\n";
823       OS << "    if (R) {\n";
824       OS << "      Out = *R;\n      return true;\n    }\n";
825       OS << "    return false;\n";
826       OS << "  }\n\n";
827 
828       OS << "  static const char *Convert" << type << "ToStr("
829         << type << " Val) {\n"
830         << "    switch(Val) {\n";
831       std::set<std::string> Uniques;
832       for (size_t I = 0; I < enums.size(); ++I) {
833         if (Uniques.insert(enums[I]).second)
834           OS << "    case " << getAttrName() << "Attr::" << enums[I]
835           << ": return \"" << values[I] << "\";\n";
836       }
837       OS << "    }\n"
838         << "    llvm_unreachable(\"No enumerator with that value\");\n"
839         << "  }\n";
840     }
841   };
842 
843   class VersionArgument : public Argument {
844   public:
845     VersionArgument(const Record &Arg, StringRef Attr)
846       : Argument(Arg, Attr)
847     {}
848 
849     void writeAccessors(raw_ostream &OS) const override {
850       OS << "  VersionTuple get" << getUpperName() << "() const {\n";
851       OS << "    return " << getLowerName() << ";\n";
852       OS << "  }\n";
853       OS << "  void set" << getUpperName()
854          << "(ASTContext &C, VersionTuple V) {\n";
855       OS << "    " << getLowerName() << " = V;\n";
856       OS << "  }";
857     }
858     void writeCloneArgs(raw_ostream &OS) const override {
859       OS << "get" << getUpperName() << "()";
860     }
861     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
862       OS << "A->get" << getUpperName() << "()";
863     }
864     void writeCtorInitializers(raw_ostream &OS) const override {
865       OS << getLowerName() << "(" << getUpperName() << ")";
866     }
867     void writeCtorDefaultInitializers(raw_ostream &OS) const override {
868       OS << getLowerName() << "()";
869     }
870     void writeCtorParameters(raw_ostream &OS) const override {
871       OS << "VersionTuple " << getUpperName();
872     }
873     void writeDeclarations(raw_ostream &OS) const override {
874       OS << "VersionTuple " << getLowerName() << ";\n";
875     }
876     void writePCHReadDecls(raw_ostream &OS) const override {
877       OS << "    VersionTuple " << getLowerName()
878          << "= ReadVersionTuple(Record, Idx);\n";
879     }
880     void writePCHReadArgs(raw_ostream &OS) const override {
881       OS << getLowerName();
882     }
883     void writePCHWrite(raw_ostream &OS) const override {
884       OS << "    AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
885     }
886     void writeValue(raw_ostream &OS) const override {
887       OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
888     }
889     void writeDump(raw_ostream &OS) const override {
890       OS << "    OS << \" \" << SA->get" << getUpperName() << "();\n";
891     }
892   };
893 
894   class ExprArgument : public SimpleArgument {
895   public:
896     ExprArgument(const Record &Arg, StringRef Attr)
897       : SimpleArgument(Arg, Attr, "Expr *")
898     {}
899 
900     void writeASTVisitorTraversal(raw_ostream &OS) const override {
901       OS << "  if (!"
902          << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
903       OS << "    return false;\n";
904     }
905 
906     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
907       OS << "tempInst" << getUpperName();
908     }
909 
910     void writeTemplateInstantiation(raw_ostream &OS) const override {
911       OS << "      " << getType() << " tempInst" << getUpperName() << ";\n";
912       OS << "      {\n";
913       OS << "        EnterExpressionEvaluationContext "
914          << "Unevaluated(S, Sema::Unevaluated);\n";
915       OS << "        ExprResult " << "Result = S.SubstExpr("
916          << "A->get" << getUpperName() << "(), TemplateArgs);\n";
917       OS << "        tempInst" << getUpperName() << " = "
918          << "Result.getAs<Expr>();\n";
919       OS << "      }\n";
920     }
921 
922     void writeDump(raw_ostream &OS) const override {}
923 
924     void writeDumpChildren(raw_ostream &OS) const override {
925       OS << "    dumpStmt(SA->get" << getUpperName() << "());\n";
926     }
927     void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
928   };
929 
930   class VariadicExprArgument : public VariadicArgument {
931   public:
932     VariadicExprArgument(const Record &Arg, StringRef Attr)
933       : VariadicArgument(Arg, Attr, "Expr *")
934     {}
935 
936     void writeASTVisitorTraversal(raw_ostream &OS) const override {
937       OS << "  {\n";
938       OS << "    " << getType() << " *I = A->" << getLowerName()
939          << "_begin();\n";
940       OS << "    " << getType() << " *E = A->" << getLowerName()
941          << "_end();\n";
942       OS << "    for (; I != E; ++I) {\n";
943       OS << "      if (!getDerived().TraverseStmt(*I))\n";
944       OS << "        return false;\n";
945       OS << "    }\n";
946       OS << "  }\n";
947     }
948 
949     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
950       OS << "tempInst" << getUpperName() << ", "
951          << "A->" << getLowerName() << "_size()";
952     }
953 
954     void writeTemplateInstantiation(raw_ostream &OS) const override {
955       OS << "      " << getType() << " *tempInst" << getUpperName()
956          << " = new (C, 16) " << getType()
957          << "[A->" << getLowerName() << "_size()];\n";
958       OS << "      {\n";
959       OS << "        EnterExpressionEvaluationContext "
960          << "Unevaluated(S, Sema::Unevaluated);\n";
961       OS << "        " << getType() << " *TI = tempInst" << getUpperName()
962          << ";\n";
963       OS << "        " << getType() << " *I = A->" << getLowerName()
964          << "_begin();\n";
965       OS << "        " << getType() << " *E = A->" << getLowerName()
966          << "_end();\n";
967       OS << "        for (; I != E; ++I, ++TI) {\n";
968       OS << "          ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
969       OS << "          *TI = Result.getAs<Expr>();\n";
970       OS << "        }\n";
971       OS << "      }\n";
972     }
973 
974     void writeDump(raw_ostream &OS) const override {}
975 
976     void writeDumpChildren(raw_ostream &OS) const override {
977       OS << "    for (" << getAttrName() << "Attr::" << getLowerName()
978          << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
979          << getLowerName() << "_end(); I != E; ++I)\n";
980       OS << "      dumpStmt(*I);\n";
981     }
982 
983     void writeHasChildren(raw_ostream &OS) const override {
984       OS << "SA->" << getLowerName() << "_begin() != "
985          << "SA->" << getLowerName() << "_end()";
986     }
987   };
988 
989   class VariadicStringArgument : public VariadicArgument {
990   public:
991     VariadicStringArgument(const Record &Arg, StringRef Attr)
992       : VariadicArgument(Arg, Attr, "std::string")
993     {}
994     void writeValueImpl(raw_ostream &OS) const override {
995       OS << "    OS << \"\\\"\" << Val << \"\\\"\";\n";
996     }
997   };
998 
999   class TypeArgument : public SimpleArgument {
1000   public:
1001     TypeArgument(const Record &Arg, StringRef Attr)
1002       : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1003     {}
1004 
1005     void writeAccessors(raw_ostream &OS) const override {
1006       OS << "  QualType get" << getUpperName() << "() const {\n";
1007       OS << "    return " << getLowerName() << "->getType();\n";
1008       OS << "  }";
1009       OS << "  " << getType() << " get" << getUpperName() << "Loc() const {\n";
1010       OS << "    return " << getLowerName() << ";\n";
1011       OS << "  }";
1012     }
1013     void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1014       OS << "A->get" << getUpperName() << "Loc()";
1015     }
1016     void writePCHWrite(raw_ostream &OS) const override {
1017       OS << "    " << WritePCHRecord(
1018           getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1019     }
1020   };
1021 } // end anonymous namespace
1022 
1023 static std::unique_ptr<Argument>
1024 createArgument(const Record &Arg, StringRef Attr,
1025                const Record *Search = nullptr) {
1026   if (!Search)
1027     Search = &Arg;
1028 
1029   std::unique_ptr<Argument> Ptr;
1030   llvm::StringRef ArgName = Search->getName();
1031 
1032   if (ArgName == "AlignedArgument")
1033     Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1034   else if (ArgName == "EnumArgument")
1035     Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1036   else if (ArgName == "ExprArgument")
1037     Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1038   else if (ArgName == "FunctionArgument")
1039     Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1040   else if (ArgName == "IdentifierArgument")
1041     Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1042   else if (ArgName == "DefaultBoolArgument")
1043     Ptr = llvm::make_unique<DefaultSimpleArgument>(
1044         Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1045   else if (ArgName == "BoolArgument")
1046     Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1047   else if (ArgName == "DefaultIntArgument")
1048     Ptr = llvm::make_unique<DefaultSimpleArgument>(
1049         Arg, Attr, "int", Arg.getValueAsInt("Default"));
1050   else if (ArgName == "IntArgument")
1051     Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1052   else if (ArgName == "StringArgument")
1053     Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1054   else if (ArgName == "TypeArgument")
1055     Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1056   else if (ArgName == "UnsignedArgument")
1057     Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1058   else if (ArgName == "VariadicUnsignedArgument")
1059     Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1060   else if (ArgName == "VariadicStringArgument")
1061     Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1062   else if (ArgName == "VariadicEnumArgument")
1063     Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1064   else if (ArgName == "VariadicExprArgument")
1065     Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1066   else if (ArgName == "VersionArgument")
1067     Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1068 
1069   if (!Ptr) {
1070     // Search in reverse order so that the most-derived type is handled first.
1071     ArrayRef<Record*> Bases = Search->getSuperClasses();
1072     for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
1073       if ((Ptr = createArgument(Arg, Attr, Base)))
1074         break;
1075     }
1076   }
1077 
1078   if (Ptr && Arg.getValueAsBit("Optional"))
1079     Ptr->setOptional(true);
1080 
1081   return Ptr;
1082 }
1083 
1084 static void writeAvailabilityValue(raw_ostream &OS) {
1085   OS << "\" << getPlatform()->getName();\n"
1086      << "  if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1087      << "  if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1088      << "  if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1089      << "  if (getUnavailable()) OS << \", unavailable\";\n"
1090      << "  OS << \"";
1091 }
1092 
1093 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1094   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1095 
1096   OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1097   if (Spellings.empty()) {
1098     OS << "  return \"(No spelling)\";\n}\n\n";
1099     return;
1100   }
1101 
1102   OS << "  switch (SpellingListIndex) {\n"
1103         "  default:\n"
1104         "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1105         "    return \"(No spelling)\";\n";
1106 
1107   for (unsigned I = 0; I < Spellings.size(); ++I)
1108     OS << "  case " << I << ":\n"
1109           "    return \"" << Spellings[I].name() << "\";\n";
1110   // End of the switch statement.
1111   OS << "  }\n";
1112   // End of the getSpelling function.
1113   OS << "}\n\n";
1114 }
1115 
1116 static void
1117 writePrettyPrintFunction(Record &R,
1118                          const std::vector<std::unique_ptr<Argument>> &Args,
1119                          raw_ostream &OS) {
1120   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1121 
1122   OS << "void " << R.getName() << "Attr::printPretty("
1123     << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1124 
1125   if (Spellings.empty()) {
1126     OS << "}\n\n";
1127     return;
1128   }
1129 
1130   OS <<
1131     "  switch (SpellingListIndex) {\n"
1132     "  default:\n"
1133     "    llvm_unreachable(\"Unknown attribute spelling!\");\n"
1134     "    break;\n";
1135 
1136   for (unsigned I = 0; I < Spellings.size(); ++ I) {
1137     llvm::SmallString<16> Prefix;
1138     llvm::SmallString<8> Suffix;
1139     // The actual spelling of the name and namespace (if applicable)
1140     // of an attribute without considering prefix and suffix.
1141     llvm::SmallString<64> Spelling;
1142     std::string Name = Spellings[I].name();
1143     std::string Variety = Spellings[I].variety();
1144 
1145     if (Variety == "GNU") {
1146       Prefix = " __attribute__((";
1147       Suffix = "))";
1148     } else if (Variety == "CXX11") {
1149       Prefix = " [[";
1150       Suffix = "]]";
1151       std::string Namespace = Spellings[I].nameSpace();
1152       if (!Namespace.empty()) {
1153         Spelling += Namespace;
1154         Spelling += "::";
1155       }
1156     } else if (Variety == "Declspec") {
1157       Prefix = " __declspec(";
1158       Suffix = ")";
1159     } else if (Variety == "Keyword") {
1160       Prefix = " ";
1161       Suffix = "";
1162     } else if (Variety == "Pragma") {
1163       Prefix = "#pragma ";
1164       Suffix = "\n";
1165       std::string Namespace = Spellings[I].nameSpace();
1166       if (!Namespace.empty()) {
1167         Spelling += Namespace;
1168         Spelling += " ";
1169       }
1170     } else {
1171       llvm_unreachable("Unknown attribute syntax variety!");
1172     }
1173 
1174     Spelling += Name;
1175 
1176     OS <<
1177       "  case " << I << " : {\n"
1178       "    OS << \"" << Prefix << Spelling;
1179 
1180     if (Variety == "Pragma") {
1181       OS << " \";\n";
1182       OS << "    printPrettyPragma(OS, Policy);\n";
1183       OS << "    OS << \"\\n\";";
1184       OS << "    break;\n";
1185       OS << "  }\n";
1186       continue;
1187     }
1188 
1189     // FIXME: always printing the parenthesis isn't the correct behavior for
1190     // attributes which have optional arguments that were not provided. For
1191     // instance: __attribute__((aligned)) will be pretty printed as
1192     // __attribute__((aligned())). The logic should check whether there is only
1193     // a single argument, and if it is optional, whether it has been provided.
1194     if (!Args.empty())
1195       OS << "(";
1196     if (Spelling == "availability") {
1197       writeAvailabilityValue(OS);
1198     } else {
1199       for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
1200         if (I != Args.begin()) OS << ", ";
1201         (*I)->writeValue(OS);
1202       }
1203     }
1204 
1205     if (!Args.empty())
1206       OS << ")";
1207     OS << Suffix + "\";\n";
1208 
1209     OS <<
1210       "    break;\n"
1211       "  }\n";
1212   }
1213 
1214   // End of the switch statement.
1215   OS << "}\n";
1216   // End of the print function.
1217   OS << "}\n\n";
1218 }
1219 
1220 /// \brief Return the index of a spelling in a spelling list.
1221 static unsigned
1222 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1223                      const FlattenedSpelling &Spelling) {
1224   assert(!SpellingList.empty() && "Spelling list is empty!");
1225 
1226   for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1227     const FlattenedSpelling &S = SpellingList[Index];
1228     if (S.variety() != Spelling.variety())
1229       continue;
1230     if (S.nameSpace() != Spelling.nameSpace())
1231       continue;
1232     if (S.name() != Spelling.name())
1233       continue;
1234 
1235     return Index;
1236   }
1237 
1238   llvm_unreachable("Unknown spelling!");
1239 }
1240 
1241 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1242   std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1243   for (const auto *Accessor : Accessors) {
1244     std::string Name = Accessor->getValueAsString("Name");
1245     std::vector<FlattenedSpelling> Spellings =
1246       GetFlattenedSpellings(*Accessor);
1247     std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1248     assert(!SpellingList.empty() &&
1249            "Attribute with empty spelling list can't have accessors!");
1250 
1251     OS << "  bool " << Name << "() const { return SpellingListIndex == ";
1252     for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1253       OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1254       if (Index != Spellings.size() -1)
1255         OS << " ||\n    SpellingListIndex == ";
1256       else
1257         OS << "; }\n";
1258     }
1259   }
1260 }
1261 
1262 static bool
1263 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1264   assert(!Spellings.empty() && "An empty list of spellings was provided");
1265   std::string FirstName = NormalizeNameForSpellingComparison(
1266     Spellings.front().name());
1267   for (const auto &Spelling :
1268        llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1269     std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1270     if (Name != FirstName)
1271       return false;
1272   }
1273   return true;
1274 }
1275 
1276 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1277 static std::string
1278 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1279                         SemanticSpellingMap &Map) {
1280   // The enumerants are automatically generated based on the variety,
1281   // namespace (if present) and name for each attribute spelling. However,
1282   // care is taken to avoid trampling on the reserved namespace due to
1283   // underscores.
1284   std::string Ret("  enum Spelling {\n");
1285   std::set<std::string> Uniques;
1286   unsigned Idx = 0;
1287   for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1288     const FlattenedSpelling &S = *I;
1289     std::string Variety = S.variety();
1290     std::string Spelling = S.name();
1291     std::string Namespace = S.nameSpace();
1292     std::string EnumName = "";
1293 
1294     EnumName += (Variety + "_");
1295     if (!Namespace.empty())
1296       EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1297       "_");
1298     EnumName += NormalizeNameForSpellingComparison(Spelling);
1299 
1300     // Even if the name is not unique, this spelling index corresponds to a
1301     // particular enumerant name that we've calculated.
1302     Map[Idx] = EnumName;
1303 
1304     // Since we have been stripping underscores to avoid trampling on the
1305     // reserved namespace, we may have inadvertently created duplicate
1306     // enumerant names. These duplicates are not considered part of the
1307     // semantic spelling, and can be elided.
1308     if (Uniques.find(EnumName) != Uniques.end())
1309       continue;
1310 
1311     Uniques.insert(EnumName);
1312     if (I != Spellings.begin())
1313       Ret += ",\n";
1314     // Duplicate spellings are not considered part of the semantic spelling
1315     // enumeration, but the spelling index and semantic spelling values are
1316     // meant to be equivalent, so we must specify a concrete value for each
1317     // enumerator.
1318     Ret += "    " + EnumName + " = " + llvm::utostr(Idx);
1319   }
1320   Ret += "\n  };\n\n";
1321   return Ret;
1322 }
1323 
1324 void WriteSemanticSpellingSwitch(const std::string &VarName,
1325                                  const SemanticSpellingMap &Map,
1326                                  raw_ostream &OS) {
1327   OS << "  switch (" << VarName << ") {\n    default: "
1328     << "llvm_unreachable(\"Unknown spelling list index\");\n";
1329   for (const auto &I : Map)
1330     OS << "    case " << I.first << ": return " << I.second << ";\n";
1331   OS << "  }\n";
1332 }
1333 
1334 // Emits the LateParsed property for attributes.
1335 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1336   OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1337   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1338 
1339   for (const auto *Attr : Attrs) {
1340     bool LateParsed = Attr->getValueAsBit("LateParsed");
1341 
1342     if (LateParsed) {
1343       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1344 
1345       // FIXME: Handle non-GNU attributes
1346       for (const auto &I : Spellings) {
1347         if (I.variety() != "GNU")
1348           continue;
1349         OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1350       }
1351     }
1352   }
1353   OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1354 }
1355 
1356 /// \brief Emits the first-argument-is-type property for attributes.
1357 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1358   OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1359   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1360 
1361   for (const auto *Attr : Attrs) {
1362     // Determine whether the first argument is a type.
1363     std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1364     if (Args.empty())
1365       continue;
1366 
1367     if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
1368       continue;
1369 
1370     // All these spellings take a single type argument.
1371     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1372     std::set<std::string> Emitted;
1373     for (const auto &S : Spellings) {
1374       if (Emitted.insert(S.name()).second)
1375         OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1376     }
1377   }
1378   OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1379 }
1380 
1381 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1382 /// attributes.
1383 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1384   OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1385   ParsedAttrMap Attrs = getParsedAttrList(Records);
1386   for (const auto &I : Attrs) {
1387     const Record &Attr = *I.second;
1388 
1389     if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1390       continue;
1391 
1392     // All these spellings take are parsed unevaluated.
1393     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1394     std::set<std::string> Emitted;
1395     for (const auto &S : Spellings) {
1396       if (Emitted.insert(S.name()).second)
1397         OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1398     }
1399   }
1400   OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1401 }
1402 
1403 static bool isIdentifierArgument(Record *Arg) {
1404   return !Arg->getSuperClasses().empty() &&
1405     llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
1406     .Case("IdentifierArgument", true)
1407     .Case("EnumArgument", true)
1408     .Case("VariadicEnumArgument", true)
1409     .Default(false);
1410 }
1411 
1412 // Emits the first-argument-is-identifier property for attributes.
1413 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1414   OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1415   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1416 
1417   for (const auto *Attr : Attrs) {
1418     // Determine whether the first argument is an identifier.
1419     std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1420     if (Args.empty() || !isIdentifierArgument(Args[0]))
1421       continue;
1422 
1423     // All these spellings take an identifier argument.
1424     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1425     std::set<std::string> Emitted;
1426     for (const auto &S : Spellings) {
1427       if (Emitted.insert(S.name()).second)
1428         OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1429     }
1430   }
1431   OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1432 }
1433 
1434 namespace clang {
1435 
1436 // Emits the class definitions for attributes.
1437 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1438   emitSourceFileHeader("Attribute classes' definitions", OS);
1439 
1440   OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1441   OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1442 
1443   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1444 
1445   for (const auto *Attr : Attrs) {
1446     const Record &R = *Attr;
1447 
1448     // FIXME: Currently, documentation is generated as-needed due to the fact
1449     // that there is no way to allow a generated project "reach into" the docs
1450     // directory (for instance, it may be an out-of-tree build). However, we want
1451     // to ensure that every attribute has a Documentation field, and produce an
1452     // error if it has been neglected. Otherwise, the on-demand generation which
1453     // happens server-side will fail. This code is ensuring that functionality,
1454     // even though this Emitter doesn't technically need the documentation.
1455     // When attribute documentation can be generated as part of the build
1456     // itself, this code can be removed.
1457     (void)R.getValueAsListOfDefs("Documentation");
1458 
1459     if (!R.getValueAsBit("ASTNode"))
1460       continue;
1461 
1462     ArrayRef<Record *> Supers = R.getSuperClasses();
1463     assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1464     std::string SuperName;
1465     for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
1466       const Record &R = *Super;
1467       if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
1468         SuperName = R.getName();
1469     }
1470 
1471     OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1472 
1473     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1474     std::vector<std::unique_ptr<Argument>> Args;
1475     Args.reserve(ArgRecords.size());
1476 
1477     for (const auto *ArgRecord : ArgRecords) {
1478       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1479       Args.back()->writeDeclarations(OS);
1480       OS << "\n\n";
1481     }
1482 
1483     OS << "\npublic:\n";
1484 
1485     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1486 
1487     // If there are zero or one spellings, all spelling-related functionality
1488     // can be elided. If all of the spellings share the same name, the spelling
1489     // functionality can also be elided.
1490     bool ElideSpelling = (Spellings.size() <= 1) ||
1491                          SpellingNamesAreCommon(Spellings);
1492 
1493     // This maps spelling index values to semantic Spelling enumerants.
1494     SemanticSpellingMap SemanticToSyntacticMap;
1495 
1496     if (!ElideSpelling)
1497       OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1498 
1499     OS << "  static " << R.getName() << "Attr *CreateImplicit(";
1500     OS << "ASTContext &Ctx";
1501     if (!ElideSpelling)
1502       OS << ", Spelling S";
1503     for (auto const &ai : Args) {
1504       OS << ", ";
1505       ai->writeCtorParameters(OS);
1506     }
1507     OS << ", SourceRange Loc = SourceRange()";
1508     OS << ") {\n";
1509     OS << "    " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
1510     OS << "Attr(Loc, Ctx, ";
1511     for (auto const &ai : Args) {
1512       ai->writeImplicitCtorArgs(OS);
1513       OS << ", ";
1514     }
1515     OS << (ElideSpelling ? "0" : "S") << ");\n";
1516     OS << "    A->setImplicit(true);\n";
1517     OS << "    return A;\n  }\n\n";
1518 
1519     OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1520 
1521     bool HasOpt = false;
1522     for (auto const &ai : Args) {
1523       OS << "              , ";
1524       ai->writeCtorParameters(OS);
1525       OS << "\n";
1526       if (ai->isOptional())
1527         HasOpt = true;
1528     }
1529 
1530     OS << "              , ";
1531     OS << "unsigned SI\n";
1532 
1533     OS << "             )\n";
1534     OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1535        << R.getValueAsBit("LateParsed") << ", "
1536        << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
1537 
1538     for (auto const &ai : Args) {
1539       OS << "              , ";
1540       ai->writeCtorInitializers(OS);
1541       OS << "\n";
1542     }
1543 
1544     OS << "  {\n";
1545 
1546     for (auto const &ai : Args) {
1547       ai->writeCtorBody(OS);
1548       OS << "\n";
1549     }
1550     OS << "  }\n\n";
1551 
1552     // If there are optional arguments, write out a constructor that elides the
1553     // optional arguments as well.
1554     if (HasOpt) {
1555       OS << "  " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1556       for (auto const &ai : Args) {
1557         if (!ai->isOptional()) {
1558           OS << "              , ";
1559           ai->writeCtorParameters(OS);
1560           OS << "\n";
1561         }
1562       }
1563 
1564       OS << "              , ";
1565       OS << "unsigned SI\n";
1566 
1567       OS << "             )\n";
1568       OS << "    : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1569          << R.getValueAsBit("LateParsed") << ", "
1570          << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
1571 
1572       for (auto const &ai : Args) {
1573         OS << "              , ";
1574         ai->writeCtorDefaultInitializers(OS);
1575         OS << "\n";
1576       }
1577 
1578       OS << "  {\n";
1579 
1580       for (auto const &ai : Args) {
1581         if (!ai->isOptional()) {
1582           ai->writeCtorBody(OS);
1583           OS << "\n";
1584         }
1585       }
1586       OS << "  }\n\n";
1587     }
1588 
1589     OS << "  " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
1590     OS << "  void printPretty(raw_ostream &OS,\n"
1591        << "                   const PrintingPolicy &Policy) const;\n";
1592     OS << "  const char *getSpelling() const;\n";
1593 
1594     if (!ElideSpelling) {
1595       assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1596       OS << "  Spelling getSemanticSpelling() const {\n";
1597       WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1598                                   OS);
1599       OS << "  }\n";
1600     }
1601 
1602     writeAttrAccessorDefinition(R, OS);
1603 
1604     for (auto const &ai : Args) {
1605       ai->writeAccessors(OS);
1606       OS << "\n\n";
1607 
1608       if (ai->isEnumArg())
1609         static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1610       else if (ai->isVariadicEnumArg())
1611         static_cast<const VariadicEnumArgument *>(ai.get())
1612             ->writeConversion(OS);
1613     }
1614 
1615     OS << R.getValueAsString("AdditionalMembers");
1616     OS << "\n\n";
1617 
1618     OS << "  static bool classof(const Attr *A) { return A->getKind() == "
1619        << "attr::" << R.getName() << "; }\n";
1620 
1621     OS << "};\n\n";
1622   }
1623 
1624   OS << "#endif\n";
1625 }
1626 
1627 // Emits the class method definitions for attributes.
1628 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1629   emitSourceFileHeader("Attribute classes' member function definitions", OS);
1630 
1631   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1632 
1633   for (auto *Attr : Attrs) {
1634     Record &R = *Attr;
1635 
1636     if (!R.getValueAsBit("ASTNode"))
1637       continue;
1638 
1639     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1640     std::vector<std::unique_ptr<Argument>> Args;
1641     for (const auto *Arg : ArgRecords)
1642       Args.emplace_back(createArgument(*Arg, R.getName()));
1643 
1644     for (auto const &ai : Args)
1645       ai->writeAccessorDefinitions(OS);
1646 
1647     OS << R.getName() << "Attr *" << R.getName()
1648        << "Attr::clone(ASTContext &C) const {\n";
1649     OS << "  auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
1650     for (auto const &ai : Args) {
1651       OS << ", ";
1652       ai->writeCloneArgs(OS);
1653     }
1654     OS << ", getSpellingListIndex());\n";
1655     OS << "  A->Inherited = Inherited;\n";
1656     OS << "  A->IsPackExpansion = IsPackExpansion;\n";
1657     OS << "  A->Implicit = Implicit;\n";
1658     OS << "  return A;\n}\n\n";
1659 
1660     writePrettyPrintFunction(R, Args, OS);
1661     writeGetSpellingFunction(R, OS);
1662   }
1663 
1664   // Instead of relying on virtual dispatch we just create a huge dispatch
1665   // switch. This is both smaller and faster than virtual functions.
1666   auto EmitFunc = [&](const char *Method) {
1667     OS << "  switch (getKind()) {\n";
1668     for (const auto *Attr : Attrs) {
1669       const Record &R = *Attr;
1670       if (!R.getValueAsBit("ASTNode"))
1671         continue;
1672 
1673       OS << "  case attr::" << R.getName() << ":\n";
1674       OS << "    return cast<" << R.getName() << "Attr>(this)->" << Method
1675          << ";\n";
1676     }
1677     OS << "  case attr::NUM_ATTRS:\n";
1678     OS << "    break;\n";
1679     OS << "  }\n";
1680     OS << "  llvm_unreachable(\"Unexpected attribute kind!\");\n";
1681     OS << "}\n\n";
1682   };
1683 
1684   OS << "const char *Attr::getSpelling() const {\n";
1685   EmitFunc("getSpelling()");
1686 
1687   OS << "Attr *Attr::clone(ASTContext &C) const {\n";
1688   EmitFunc("clone(C)");
1689 
1690   OS << "void Attr::printPretty(raw_ostream &OS, "
1691         "const PrintingPolicy &Policy) const {\n";
1692   EmitFunc("printPretty(OS, Policy)");
1693 }
1694 
1695 } // end namespace clang
1696 
1697 static void EmitAttrList(raw_ostream &OS, StringRef Class,
1698                          const std::vector<Record*> &AttrList) {
1699   std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();
1700 
1701   if (i != e) {
1702     // Move the end iterator back to emit the last attribute.
1703     for(--e; i != e; ++i) {
1704       if (!(*i)->getValueAsBit("ASTNode"))
1705         continue;
1706 
1707       OS << Class << "(" << (*i)->getName() << ")\n";
1708     }
1709 
1710     OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
1711   }
1712 }
1713 
1714 // Determines if an attribute has a Pragma spelling.
1715 static bool AttrHasPragmaSpelling(const Record *R) {
1716   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1717   return std::find_if(Spellings.begin(), Spellings.end(),
1718                       [](const FlattenedSpelling &S) {
1719            return S.variety() == "Pragma";
1720          }) != Spellings.end();
1721 }
1722 
1723 namespace clang {
1724 // Emits the enumeration list for attributes.
1725 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
1726   emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
1727 
1728   OS << "#ifndef LAST_ATTR\n";
1729   OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
1730   OS << "#endif\n\n";
1731 
1732   OS << "#ifndef INHERITABLE_ATTR\n";
1733   OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
1734   OS << "#endif\n\n";
1735 
1736   OS << "#ifndef LAST_INHERITABLE_ATTR\n";
1737   OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
1738   OS << "#endif\n\n";
1739 
1740   OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
1741   OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
1742   OS << "#endif\n\n";
1743 
1744   OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
1745   OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
1746         " INHERITABLE_PARAM_ATTR(NAME)\n";
1747   OS << "#endif\n\n";
1748 
1749   OS << "#ifndef PRAGMA_SPELLING_ATTR\n";
1750   OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n";
1751   OS << "#endif\n\n";
1752 
1753   OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n";
1754   OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n";
1755   OS << "#endif\n\n";
1756 
1757   Record *InhClass = Records.getClass("InheritableAttr");
1758   Record *InhParamClass = Records.getClass("InheritableParamAttr");
1759   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"),
1760                         NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs;
1761   for (auto *Attr : Attrs) {
1762     if (!Attr->getValueAsBit("ASTNode"))
1763       continue;
1764 
1765     if (AttrHasPragmaSpelling(Attr))
1766       PragmaAttrs.push_back(Attr);
1767 
1768     if (Attr->isSubClassOf(InhParamClass))
1769       InhParamAttrs.push_back(Attr);
1770     else if (Attr->isSubClassOf(InhClass))
1771       InhAttrs.push_back(Attr);
1772     else
1773       NonInhAttrs.push_back(Attr);
1774   }
1775 
1776   EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
1777   EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
1778   EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
1779   EmitAttrList(OS, "ATTR", NonInhAttrs);
1780 
1781   OS << "#undef LAST_ATTR\n";
1782   OS << "#undef INHERITABLE_ATTR\n";
1783   OS << "#undef LAST_INHERITABLE_ATTR\n";
1784   OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
1785   OS << "#undef LAST_PRAGMA_ATTR\n";
1786   OS << "#undef PRAGMA_SPELLING_ATTR\n";
1787   OS << "#undef ATTR\n";
1788 }
1789 
1790 // Emits the code to read an attribute from a precompiled header.
1791 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
1792   emitSourceFileHeader("Attribute deserialization code", OS);
1793 
1794   Record *InhClass = Records.getClass("InheritableAttr");
1795   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1796                        ArgRecords;
1797   std::vector<std::unique_ptr<Argument>> Args;
1798 
1799   OS << "  switch (Kind) {\n";
1800   OS << "  default:\n";
1801   OS << "    llvm_unreachable(\"Unknown attribute!\");\n";
1802   for (const auto *Attr : Attrs) {
1803     const Record &R = *Attr;
1804     if (!R.getValueAsBit("ASTNode"))
1805       continue;
1806 
1807     OS << "  case attr::" << R.getName() << ": {\n";
1808     if (R.isSubClassOf(InhClass))
1809       OS << "    bool isInherited = Record[Idx++];\n";
1810     OS << "    bool isImplicit = Record[Idx++];\n";
1811     OS << "    unsigned Spelling = Record[Idx++];\n";
1812     ArgRecords = R.getValueAsListOfDefs("Args");
1813     Args.clear();
1814     for (const auto *Arg : ArgRecords) {
1815       Args.emplace_back(createArgument(*Arg, R.getName()));
1816       Args.back()->writePCHReadDecls(OS);
1817     }
1818     OS << "    New = new (Context) " << R.getName() << "Attr(Range, Context";
1819     for (auto const &ri : Args) {
1820       OS << ", ";
1821       ri->writePCHReadArgs(OS);
1822     }
1823     OS << ", Spelling);\n";
1824     if (R.isSubClassOf(InhClass))
1825       OS << "    cast<InheritableAttr>(New)->setInherited(isInherited);\n";
1826     OS << "    New->setImplicit(isImplicit);\n";
1827     OS << "    break;\n";
1828     OS << "  }\n";
1829   }
1830   OS << "  }\n";
1831 }
1832 
1833 // Emits the code to write an attribute to a precompiled header.
1834 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
1835   emitSourceFileHeader("Attribute serialization code", OS);
1836 
1837   Record *InhClass = Records.getClass("InheritableAttr");
1838   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
1839 
1840   OS << "  switch (A->getKind()) {\n";
1841   OS << "  default:\n";
1842   OS << "    llvm_unreachable(\"Unknown attribute kind!\");\n";
1843   OS << "    break;\n";
1844   for (const auto *Attr : Attrs) {
1845     const Record &R = *Attr;
1846     if (!R.getValueAsBit("ASTNode"))
1847       continue;
1848     OS << "  case attr::" << R.getName() << ": {\n";
1849     Args = R.getValueAsListOfDefs("Args");
1850     if (R.isSubClassOf(InhClass) || !Args.empty())
1851       OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
1852          << "Attr>(A);\n";
1853     if (R.isSubClassOf(InhClass))
1854       OS << "    Record.push_back(SA->isInherited());\n";
1855     OS << "    Record.push_back(A->isImplicit());\n";
1856     OS << "    Record.push_back(A->getSpellingListIndex());\n";
1857 
1858     for (const auto *Arg : Args)
1859       createArgument(*Arg, R.getName())->writePCHWrite(OS);
1860     OS << "    break;\n";
1861     OS << "  }\n";
1862   }
1863   OS << "  }\n";
1864 }
1865 
1866 // Generate a conditional expression to check if the current target satisfies
1867 // the conditions for a TargetSpecificAttr record, and append the code for
1868 // those checks to the Test string. If the FnName string pointer is non-null,
1869 // append a unique suffix to distinguish this set of target checks from other
1870 // TargetSpecificAttr records.
1871 static void GenerateTargetSpecificAttrChecks(const Record *R,
1872                                              std::vector<std::string> &Arches,
1873                                              std::string &Test,
1874                                              std::string *FnName) {
1875   // It is assumed that there will be an llvm::Triple object
1876   // named "T" and a TargetInfo object named "Target" within
1877   // scope that can be used to determine whether the attribute exists in
1878   // a given target.
1879   Test += "(";
1880 
1881   for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
1882     std::string Part = *I;
1883     Test += "T.getArch() == llvm::Triple::" + Part;
1884     if (I + 1 != E)
1885       Test += " || ";
1886     if (FnName)
1887       *FnName += Part;
1888   }
1889   Test += ")";
1890 
1891   // If the attribute is specific to particular OSes, check those.
1892   if (!R->isValueUnset("OSes")) {
1893     // We know that there was at least one arch test, so we need to and in the
1894     // OS tests.
1895     Test += " && (";
1896     std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
1897     for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
1898       std::string Part = *I;
1899 
1900       Test += "T.getOS() == llvm::Triple::" + Part;
1901       if (I + 1 != E)
1902         Test += " || ";
1903       if (FnName)
1904         *FnName += Part;
1905     }
1906     Test += ")";
1907   }
1908 
1909   // If one or more CXX ABIs are specified, check those as well.
1910   if (!R->isValueUnset("CXXABIs")) {
1911     Test += " && (";
1912     std::vector<std::string> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
1913     for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
1914       std::string Part = *I;
1915       Test += "Target.getCXXABI().getKind() == TargetCXXABI::" + Part;
1916       if (I + 1 != E)
1917         Test += " || ";
1918       if (FnName)
1919         *FnName += Part;
1920     }
1921     Test += ")";
1922   }
1923 }
1924 
1925 static void GenerateHasAttrSpellingStringSwitch(
1926     const std::vector<Record *> &Attrs, raw_ostream &OS,
1927     const std::string &Variety = "", const std::string &Scope = "") {
1928   for (const auto *Attr : Attrs) {
1929     // C++11-style attributes have specific version information associated with
1930     // them. If the attribute has no scope, the version information must not
1931     // have the default value (1), as that's incorrect. Instead, the unscoped
1932     // attribute version information should be taken from the SD-6 standing
1933     // document, which can be found at:
1934     // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
1935     int Version = 1;
1936 
1937     if (Variety == "CXX11") {
1938         std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
1939         for (const auto &Spelling : Spellings) {
1940           if (Spelling->getValueAsString("Variety") == "CXX11") {
1941             Version = static_cast<int>(Spelling->getValueAsInt("Version"));
1942             if (Scope.empty() && Version == 1)
1943               PrintError(Spelling->getLoc(), "C++ standard attributes must "
1944               "have valid version information.");
1945             break;
1946           }
1947       }
1948     }
1949 
1950     std::string Test;
1951     if (Attr->isSubClassOf("TargetSpecificAttr")) {
1952       const Record *R = Attr->getValueAsDef("Target");
1953       std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
1954       GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
1955 
1956       // If this is the C++11 variety, also add in the LangOpts test.
1957       if (Variety == "CXX11")
1958         Test += " && LangOpts.CPlusPlus11";
1959     } else if (Variety == "CXX11")
1960       // C++11 mode should be checked against LangOpts, which is presumed to be
1961       // present in the caller.
1962       Test = "LangOpts.CPlusPlus11";
1963 
1964     std::string TestStr =
1965         !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
1966     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1967     for (const auto &S : Spellings)
1968       if (Variety.empty() || (Variety == S.variety() &&
1969                               (Scope.empty() || Scope == S.nameSpace())))
1970         OS << "    .Case(\"" << S.name() << "\", " << TestStr << ")\n";
1971   }
1972   OS << "    .Default(0);\n";
1973 }
1974 
1975 // Emits the list of spellings for attributes.
1976 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1977   emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
1978 
1979   // Separate all of the attributes out into four group: generic, C++11, GNU,
1980   // and declspecs. Then generate a big switch statement for each of them.
1981   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1982   std::vector<Record *> Declspec, GNU, Pragma;
1983   std::map<std::string, std::vector<Record *>> CXX;
1984 
1985   // Walk over the list of all attributes, and split them out based on the
1986   // spelling variety.
1987   for (auto *R : Attrs) {
1988     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1989     for (const auto &SI : Spellings) {
1990       std::string Variety = SI.variety();
1991       if (Variety == "GNU")
1992         GNU.push_back(R);
1993       else if (Variety == "Declspec")
1994         Declspec.push_back(R);
1995       else if (Variety == "CXX11")
1996         CXX[SI.nameSpace()].push_back(R);
1997       else if (Variety == "Pragma")
1998         Pragma.push_back(R);
1999     }
2000   }
2001 
2002   OS << "const llvm::Triple &T = Target.getTriple();\n";
2003   OS << "switch (Syntax) {\n";
2004   OS << "case AttrSyntax::GNU:\n";
2005   OS << "  return llvm::StringSwitch<int>(Name)\n";
2006   GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2007   OS << "case AttrSyntax::Declspec:\n";
2008   OS << "  return llvm::StringSwitch<int>(Name)\n";
2009   GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
2010   OS << "case AttrSyntax::Pragma:\n";
2011   OS << "  return llvm::StringSwitch<int>(Name)\n";
2012   GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
2013   OS << "case AttrSyntax::CXX: {\n";
2014   // C++11-style attributes are further split out based on the Scope.
2015   for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
2016                                                               E = CXX.end();
2017        I != E; ++I) {
2018     if (I != CXX.begin())
2019       OS << " else ";
2020     if (I->first.empty())
2021       OS << "if (!Scope || Scope->getName() == \"\") {\n";
2022     else
2023       OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
2024     OS << "  return llvm::StringSwitch<int>(Name)\n";
2025     GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
2026     OS << "}";
2027   }
2028   OS << "\n}\n";
2029   OS << "}\n";
2030 }
2031 
2032 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
2033   emitSourceFileHeader("Code to translate different attribute spellings "
2034                        "into internal identifiers", OS);
2035 
2036   OS <<
2037     "  switch (AttrKind) {\n"
2038     "  default:\n"
2039     "    llvm_unreachable(\"Unknown attribute kind!\");\n"
2040     "    break;\n";
2041 
2042   ParsedAttrMap Attrs = getParsedAttrList(Records);
2043   for (const auto &I : Attrs) {
2044     const Record &R = *I.second;
2045     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2046     OS << "  case AT_" << I.first << ": {\n";
2047     for (unsigned I = 0; I < Spellings.size(); ++ I) {
2048       OS << "    if (Name == \"" << Spellings[I].name() << "\" && "
2049          << "SyntaxUsed == "
2050          << StringSwitch<unsigned>(Spellings[I].variety())
2051                 .Case("GNU", 0)
2052                 .Case("CXX11", 1)
2053                 .Case("Declspec", 2)
2054                 .Case("Keyword", 3)
2055                 .Case("Pragma", 4)
2056                 .Default(0)
2057          << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2058          << "        return " << I << ";\n";
2059     }
2060 
2061     OS << "    break;\n";
2062     OS << "  }\n";
2063   }
2064 
2065   OS << "  }\n";
2066   OS << "  return 0;\n";
2067 }
2068 
2069 // Emits code used by RecursiveASTVisitor to visit attributes
2070 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2071   emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2072 
2073   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2074 
2075   // Write method declarations for Traverse* methods.
2076   // We emit this here because we only generate methods for attributes that
2077   // are declared as ASTNodes.
2078   OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2079   for (const auto *Attr : Attrs) {
2080     const Record &R = *Attr;
2081     if (!R.getValueAsBit("ASTNode"))
2082       continue;
2083     OS << "  bool Traverse"
2084        << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2085     OS << "  bool Visit"
2086        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2087        << "    return true; \n"
2088        << "  }\n";
2089   }
2090   OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2091 
2092   // Write individual Traverse* methods for each attribute class.
2093   for (const auto *Attr : Attrs) {
2094     const Record &R = *Attr;
2095     if (!R.getValueAsBit("ASTNode"))
2096       continue;
2097 
2098     OS << "template <typename Derived>\n"
2099        << "bool VISITORCLASS<Derived>::Traverse"
2100        << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2101        << "  if (!getDerived().VisitAttr(A))\n"
2102        << "    return false;\n"
2103        << "  if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2104        << "    return false;\n";
2105 
2106     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2107     for (const auto *Arg : ArgRecords)
2108       createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
2109 
2110     OS << "  return true;\n";
2111     OS << "}\n\n";
2112   }
2113 
2114   // Write generic Traverse routine
2115   OS << "template <typename Derived>\n"
2116      << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
2117      << "  if (!A)\n"
2118      << "    return true;\n"
2119      << "\n"
2120      << "  switch (A->getKind()) {\n"
2121      << "    default:\n"
2122      << "      return true;\n";
2123 
2124   for (const auto *Attr : Attrs) {
2125     const Record &R = *Attr;
2126     if (!R.getValueAsBit("ASTNode"))
2127       continue;
2128 
2129     OS << "    case attr::" << R.getName() << ":\n"
2130        << "      return getDerived().Traverse" << R.getName() << "Attr("
2131        << "cast<" << R.getName() << "Attr>(A));\n";
2132   }
2133   OS << "  }\n";  // end case
2134   OS << "}\n";  // end function
2135   OS << "#endif  // ATTR_VISITOR_DECLS_ONLY\n";
2136 }
2137 
2138 // Emits code to instantiate dependent attributes on templates.
2139 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
2140   emitSourceFileHeader("Template instantiation code for attributes", OS);
2141 
2142   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2143 
2144   OS << "namespace clang {\n"
2145      << "namespace sema {\n\n"
2146      << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
2147      << "Sema &S,\n"
2148      << "        const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
2149      << "  switch (At->getKind()) {\n"
2150      << "    default:\n"
2151      << "      break;\n";
2152 
2153   for (const auto *Attr : Attrs) {
2154     const Record &R = *Attr;
2155     if (!R.getValueAsBit("ASTNode"))
2156       continue;
2157 
2158     OS << "    case attr::" << R.getName() << ": {\n";
2159     bool ShouldClone = R.getValueAsBit("Clone");
2160 
2161     if (!ShouldClone) {
2162       OS << "      return nullptr;\n";
2163       OS << "    }\n";
2164       continue;
2165     }
2166 
2167     OS << "      const " << R.getName() << "Attr *A = cast<"
2168        << R.getName() << "Attr>(At);\n";
2169     bool TDependent = R.getValueAsBit("TemplateDependent");
2170 
2171     if (!TDependent) {
2172       OS << "      return A->clone(C);\n";
2173       OS << "    }\n";
2174       continue;
2175     }
2176 
2177     std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2178     std::vector<std::unique_ptr<Argument>> Args;
2179     Args.reserve(ArgRecords.size());
2180 
2181     for (const auto *ArgRecord : ArgRecords)
2182       Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2183 
2184     for (auto const &ai : Args)
2185       ai->writeTemplateInstantiation(OS);
2186 
2187     OS << "      return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2188     for (auto const &ai : Args) {
2189       OS << ", ";
2190       ai->writeTemplateInstantiationArgs(OS);
2191     }
2192     OS << ", A->getSpellingListIndex());\n    }\n";
2193   }
2194   OS << "  } // end switch\n"
2195      << "  llvm_unreachable(\"Unknown attribute!\");\n"
2196      << "  return nullptr;\n"
2197      << "}\n\n"
2198      << "} // end namespace sema\n"
2199      << "} // end namespace clang\n";
2200 }
2201 
2202 // Emits the list of parsed attributes.
2203 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2204   emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2205 
2206   OS << "#ifndef PARSED_ATTR\n";
2207   OS << "#define PARSED_ATTR(NAME) NAME\n";
2208   OS << "#endif\n\n";
2209 
2210   ParsedAttrMap Names = getParsedAttrList(Records);
2211   for (const auto &I : Names) {
2212     OS << "PARSED_ATTR(" << I.first << ")\n";
2213   }
2214 }
2215 
2216 static bool isArgVariadic(const Record &R, StringRef AttrName) {
2217   return createArgument(R, AttrName)->isVariadic();
2218 }
2219 
2220 static void emitArgInfo(const Record &R, std::stringstream &OS) {
2221   // This function will count the number of arguments specified for the
2222   // attribute and emit the number of required arguments followed by the
2223   // number of optional arguments.
2224   std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
2225   unsigned ArgCount = 0, OptCount = 0;
2226   bool HasVariadic = false;
2227   for (const auto *Arg : Args) {
2228     Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
2229     if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
2230       HasVariadic = true;
2231   }
2232 
2233   // If there is a variadic argument, we will set the optional argument count
2234   // to its largest value. Since it's currently a 4-bit number, we set it to 15.
2235   OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
2236 }
2237 
2238 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
2239   OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
2240   OS << "const Decl *) {\n";
2241   OS << "  return true;\n";
2242   OS << "}\n\n";
2243 }
2244 
2245 static std::string CalculateDiagnostic(const Record &S) {
2246   // If the SubjectList object has a custom diagnostic associated with it,
2247   // return that directly.
2248   std::string CustomDiag = S.getValueAsString("CustomDiag");
2249   if (!CustomDiag.empty())
2250     return CustomDiag;
2251 
2252   // Given the list of subjects, determine what diagnostic best fits.
2253   enum {
2254     Func = 1U << 0,
2255     Var = 1U << 1,
2256     ObjCMethod = 1U << 2,
2257     Param = 1U << 3,
2258     Class = 1U << 4,
2259     GenericRecord = 1U << 5,
2260     Type = 1U << 6,
2261     ObjCIVar = 1U << 7,
2262     ObjCProp = 1U << 8,
2263     ObjCInterface = 1U << 9,
2264     Block = 1U << 10,
2265     Namespace = 1U << 11,
2266     Field = 1U << 12,
2267     CXXMethod = 1U << 13,
2268     ObjCProtocol = 1U << 14,
2269     Enum = 1U << 15
2270   };
2271   uint32_t SubMask = 0;
2272 
2273   std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2274   for (const auto *Subject : Subjects) {
2275     const Record &R = *Subject;
2276     std::string Name;
2277 
2278     if (R.isSubClassOf("SubsetSubject")) {
2279       PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2280       // As a fallback, look through the SubsetSubject to see what its base
2281       // type is, and use that. This needs to be updated if SubsetSubjects
2282       // are allowed within other SubsetSubjects.
2283       Name = R.getValueAsDef("Base")->getName();
2284     } else
2285       Name = R.getName();
2286 
2287     uint32_t V = StringSwitch<uint32_t>(Name)
2288                    .Case("Function", Func)
2289                    .Case("Var", Var)
2290                    .Case("ObjCMethod", ObjCMethod)
2291                    .Case("ParmVar", Param)
2292                    .Case("TypedefName", Type)
2293                    .Case("ObjCIvar", ObjCIVar)
2294                    .Case("ObjCProperty", ObjCProp)
2295                    .Case("Record", GenericRecord)
2296                    .Case("ObjCInterface", ObjCInterface)
2297                    .Case("ObjCProtocol", ObjCProtocol)
2298                    .Case("Block", Block)
2299                    .Case("CXXRecord", Class)
2300                    .Case("Namespace", Namespace)
2301                    .Case("Field", Field)
2302                    .Case("CXXMethod", CXXMethod)
2303                    .Case("Enum", Enum)
2304                    .Default(0);
2305     if (!V) {
2306       // Something wasn't in our mapping, so be helpful and let the developer
2307       // know about it.
2308       PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2309       return "";
2310     }
2311 
2312     SubMask |= V;
2313   }
2314 
2315   switch (SubMask) {
2316     // For the simple cases where there's only a single entry in the mask, we
2317     // don't have to resort to bit fiddling.
2318     case Func:  return "ExpectedFunction";
2319     case Var:   return "ExpectedVariable";
2320     case Param: return "ExpectedParameter";
2321     case Class: return "ExpectedClass";
2322     case Enum:  return "ExpectedEnum";
2323     case CXXMethod:
2324       // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2325       // but should map to something a bit more accurate at some point.
2326     case ObjCMethod:  return "ExpectedMethod";
2327     case Type:  return "ExpectedType";
2328     case ObjCInterface: return "ExpectedObjectiveCInterface";
2329     case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2330 
2331     // "GenericRecord" means struct, union or class; check the language options
2332     // and if not compiling for C++, strip off the class part. Note that this
2333     // relies on the fact that the context for this declares "Sema &S".
2334     case GenericRecord:
2335       return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2336                                            "ExpectedStructOrUnion)";
2337     case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2338     case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2339     case Func | Param:
2340     case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2341     case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2342     case Func | Var: return "ExpectedVariableOrFunction";
2343 
2344     // If not compiling for C++, the class portion does not apply.
2345     case Func | Var | Class:
2346       return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2347                                            "ExpectedVariableOrFunction)";
2348 
2349     case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2350     case ObjCProtocol | ObjCInterface:
2351       return "ExpectedObjectiveCInterfaceOrProtocol";
2352     case Field | Var: return "ExpectedFieldOrGlobalVar";
2353   }
2354 
2355   PrintFatalError(S.getLoc(),
2356                   "Could not deduce diagnostic argument for Attr subjects");
2357 
2358   return "";
2359 }
2360 
2361 static std::string GetSubjectWithSuffix(const Record *R) {
2362   std::string B = R->getName();
2363   if (B == "DeclBase")
2364     return "Decl";
2365   return B + "Decl";
2366 }
2367 
2368 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2369                                               raw_ostream &OS) {
2370   std::string FnName = "is" + Subject.getName();
2371 
2372   // If this code has already been generated, simply return the previous
2373   // instance of it.
2374   static std::set<std::string> CustomSubjectSet;
2375   std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
2376   if (I != CustomSubjectSet.end())
2377     return *I;
2378 
2379   Record *Base = Subject.getValueAsDef("Base");
2380 
2381   // Not currently support custom subjects within custom subjects.
2382   if (Base->isSubClassOf("SubsetSubject")) {
2383     PrintFatalError(Subject.getLoc(),
2384                     "SubsetSubjects within SubsetSubjects is not supported");
2385     return "";
2386   }
2387 
2388   OS << "static bool " << FnName << "(const Decl *D) {\n";
2389   OS << "  if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
2390   OS << GetSubjectWithSuffix(Base);
2391   OS << ">(D))\n";
2392   OS << "    return " << Subject.getValueAsString("CheckCode") << ";\n";
2393   OS << "  return false;\n";
2394   OS << "}\n\n";
2395 
2396   CustomSubjectSet.insert(FnName);
2397   return FnName;
2398 }
2399 
2400 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2401   // If the attribute does not contain a Subjects definition, then use the
2402   // default appertainsTo logic.
2403   if (Attr.isValueUnset("Subjects"))
2404     return "defaultAppertainsTo";
2405 
2406   const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2407   std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2408 
2409   // If the list of subjects is empty, it is assumed that the attribute
2410   // appertains to everything.
2411   if (Subjects.empty())
2412     return "defaultAppertainsTo";
2413 
2414   bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2415 
2416   // Otherwise, generate an appertainsTo check specific to this attribute which
2417   // checks all of the given subjects against the Decl passed in. Return the
2418   // name of that check to the caller.
2419   std::string FnName = "check" + Attr.getName() + "AppertainsTo";
2420   std::stringstream SS;
2421   SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2422   SS << "const Decl *D) {\n";
2423   SS << "  if (";
2424   for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2425     // If the subject has custom code associated with it, generate a function
2426     // for it. The function cannot be inlined into this check (yet) because it
2427     // requires the subject to be of a specific type, and were that information
2428     // inlined here, it would not support an attribute with multiple custom
2429     // subjects.
2430     if ((*I)->isSubClassOf("SubsetSubject")) {
2431       SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2432     } else {
2433       SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2434     }
2435 
2436     if (I + 1 != E)
2437       SS << " && ";
2438   }
2439   SS << ") {\n";
2440   SS << "    S.Diag(Attr.getLoc(), diag::";
2441   SS << (Warn ? "warn_attribute_wrong_decl_type" :
2442                "err_attribute_wrong_decl_type");
2443   SS << ")\n";
2444   SS << "      << Attr.getName() << ";
2445   SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2446   SS << "    return false;\n";
2447   SS << "  }\n";
2448   SS << "  return true;\n";
2449   SS << "}\n\n";
2450 
2451   OS << SS.str();
2452   return FnName;
2453 }
2454 
2455 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2456   OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2457   OS << "const AttributeList &) {\n";
2458   OS << "  return true;\n";
2459   OS << "}\n\n";
2460 }
2461 
2462 static std::string GenerateLangOptRequirements(const Record &R,
2463                                                raw_ostream &OS) {
2464   // If the attribute has an empty or unset list of language requirements,
2465   // return the default handler.
2466   std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2467   if (LangOpts.empty())
2468     return "defaultDiagnoseLangOpts";
2469 
2470   // Generate the test condition, as well as a unique function name for the
2471   // diagnostic test. The list of options should usually be short (one or two
2472   // options), and the uniqueness isn't strictly necessary (it is just for
2473   // codegen efficiency).
2474   std::string FnName = "check", Test;
2475   for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2476     std::string Part = (*I)->getValueAsString("Name");
2477     if ((*I)->getValueAsBit("Negated"))
2478       Test += "!";
2479     Test += "S.LangOpts." + Part;
2480     if (I + 1 != E)
2481       Test += " || ";
2482     FnName += Part;
2483   }
2484   FnName += "LangOpts";
2485 
2486   // If this code has already been generated, simply return the previous
2487   // instance of it.
2488   static std::set<std::string> CustomLangOptsSet;
2489   std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
2490   if (I != CustomLangOptsSet.end())
2491     return *I;
2492 
2493   OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2494   OS << "  if (" << Test << ")\n";
2495   OS << "    return true;\n\n";
2496   OS << "  S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2497   OS << "<< Attr.getName();\n";
2498   OS << "  return false;\n";
2499   OS << "}\n\n";
2500 
2501   CustomLangOptsSet.insert(FnName);
2502   return FnName;
2503 }
2504 
2505 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2506   OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
2507   OS << "  return true;\n";
2508   OS << "}\n\n";
2509 }
2510 
2511 static std::string GenerateTargetRequirements(const Record &Attr,
2512                                               const ParsedAttrMap &Dupes,
2513                                               raw_ostream &OS) {
2514   // If the attribute is not a target specific attribute, return the default
2515   // target handler.
2516   if (!Attr.isSubClassOf("TargetSpecificAttr"))
2517     return "defaultTargetRequirements";
2518 
2519   // Get the list of architectures to be tested for.
2520   const Record *R = Attr.getValueAsDef("Target");
2521   std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2522   if (Arches.empty()) {
2523     PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2524                               "target-specific attr");
2525     return "defaultTargetRequirements";
2526   }
2527 
2528   // If there are other attributes which share the same parsed attribute kind,
2529   // such as target-specific attributes with a shared spelling, collapse the
2530   // duplicate architectures. This is required because a shared target-specific
2531   // attribute has only one AttributeList::Kind enumeration value, but it
2532   // applies to multiple target architectures. In order for the attribute to be
2533   // considered valid, all of its architectures need to be included.
2534   if (!Attr.isValueUnset("ParseKind")) {
2535     std::string APK = Attr.getValueAsString("ParseKind");
2536     for (const auto &I : Dupes) {
2537       if (I.first == APK) {
2538         std::vector<std::string> DA = I.second->getValueAsDef("Target")
2539                                           ->getValueAsListOfStrings("Arches");
2540         std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
2541       }
2542     }
2543   }
2544 
2545   std::string FnName = "isTarget";
2546   std::string Test;
2547   GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
2548 
2549   // If this code has already been generated, simply return the previous
2550   // instance of it.
2551   static std::set<std::string> CustomTargetSet;
2552   std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
2553   if (I != CustomTargetSet.end())
2554     return *I;
2555 
2556   OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
2557   OS << "  const llvm::Triple &T = Target.getTriple();\n";
2558   OS << "  return " << Test << ";\n";
2559   OS << "}\n\n";
2560 
2561   CustomTargetSet.insert(FnName);
2562   return FnName;
2563 }
2564 
2565 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2566   OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2567      << "const AttributeList &Attr) {\n";
2568   OS << "  return UINT_MAX;\n";
2569   OS << "}\n\n";
2570 }
2571 
2572 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2573                                                            raw_ostream &OS) {
2574   // If the attribute does not have a semantic form, we can bail out early.
2575   if (!Attr.getValueAsBit("ASTNode"))
2576     return "defaultSpellingIndexToSemanticSpelling";
2577 
2578   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2579 
2580   // If there are zero or one spellings, or all of the spellings share the same
2581   // name, we can also bail out early.
2582   if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2583     return "defaultSpellingIndexToSemanticSpelling";
2584 
2585   // Generate the enumeration we will use for the mapping.
2586   SemanticSpellingMap SemanticToSyntacticMap;
2587   std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2588   std::string Name = Attr.getName() + "AttrSpellingMap";
2589 
2590   OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2591   OS << Enum;
2592   OS << "  unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2593   WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2594   OS << "}\n\n";
2595 
2596   return Name;
2597 }
2598 
2599 static bool IsKnownToGCC(const Record &Attr) {
2600   // Look at the spellings for this subject; if there are any spellings which
2601   // claim to be known to GCC, the attribute is known to GCC.
2602   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2603   for (const auto &I : Spellings) {
2604     if (I.knownToGCC())
2605       return true;
2606   }
2607   return false;
2608 }
2609 
2610 /// Emits the parsed attribute helpers
2611 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2612   emitSourceFileHeader("Parsed attribute helpers", OS);
2613 
2614   // Get the list of parsed attributes, and accept the optional list of
2615   // duplicates due to the ParseKind.
2616   ParsedAttrMap Dupes;
2617   ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2618 
2619   // Generate the default appertainsTo, target and language option diagnostic,
2620   // and spelling list index mapping methods.
2621   GenerateDefaultAppertainsTo(OS);
2622   GenerateDefaultLangOptRequirements(OS);
2623   GenerateDefaultTargetRequirements(OS);
2624   GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2625 
2626   // Generate the appertainsTo diagnostic methods and write their names into
2627   // another mapping. At the same time, generate the AttrInfoMap object
2628   // contents. Due to the reliance on generated code, use separate streams so
2629   // that code will not be interleaved.
2630   std::stringstream SS;
2631   for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2632     // TODO: If the attribute's kind appears in the list of duplicates, that is
2633     // because it is a target-specific attribute that appears multiple times.
2634     // It would be beneficial to test whether the duplicates are "similar
2635     // enough" to each other to not cause problems. For instance, check that
2636     // the spellings are identical, and custom parsing rules match, etc.
2637 
2638     // We need to generate struct instances based off ParsedAttrInfo from
2639     // AttributeList.cpp.
2640     SS << "  { ";
2641     emitArgInfo(*I->second, SS);
2642     SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2643     SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2644     SS << ", " << I->second->isSubClassOf("TypeAttr");
2645     SS << ", " << IsKnownToGCC(*I->second);
2646     SS << ", " << GenerateAppertainsTo(*I->second, OS);
2647     SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2648     SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2649     SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2650     SS << " }";
2651 
2652     if (I + 1 != E)
2653       SS << ",";
2654 
2655     SS << "  // AT_" << I->first << "\n";
2656   }
2657 
2658   OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2659   OS << SS.str();
2660   OS << "};\n\n";
2661 }
2662 
2663 // Emits the kind list of parsed attributes
2664 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2665   emitSourceFileHeader("Attribute name matcher", OS);
2666 
2667   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2668   std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
2669   std::set<std::string> Seen;
2670   for (const auto *A : Attrs) {
2671     const Record &Attr = *A;
2672 
2673     bool SemaHandler = Attr.getValueAsBit("SemaHandler");
2674     bool Ignored = Attr.getValueAsBit("Ignored");
2675     if (SemaHandler || Ignored) {
2676       // Attribute spellings can be shared between target-specific attributes,
2677       // and can be shared between syntaxes for the same attribute. For
2678       // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
2679       // specific attribute, or MSP430-specific attribute. Additionally, an
2680       // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
2681       // for the same semantic attribute. Ultimately, we need to map each of
2682       // these to a single AttributeList::Kind value, but the StringMatcher
2683       // class cannot handle duplicate match strings. So we generate a list of
2684       // string to match based on the syntax, and emit multiple string matchers
2685       // depending on the syntax used.
2686       std::string AttrName;
2687       if (Attr.isSubClassOf("TargetSpecificAttr") &&
2688           !Attr.isValueUnset("ParseKind")) {
2689         AttrName = Attr.getValueAsString("ParseKind");
2690         if (Seen.find(AttrName) != Seen.end())
2691           continue;
2692         Seen.insert(AttrName);
2693       } else
2694         AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
2695 
2696       std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2697       for (const auto &S : Spellings) {
2698         std::string RawSpelling = S.name();
2699         std::vector<StringMatcher::StringPair> *Matches = nullptr;
2700         std::string Spelling, Variety = S.variety();
2701         if (Variety == "CXX11") {
2702           Matches = &CXX11;
2703           Spelling += S.nameSpace();
2704           Spelling += "::";
2705         } else if (Variety == "GNU")
2706           Matches = &GNU;
2707         else if (Variety == "Declspec")
2708           Matches = &Declspec;
2709         else if (Variety == "Keyword")
2710           Matches = &Keywords;
2711         else if (Variety == "Pragma")
2712           Matches = &Pragma;
2713 
2714         assert(Matches && "Unsupported spelling variety found");
2715 
2716         Spelling += NormalizeAttrSpelling(RawSpelling);
2717         if (SemaHandler)
2718           Matches->push_back(StringMatcher::StringPair(Spelling,
2719                               "return AttributeList::AT_" + AttrName + ";"));
2720         else
2721           Matches->push_back(StringMatcher::StringPair(Spelling,
2722                               "return AttributeList::IgnoredAttribute;"));
2723       }
2724     }
2725   }
2726 
2727   OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
2728   OS << "AttributeList::Syntax Syntax) {\n";
2729   OS << "  if (AttributeList::AS_GNU == Syntax) {\n";
2730   StringMatcher("Name", GNU, OS).Emit();
2731   OS << "  } else if (AttributeList::AS_Declspec == Syntax) {\n";
2732   StringMatcher("Name", Declspec, OS).Emit();
2733   OS << "  } else if (AttributeList::AS_CXX11 == Syntax) {\n";
2734   StringMatcher("Name", CXX11, OS).Emit();
2735   OS << "  } else if (AttributeList::AS_Keyword == Syntax || ";
2736   OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
2737   StringMatcher("Name", Keywords, OS).Emit();
2738   OS << "  } else if (AttributeList::AS_Pragma == Syntax) {\n";
2739   StringMatcher("Name", Pragma, OS).Emit();
2740   OS << "  }\n";
2741   OS << "  return AttributeList::UnknownAttribute;\n"
2742      << "}\n";
2743 }
2744 
2745 // Emits the code to dump an attribute.
2746 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
2747   emitSourceFileHeader("Attribute dumper", OS);
2748 
2749   OS <<
2750     "  switch (A->getKind()) {\n"
2751     "  default:\n"
2752     "    llvm_unreachable(\"Unknown attribute kind!\");\n"
2753     "    break;\n";
2754   std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2755   for (const auto *Attr : Attrs) {
2756     const Record &R = *Attr;
2757     if (!R.getValueAsBit("ASTNode"))
2758       continue;
2759     OS << "  case attr::" << R.getName() << ": {\n";
2760 
2761     // If the attribute has a semantically-meaningful name (which is determined
2762     // by whether there is a Spelling enumeration for it), then write out the
2763     // spelling used for the attribute.
2764     std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2765     if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
2766       OS << "    OS << \" \" << A->getSpelling();\n";
2767 
2768     Args = R.getValueAsListOfDefs("Args");
2769     if (!Args.empty()) {
2770       OS << "    const " << R.getName() << "Attr *SA = cast<" << R.getName()
2771          << "Attr>(A);\n";
2772       for (const auto *Arg : Args)
2773         createArgument(*Arg, R.getName())->writeDump(OS);
2774 
2775       for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI)
2776         createArgument(**AI, R.getName())->writeDumpChildren(OS);
2777     }
2778     OS <<
2779       "    break;\n"
2780       "  }\n";
2781   }
2782   OS << "  }\n";
2783 }
2784 
2785 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
2786                                        raw_ostream &OS) {
2787   emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
2788   emitClangAttrArgContextList(Records, OS);
2789   emitClangAttrIdentifierArgList(Records, OS);
2790   emitClangAttrTypeArgList(Records, OS);
2791   emitClangAttrLateParsedList(Records, OS);
2792 }
2793 
2794 class DocumentationData {
2795 public:
2796   const Record *Documentation;
2797   const Record *Attribute;
2798 
2799   DocumentationData(const Record &Documentation, const Record &Attribute)
2800       : Documentation(&Documentation), Attribute(&Attribute) {}
2801 };
2802 
2803 static void WriteCategoryHeader(const Record *DocCategory,
2804                                 raw_ostream &OS) {
2805   const std::string &Name = DocCategory->getValueAsString("Name");
2806   OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
2807 
2808   // If there is content, print that as well.
2809   std::string ContentStr = DocCategory->getValueAsString("Content");
2810   // Trim leading and trailing newlines and spaces.
2811   OS << StringRef(ContentStr).trim();
2812 
2813   OS << "\n\n";
2814 }
2815 
2816 enum SpellingKind {
2817   GNU = 1 << 0,
2818   CXX11 = 1 << 1,
2819   Declspec = 1 << 2,
2820   Keyword = 1 << 3,
2821   Pragma = 1 << 4
2822 };
2823 
2824 static void WriteDocumentation(const DocumentationData &Doc,
2825                                raw_ostream &OS) {
2826   // FIXME: there is no way to have a per-spelling category for the attribute
2827   // documentation. This may not be a limiting factor since the spellings
2828   // should generally be consistently applied across the category.
2829 
2830   std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
2831 
2832   // Determine the heading to be used for this attribute.
2833   std::string Heading = Doc.Documentation->getValueAsString("Heading");
2834   bool CustomHeading = !Heading.empty();
2835   if (Heading.empty()) {
2836     // If there's only one spelling, we can simply use that.
2837     if (Spellings.size() == 1)
2838       Heading = Spellings.begin()->name();
2839     else {
2840       std::set<std::string> Uniques;
2841       for (auto I = Spellings.begin(), E = Spellings.end();
2842            I != E && Uniques.size() <= 1; ++I) {
2843         std::string Spelling = NormalizeNameForSpellingComparison(I->name());
2844         Uniques.insert(Spelling);
2845       }
2846       // If the semantic map has only one spelling, that is sufficient for our
2847       // needs.
2848       if (Uniques.size() == 1)
2849         Heading = *Uniques.begin();
2850     }
2851   }
2852 
2853   // If the heading is still empty, it is an error.
2854   if (Heading.empty())
2855     PrintFatalError(Doc.Attribute->getLoc(),
2856                     "This attribute requires a heading to be specified");
2857 
2858   // Gather a list of unique spellings; this is not the same as the semantic
2859   // spelling for the attribute. Variations in underscores and other non-
2860   // semantic characters are still acceptable.
2861   std::vector<std::string> Names;
2862 
2863   unsigned SupportedSpellings = 0;
2864   for (const auto &I : Spellings) {
2865     SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
2866                             .Case("GNU", GNU)
2867                             .Case("CXX11", CXX11)
2868                             .Case("Declspec", Declspec)
2869                             .Case("Keyword", Keyword)
2870                             .Case("Pragma", Pragma);
2871 
2872     // Mask in the supported spelling.
2873     SupportedSpellings |= Kind;
2874 
2875     std::string Name;
2876     if (Kind == CXX11 && !I.nameSpace().empty())
2877       Name = I.nameSpace() + "::";
2878     Name += I.name();
2879 
2880     // If this name is the same as the heading, do not add it.
2881     if (Name != Heading)
2882       Names.push_back(Name);
2883   }
2884 
2885   // Print out the heading for the attribute. If there are alternate spellings,
2886   // then display those after the heading.
2887   if (!CustomHeading && !Names.empty()) {
2888     Heading += " (";
2889     for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
2890       if (I != Names.begin())
2891         Heading += ", ";
2892       Heading += *I;
2893     }
2894     Heading += ")";
2895   }
2896   OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
2897 
2898   if (!SupportedSpellings)
2899     PrintFatalError(Doc.Attribute->getLoc(),
2900                     "Attribute has no supported spellings; cannot be "
2901                     "documented");
2902 
2903   // List what spelling syntaxes the attribute supports.
2904   OS << ".. csv-table:: Supported Syntaxes\n";
2905   OS << "   :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
2906   OS << " \"Pragma\"\n\n";
2907   OS << "   \"";
2908   if (SupportedSpellings & GNU) OS << "X";
2909   OS << "\",\"";
2910   if (SupportedSpellings & CXX11) OS << "X";
2911   OS << "\",\"";
2912   if (SupportedSpellings & Declspec) OS << "X";
2913   OS << "\",\"";
2914   if (SupportedSpellings & Keyword) OS << "X";
2915   OS << "\", \"";
2916   if (SupportedSpellings & Pragma) OS << "X";
2917   OS << "\"\n\n";
2918 
2919   // If the attribute is deprecated, print a message about it, and possibly
2920   // provide a replacement attribute.
2921   if (!Doc.Documentation->isValueUnset("Deprecated")) {
2922     OS << "This attribute has been deprecated, and may be removed in a future "
2923        << "version of Clang.";
2924     const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
2925     std::string Replacement = Deprecated.getValueAsString("Replacement");
2926     if (!Replacement.empty())
2927       OS << "  This attribute has been superseded by ``"
2928          << Replacement << "``.";
2929     OS << "\n\n";
2930   }
2931 
2932   std::string ContentStr = Doc.Documentation->getValueAsString("Content");
2933   // Trim leading and trailing newlines and spaces.
2934   OS << StringRef(ContentStr).trim();
2935 
2936   OS << "\n\n\n";
2937 }
2938 
2939 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
2940   // Get the documentation introduction paragraph.
2941   const Record *Documentation = Records.getDef("GlobalDocumentation");
2942   if (!Documentation) {
2943     PrintFatalError("The Documentation top-level definition is missing, "
2944                     "no documentation will be generated.");
2945     return;
2946   }
2947 
2948   OS << Documentation->getValueAsString("Intro") << "\n";
2949 
2950   // Gather the Documentation lists from each of the attributes, based on the
2951   // category provided.
2952   std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2953   std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
2954   for (const auto *A : Attrs) {
2955     const Record &Attr = *A;
2956     std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
2957     for (const auto *D : Docs) {
2958       const Record &Doc = *D;
2959       const Record *Category = Doc.getValueAsDef("Category");
2960       // If the category is "undocumented", then there cannot be any other
2961       // documentation categories (otherwise, the attribute would become
2962       // documented).
2963       std::string Cat = Category->getValueAsString("Name");
2964       bool Undocumented = Cat == "Undocumented";
2965       if (Undocumented && Docs.size() > 1)
2966         PrintFatalError(Doc.getLoc(),
2967                         "Attribute is \"Undocumented\", but has multiple "
2968                         "documentation categories");
2969 
2970       if (!Undocumented)
2971         SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
2972     }
2973   }
2974 
2975   // Having split the attributes out based on what documentation goes where,
2976   // we can begin to generate sections of documentation.
2977   for (const auto &I : SplitDocs) {
2978     WriteCategoryHeader(I.first, OS);
2979 
2980     // Walk over each of the attributes in the category and write out their
2981     // documentation.
2982     for (const auto &Doc : I.second)
2983       WriteDocumentation(Doc, OS);
2984   }
2985 }
2986 
2987 } // end namespace clang
2988