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