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