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