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