1 //===- ClangAttrEmitter.cpp - Generate Clang attribute handling =-*- C++ -*--=//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // These tablegen backends emit Clang attribute processing code
12 //===----------------------------------------------------------------------===//
14 #include "llvm/ADT/SmallString.h"
15 #include "llvm/ADT/STLExtras.h"
16 #include "llvm/ADT/SmallSet.h"
17 #include "llvm/ADT/StringSwitch.h"
18 #include "llvm/TableGen/Error.h"
19 #include "llvm/TableGen/Record.h"
20 #include "llvm/TableGen/StringMatcher.h"
21 #include "llvm/TableGen/TableGenBackend.h"
30 class FlattenedSpelling {
35 FlattenedSpelling(const std::string &Variety, const std::string &Name,
36 const std::string &Namespace, bool KnownToGCC) :
37 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
38 explicit FlattenedSpelling(const Record &Spelling) :
39 V(Spelling.getValueAsString("Variety")),
40 N(Spelling.getValueAsString("Name")) {
42 assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
44 if (V == "CXX11" || V == "Pragma")
45 NS = Spelling.getValueAsString("Namespace");
47 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
50 const std::string &variety() const { return V; }
51 const std::string &name() const { return N; }
52 const std::string &nameSpace() const { return NS; }
53 bool knownToGCC() const { return K; }
56 std::vector<FlattenedSpelling> GetFlattenedSpellings(const Record &Attr) {
57 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
58 std::vector<FlattenedSpelling> Ret;
60 for (const auto &Spelling : Spellings) {
61 if (Spelling->getValueAsString("Variety") == "GCC") {
62 // Gin up two new spelling objects to add into the list.
63 Ret.push_back(FlattenedSpelling("GNU", Spelling->getValueAsString("Name"),
65 Ret.push_back(FlattenedSpelling(
66 "CXX11", Spelling->getValueAsString("Name"), "gnu", true));
68 Ret.push_back(FlattenedSpelling(*Spelling));
74 static std::string ReadPCHRecord(StringRef type) {
75 return StringSwitch<std::string>(type)
76 .EndsWith("Decl *", "GetLocalDeclAs<"
77 + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
78 .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
79 .Case("Expr *", "ReadExpr(F)")
80 .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
81 .Default("Record[Idx++]");
84 // Assumes that the way to get the value is SA->getname()
85 static std::string WritePCHRecord(StringRef type, StringRef name) {
86 return StringSwitch<std::string>(type)
87 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
89 .Case("TypeSourceInfo *",
90 "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
91 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
92 .Case("IdentifierInfo *",
93 "AddIdentifierRef(" + std::string(name) + ", Record);\n")
94 .Default("Record.push_back(" + std::string(name) + ");\n");
97 // Normalize attribute name by removing leading and trailing
98 // underscores. For example, __foo, foo__, __foo__ would
100 static StringRef NormalizeAttrName(StringRef AttrName) {
101 if (AttrName.startswith("__"))
102 AttrName = AttrName.substr(2, AttrName.size());
104 if (AttrName.endswith("__"))
105 AttrName = AttrName.substr(0, AttrName.size() - 2);
110 // Normalize the name by removing any and all leading and trailing underscores.
111 // This is different from NormalizeAttrName in that it also handles names like
112 // _pascal and __pascal.
113 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
114 while (Name.startswith("_"))
115 Name = Name.substr(1, Name.size());
116 while (Name.endswith("_"))
117 Name = Name.substr(0, Name.size() - 1);
121 // Normalize attribute spelling only if the spelling has both leading
122 // and trailing underscores. For example, __ms_struct__ will be
123 // normalized to "ms_struct"; __cdecl will remain intact.
124 static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
125 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
126 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
132 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
134 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
135 ParsedAttrMap *Dupes = nullptr) {
136 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
137 std::set<std::string> Seen;
139 for (const auto *Attr : Attrs) {
140 if (Attr->getValueAsBit("SemaHandler")) {
142 if (Attr->isSubClassOf("TargetSpecificAttr") &&
143 !Attr->isValueUnset("ParseKind")) {
144 AN = Attr->getValueAsString("ParseKind");
146 // If this attribute has already been handled, it does not need to be
148 if (Seen.find(AN) != Seen.end()) {
150 Dupes->push_back(std::make_pair(AN, Attr));
155 AN = NormalizeAttrName(Attr->getName()).str();
157 R.push_back(std::make_pair(AN, Attr));
165 std::string lowerName, upperName;
170 Argument(const Record &Arg, StringRef Attr)
171 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
172 attrName(Attr), isOpt(false) {
173 if (!lowerName.empty()) {
174 lowerName[0] = std::tolower(lowerName[0]);
175 upperName[0] = std::toupper(upperName[0]);
178 virtual ~Argument() {}
180 StringRef getLowerName() const { return lowerName; }
181 StringRef getUpperName() const { return upperName; }
182 StringRef getAttrName() const { return attrName; }
184 bool isOptional() const { return isOpt; }
185 void setOptional(bool set) { isOpt = set; }
187 // These functions print the argument contents formatted in different ways.
188 virtual void writeAccessors(raw_ostream &OS) const = 0;
189 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
190 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
191 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
192 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
193 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
194 virtual void writeCtorBody(raw_ostream &OS) const {}
195 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
196 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
197 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
198 virtual void writeDeclarations(raw_ostream &OS) const = 0;
199 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
200 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
201 virtual void writePCHWrite(raw_ostream &OS) const = 0;
202 virtual void writeValue(raw_ostream &OS) const = 0;
203 virtual void writeDump(raw_ostream &OS) const = 0;
204 virtual void writeDumpChildren(raw_ostream &OS) const {}
205 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
207 virtual bool isEnumArg() const { return false; }
208 virtual bool isVariadicEnumArg() const { return false; }
210 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
211 OS << getUpperName();
215 class SimpleArgument : public Argument {
219 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
220 : Argument(Arg, Attr), type(T)
223 std::string getType() const { return type; }
225 void writeAccessors(raw_ostream &OS) const override {
226 OS << " " << type << " get" << getUpperName() << "() const {\n";
227 OS << " return " << getLowerName() << ";\n";
230 void writeCloneArgs(raw_ostream &OS) const override {
231 OS << getLowerName();
233 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
234 OS << "A->get" << getUpperName() << "()";
236 void writeCtorInitializers(raw_ostream &OS) const override {
237 OS << getLowerName() << "(" << getUpperName() << ")";
239 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
240 OS << getLowerName() << "()";
242 void writeCtorParameters(raw_ostream &OS) const override {
243 OS << type << " " << getUpperName();
245 void writeDeclarations(raw_ostream &OS) const override {
246 OS << type << " " << getLowerName() << ";";
248 void writePCHReadDecls(raw_ostream &OS) const override {
249 std::string read = ReadPCHRecord(type);
250 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
252 void writePCHReadArgs(raw_ostream &OS) const override {
253 OS << getLowerName();
255 void writePCHWrite(raw_ostream &OS) const override {
256 OS << " " << WritePCHRecord(type, "SA->get" +
257 std::string(getUpperName()) + "()");
259 void writeValue(raw_ostream &OS) const override {
260 if (type == "FunctionDecl *") {
261 OS << "\" << get" << getUpperName()
262 << "()->getNameInfo().getAsString() << \"";
263 } else if (type == "IdentifierInfo *") {
264 OS << "\" << get" << getUpperName() << "()->getName() << \"";
265 } else if (type == "TypeSourceInfo *") {
266 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
268 OS << "\" << get" << getUpperName() << "() << \"";
271 void writeDump(raw_ostream &OS) const override {
272 if (type == "FunctionDecl *") {
273 OS << " OS << \" \";\n";
274 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
275 } else if (type == "IdentifierInfo *") {
276 OS << " OS << \" \" << SA->get" << getUpperName()
277 << "()->getName();\n";
278 } else if (type == "TypeSourceInfo *") {
279 OS << " OS << \" \" << SA->get" << getUpperName()
280 << "().getAsString();\n";
281 } else if (type == "bool") {
282 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
283 << getUpperName() << "\";\n";
284 } else if (type == "int" || type == "unsigned") {
285 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
287 llvm_unreachable("Unknown SimpleArgument type!");
292 class DefaultSimpleArgument : public SimpleArgument {
296 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
297 std::string T, int64_t Default)
298 : SimpleArgument(Arg, Attr, T), Default(Default) {}
300 void writeAccessors(raw_ostream &OS) const override {
301 SimpleArgument::writeAccessors(OS);
303 OS << "\n\n static const " << getType() << " Default" << getUpperName()
304 << " = " << Default << ";";
308 class StringArgument : public Argument {
310 StringArgument(const Record &Arg, StringRef Attr)
311 : Argument(Arg, Attr)
314 void writeAccessors(raw_ostream &OS) const override {
315 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
316 OS << " return llvm::StringRef(" << getLowerName() << ", "
317 << getLowerName() << "Length);\n";
319 OS << " unsigned get" << getUpperName() << "Length() const {\n";
320 OS << " return " << getLowerName() << "Length;\n";
322 OS << " void set" << getUpperName()
323 << "(ASTContext &C, llvm::StringRef S) {\n";
324 OS << " " << getLowerName() << "Length = S.size();\n";
325 OS << " this->" << getLowerName() << " = new (C, 1) char ["
326 << getLowerName() << "Length];\n";
327 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
328 << getLowerName() << "Length);\n";
331 void writeCloneArgs(raw_ostream &OS) const override {
332 OS << "get" << getUpperName() << "()";
334 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
335 OS << "A->get" << getUpperName() << "()";
337 void writeCtorBody(raw_ostream &OS) const override {
338 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
339 << ".data(), " << getLowerName() << "Length);";
341 void writeCtorInitializers(raw_ostream &OS) const override {
342 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
343 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
346 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
347 OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
349 void writeCtorParameters(raw_ostream &OS) const override {
350 OS << "llvm::StringRef " << getUpperName();
352 void writeDeclarations(raw_ostream &OS) const override {
353 OS << "unsigned " << getLowerName() << "Length;\n";
354 OS << "char *" << getLowerName() << ";";
356 void writePCHReadDecls(raw_ostream &OS) const override {
357 OS << " std::string " << getLowerName()
358 << "= ReadString(Record, Idx);\n";
360 void writePCHReadArgs(raw_ostream &OS) const override {
361 OS << getLowerName();
363 void writePCHWrite(raw_ostream &OS) const override {
364 OS << " AddString(SA->get" << getUpperName() << "(), Record);\n";
366 void writeValue(raw_ostream &OS) const override {
367 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
369 void writeDump(raw_ostream &OS) const override {
370 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
371 << "() << \"\\\"\";\n";
375 class AlignedArgument : public Argument {
377 AlignedArgument(const Record &Arg, StringRef Attr)
378 : Argument(Arg, Attr)
381 void writeAccessors(raw_ostream &OS) const override {
382 OS << " bool is" << getUpperName() << "Dependent() const;\n";
384 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
386 OS << " bool is" << getUpperName() << "Expr() const {\n";
387 OS << " return is" << getLowerName() << "Expr;\n";
390 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
391 OS << " assert(is" << getLowerName() << "Expr);\n";
392 OS << " return " << getLowerName() << "Expr;\n";
395 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
396 OS << " assert(!is" << getLowerName() << "Expr);\n";
397 OS << " return " << getLowerName() << "Type;\n";
400 void writeAccessorDefinitions(raw_ostream &OS) const override {
401 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
402 << "Dependent() const {\n";
403 OS << " if (is" << getLowerName() << "Expr)\n";
404 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
405 << "Expr->isValueDependent() || " << getLowerName()
406 << "Expr->isTypeDependent());\n";
408 OS << " return " << getLowerName()
409 << "Type->getType()->isDependentType();\n";
412 // FIXME: Do not do the calculation here
413 // FIXME: Handle types correctly
414 // A null pointer means maximum alignment
415 // FIXME: Load the platform-specific maximum alignment, rather than
417 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
418 << "(ASTContext &Ctx) const {\n";
419 OS << " assert(!is" << getUpperName() << "Dependent());\n";
420 OS << " if (is" << getLowerName() << "Expr)\n";
421 OS << " return (" << getLowerName() << "Expr ? " << getLowerName()
422 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue() : 16)"
423 << "* Ctx.getCharWidth();\n";
425 OS << " return 0; // FIXME\n";
428 void writeCloneArgs(raw_ostream &OS) const override {
429 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
430 << "Expr ? static_cast<void*>(" << getLowerName()
431 << "Expr) : " << getLowerName()
434 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
435 // FIXME: move the definition in Sema::InstantiateAttrs to here.
436 // In the meantime, aligned attributes are cloned.
438 void writeCtorBody(raw_ostream &OS) const override {
439 OS << " if (is" << getLowerName() << "Expr)\n";
440 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
441 << getUpperName() << ");\n";
443 OS << " " << getLowerName()
444 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
447 void writeCtorInitializers(raw_ostream &OS) const override {
448 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
450 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
451 OS << "is" << getLowerName() << "Expr(false)";
453 void writeCtorParameters(raw_ostream &OS) const override {
454 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
456 void writeImplicitCtorArgs(raw_ostream &OS) const override {
457 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
459 void writeDeclarations(raw_ostream &OS) const override {
460 OS << "bool is" << getLowerName() << "Expr;\n";
462 OS << "Expr *" << getLowerName() << "Expr;\n";
463 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
466 void writePCHReadArgs(raw_ostream &OS) const override {
467 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
469 void writePCHReadDecls(raw_ostream &OS) const override {
470 OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
471 OS << " void *" << getLowerName() << "Ptr;\n";
472 OS << " if (is" << getLowerName() << "Expr)\n";
473 OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
475 OS << " " << getLowerName()
476 << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
478 void writePCHWrite(raw_ostream &OS) const override {
479 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
480 OS << " if (SA->is" << getUpperName() << "Expr())\n";
481 OS << " AddStmt(SA->get" << getUpperName() << "Expr());\n";
483 OS << " AddTypeSourceInfo(SA->get" << getUpperName()
484 << "Type(), Record);\n";
486 void writeValue(raw_ostream &OS) const override {
488 OS << " assert(is" << getLowerName() << "Expr && " << getLowerName()
489 << "Expr != nullptr);\n";
490 OS << " " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n";
493 void writeDump(raw_ostream &OS) const override {
495 void writeDumpChildren(raw_ostream &OS) const override {
496 OS << " if (SA->is" << getUpperName() << "Expr()) {\n";
497 OS << " lastChild();\n";
498 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
500 OS << " dumpType(SA->get" << getUpperName()
501 << "Type()->getType());\n";
503 void writeHasChildren(raw_ostream &OS) const override {
504 OS << "SA->is" << getUpperName() << "Expr()";
508 class VariadicArgument : public Argument {
509 std::string Type, ArgName, ArgSizeName, RangeName;
512 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
513 : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
514 ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}
516 std::string getType() const { return Type; }
518 void writeAccessors(raw_ostream &OS) const override {
519 std::string IteratorType = getLowerName().str() + "_iterator";
520 std::string BeginFn = getLowerName().str() + "_begin()";
521 std::string EndFn = getLowerName().str() + "_end()";
523 OS << " typedef " << Type << "* " << IteratorType << ";\n";
524 OS << " " << IteratorType << " " << BeginFn << " const {"
525 << " return " << ArgName << "; }\n";
526 OS << " " << IteratorType << " " << EndFn << " const {"
527 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
528 OS << " unsigned " << getLowerName() << "_size() const {"
529 << " return " << ArgSizeName << "; }\n";
530 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
531 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
534 void writeCloneArgs(raw_ostream &OS) const override {
535 OS << ArgName << ", " << ArgSizeName;
537 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
538 // This isn't elegant, but we have to go through public methods...
539 OS << "A->" << getLowerName() << "_begin(), "
540 << "A->" << getLowerName() << "_size()";
542 void writeCtorBody(raw_ostream &OS) const override {
543 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
544 << " + " << ArgSizeName << ", " << ArgName << ");";
546 void writeCtorInitializers(raw_ostream &OS) const override {
547 OS << ArgSizeName << "(" << getUpperName() << "Size), "
548 << ArgName << "(new (Ctx, 16) " << getType() << "["
549 << ArgSizeName << "])";
551 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
552 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
554 void writeCtorParameters(raw_ostream &OS) const override {
555 OS << getType() << " *" << getUpperName() << ", unsigned "
556 << getUpperName() << "Size";
558 void writeImplicitCtorArgs(raw_ostream &OS) const override {
559 OS << getUpperName() << ", " << getUpperName() << "Size";
561 void writeDeclarations(raw_ostream &OS) const override {
562 OS << " unsigned " << ArgSizeName << ";\n";
563 OS << " " << getType() << " *" << ArgName << ";";
565 void writePCHReadDecls(raw_ostream &OS) const override {
566 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
567 OS << " SmallVector<" << Type << ", 4> " << getLowerName()
569 OS << " " << getLowerName() << ".reserve(" << getLowerName()
571 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
573 std::string read = ReadPCHRecord(Type);
574 OS << " " << getLowerName() << ".push_back(" << read << ");\n";
576 void writePCHReadArgs(raw_ostream &OS) const override {
577 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
579 void writePCHWrite(raw_ostream &OS) const override {
580 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
581 OS << " for (auto &Val : SA->" << RangeName << "())\n";
582 OS << " " << WritePCHRecord(Type, "Val");
584 void writeValue(raw_ostream &OS) const override {
586 OS << " bool isFirst = true;\n"
587 << " for (const auto &Val : " << RangeName << "()) {\n"
588 << " if (isFirst) isFirst = false;\n"
589 << " else OS << \", \";\n"
594 void writeDump(raw_ostream &OS) const override {
595 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
596 OS << " OS << \" \" << Val;\n";
600 // Unique the enums, but maintain the original declaration ordering.
601 std::vector<std::string>
602 uniqueEnumsInOrder(const std::vector<std::string> &enums) {
603 std::vector<std::string> uniques;
604 std::set<std::string> unique_set(enums.begin(), enums.end());
605 for (const auto &i : enums) {
606 std::set<std::string>::iterator set_i = unique_set.find(i);
607 if (set_i != unique_set.end()) {
608 uniques.push_back(i);
609 unique_set.erase(set_i);
615 class EnumArgument : public Argument {
617 std::vector<std::string> values, enums, uniques;
619 EnumArgument(const Record &Arg, StringRef Attr)
620 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
621 values(Arg.getValueAsListOfStrings("Values")),
622 enums(Arg.getValueAsListOfStrings("Enums")),
623 uniques(uniqueEnumsInOrder(enums))
625 // FIXME: Emit a proper error
626 assert(!uniques.empty());
629 bool isEnumArg() const override { return true; }
631 void writeAccessors(raw_ostream &OS) const override {
632 OS << " " << type << " get" << getUpperName() << "() const {\n";
633 OS << " return " << getLowerName() << ";\n";
636 void writeCloneArgs(raw_ostream &OS) const override {
637 OS << getLowerName();
639 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
640 OS << "A->get" << getUpperName() << "()";
642 void writeCtorInitializers(raw_ostream &OS) const override {
643 OS << getLowerName() << "(" << getUpperName() << ")";
645 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
646 OS << getLowerName() << "(" << type << "(0))";
648 void writeCtorParameters(raw_ostream &OS) const override {
649 OS << type << " " << getUpperName();
651 void writeDeclarations(raw_ostream &OS) const override {
652 std::vector<std::string>::const_iterator i = uniques.begin(),
654 // The last one needs to not have a comma.
658 OS << " enum " << type << " {\n";
660 OS << " " << *i << ",\n";
661 OS << " " << *e << "\n";
664 OS << " " << type << " " << getLowerName() << ";";
666 void writePCHReadDecls(raw_ostream &OS) const override {
667 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
668 << "(static_cast<" << getAttrName() << "Attr::" << type
669 << ">(Record[Idx++]));\n";
671 void writePCHReadArgs(raw_ostream &OS) const override {
672 OS << getLowerName();
674 void writePCHWrite(raw_ostream &OS) const override {
675 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
677 void writeValue(raw_ostream &OS) const override {
678 OS << "\" << get" << getUpperName() << "() << \"";
680 void writeDump(raw_ostream &OS) const override {
681 OS << " switch(SA->get" << getUpperName() << "()) {\n";
682 for (const auto &I : uniques) {
683 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
684 OS << " OS << \" " << I << "\";\n";
690 void writeConversion(raw_ostream &OS) const {
691 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
692 OS << type << " &Out) {\n";
693 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
694 OS << type << ">>(Val)\n";
695 for (size_t I = 0; I < enums.size(); ++I) {
696 OS << " .Case(\"" << values[I] << "\", ";
697 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
699 OS << " .Default(Optional<" << type << ">());\n";
701 OS << " Out = *R;\n return true;\n }\n";
702 OS << " return false;\n";
707 class VariadicEnumArgument: public VariadicArgument {
708 std::string type, QualifiedTypeName;
709 std::vector<std::string> values, enums, uniques;
711 VariadicEnumArgument(const Record &Arg, StringRef Attr)
712 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
713 type(Arg.getValueAsString("Type")),
714 values(Arg.getValueAsListOfStrings("Values")),
715 enums(Arg.getValueAsListOfStrings("Enums")),
716 uniques(uniqueEnumsInOrder(enums))
718 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
720 // FIXME: Emit a proper error
721 assert(!uniques.empty());
724 bool isVariadicEnumArg() const override { return true; }
726 void writeDeclarations(raw_ostream &OS) const override {
727 std::vector<std::string>::const_iterator i = uniques.begin(),
729 // The last one needs to not have a comma.
733 OS << " enum " << type << " {\n";
735 OS << " " << *i << ",\n";
736 OS << " " << *e << "\n";
740 VariadicArgument::writeDeclarations(OS);
742 void writeDump(raw_ostream &OS) const override {
743 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
744 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
745 << getLowerName() << "_end(); I != E; ++I) {\n";
746 OS << " switch(*I) {\n";
747 for (const auto &UI : uniques) {
748 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
749 OS << " OS << \" " << UI << "\";\n";
755 void writePCHReadDecls(raw_ostream &OS) const override {
756 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
757 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
759 OS << " " << getLowerName() << ".reserve(" << getLowerName()
761 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
762 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
763 << QualifiedTypeName << ">(Record[Idx++]));\n";
765 void writePCHWrite(raw_ostream &OS) const override {
766 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
767 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
768 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
769 << getLowerName() << "_end(); i != e; ++i)\n";
770 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
772 void writeConversion(raw_ostream &OS) const {
773 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
774 OS << type << " &Out) {\n";
775 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
776 OS << type << ">>(Val)\n";
777 for (size_t I = 0; I < enums.size(); ++I) {
778 OS << " .Case(\"" << values[I] << "\", ";
779 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
781 OS << " .Default(Optional<" << type << ">());\n";
783 OS << " Out = *R;\n return true;\n }\n";
784 OS << " return false;\n";
789 class VersionArgument : public Argument {
791 VersionArgument(const Record &Arg, StringRef Attr)
792 : Argument(Arg, Attr)
795 void writeAccessors(raw_ostream &OS) const override {
796 OS << " VersionTuple get" << getUpperName() << "() const {\n";
797 OS << " return " << getLowerName() << ";\n";
799 OS << " void set" << getUpperName()
800 << "(ASTContext &C, VersionTuple V) {\n";
801 OS << " " << getLowerName() << " = V;\n";
804 void writeCloneArgs(raw_ostream &OS) const override {
805 OS << "get" << getUpperName() << "()";
807 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
808 OS << "A->get" << getUpperName() << "()";
810 void writeCtorInitializers(raw_ostream &OS) const override {
811 OS << getLowerName() << "(" << getUpperName() << ")";
813 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
814 OS << getLowerName() << "()";
816 void writeCtorParameters(raw_ostream &OS) const override {
817 OS << "VersionTuple " << getUpperName();
819 void writeDeclarations(raw_ostream &OS) const override {
820 OS << "VersionTuple " << getLowerName() << ";\n";
822 void writePCHReadDecls(raw_ostream &OS) const override {
823 OS << " VersionTuple " << getLowerName()
824 << "= ReadVersionTuple(Record, Idx);\n";
826 void writePCHReadArgs(raw_ostream &OS) const override {
827 OS << getLowerName();
829 void writePCHWrite(raw_ostream &OS) const override {
830 OS << " AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
832 void writeValue(raw_ostream &OS) const override {
833 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
835 void writeDump(raw_ostream &OS) const override {
836 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
840 class ExprArgument : public SimpleArgument {
842 ExprArgument(const Record &Arg, StringRef Attr)
843 : SimpleArgument(Arg, Attr, "Expr *")
846 void writeASTVisitorTraversal(raw_ostream &OS) const override {
848 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
849 OS << " return false;\n";
852 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
853 OS << "tempInst" << getUpperName();
856 void writeTemplateInstantiation(raw_ostream &OS) const override {
857 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
859 OS << " EnterExpressionEvaluationContext "
860 << "Unevaluated(S, Sema::Unevaluated);\n";
861 OS << " ExprResult " << "Result = S.SubstExpr("
862 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
863 OS << " tempInst" << getUpperName() << " = "
864 << "Result.getAs<Expr>();\n";
868 void writeDump(raw_ostream &OS) const override {}
870 void writeDumpChildren(raw_ostream &OS) const override {
871 OS << " lastChild();\n";
872 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
874 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
877 class VariadicExprArgument : public VariadicArgument {
879 VariadicExprArgument(const Record &Arg, StringRef Attr)
880 : VariadicArgument(Arg, Attr, "Expr *")
883 void writeASTVisitorTraversal(raw_ostream &OS) const override {
885 OS << " " << getType() << " *I = A->" << getLowerName()
887 OS << " " << getType() << " *E = A->" << getLowerName()
889 OS << " for (; I != E; ++I) {\n";
890 OS << " if (!getDerived().TraverseStmt(*I))\n";
891 OS << " return false;\n";
896 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
897 OS << "tempInst" << getUpperName() << ", "
898 << "A->" << getLowerName() << "_size()";
901 void writeTemplateInstantiation(raw_ostream &OS) const override {
902 OS << " " << getType() << " *tempInst" << getUpperName()
903 << " = new (C, 16) " << getType()
904 << "[A->" << getLowerName() << "_size()];\n";
906 OS << " EnterExpressionEvaluationContext "
907 << "Unevaluated(S, Sema::Unevaluated);\n";
908 OS << " " << getType() << " *TI = tempInst" << getUpperName()
910 OS << " " << getType() << " *I = A->" << getLowerName()
912 OS << " " << getType() << " *E = A->" << getLowerName()
914 OS << " for (; I != E; ++I, ++TI) {\n";
915 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
916 OS << " *TI = Result.getAs<Expr>();\n";
921 void writeDump(raw_ostream &OS) const override {}
923 void writeDumpChildren(raw_ostream &OS) const override {
924 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
925 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
926 << getLowerName() << "_end(); I != E; ++I) {\n";
927 OS << " if (I + 1 == E)\n";
928 OS << " lastChild();\n";
929 OS << " dumpStmt(*I);\n";
933 void writeHasChildren(raw_ostream &OS) const override {
934 OS << "SA->" << getLowerName() << "_begin() != "
935 << "SA->" << getLowerName() << "_end()";
939 class TypeArgument : public SimpleArgument {
941 TypeArgument(const Record &Arg, StringRef Attr)
942 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
945 void writeAccessors(raw_ostream &OS) const override {
946 OS << " QualType get" << getUpperName() << "() const {\n";
947 OS << " return " << getLowerName() << "->getType();\n";
949 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
950 OS << " return " << getLowerName() << ";\n";
953 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
954 OS << "A->get" << getUpperName() << "Loc()";
956 void writePCHWrite(raw_ostream &OS) const override {
957 OS << " " << WritePCHRecord(
958 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
963 static std::unique_ptr<Argument>
964 createArgument(const Record &Arg, StringRef Attr,
965 const Record *Search = nullptr) {
969 Argument *Ptr = nullptr;
970 llvm::StringRef ArgName = Search->getName();
972 if (ArgName == "AlignedArgument") Ptr = new AlignedArgument(Arg, Attr);
973 else if (ArgName == "EnumArgument") Ptr = new EnumArgument(Arg, Attr);
974 else if (ArgName == "ExprArgument") Ptr = new ExprArgument(Arg, Attr);
975 else if (ArgName == "FunctionArgument")
976 Ptr = new SimpleArgument(Arg, Attr, "FunctionDecl *");
977 else if (ArgName == "IdentifierArgument")
978 Ptr = new SimpleArgument(Arg, Attr, "IdentifierInfo *");
979 else if (ArgName == "DefaultBoolArgument")
980 Ptr = new DefaultSimpleArgument(Arg, Attr, "bool",
981 Arg.getValueAsBit("Default"));
982 else if (ArgName == "BoolArgument") Ptr = new SimpleArgument(Arg, Attr,
984 else if (ArgName == "DefaultIntArgument")
985 Ptr = new DefaultSimpleArgument(Arg, Attr, "int",
986 Arg.getValueAsInt("Default"));
987 else if (ArgName == "IntArgument") Ptr = new SimpleArgument(Arg, Attr, "int");
988 else if (ArgName == "StringArgument") Ptr = new StringArgument(Arg, Attr);
989 else if (ArgName == "TypeArgument") Ptr = new TypeArgument(Arg, Attr);
990 else if (ArgName == "UnsignedArgument")
991 Ptr = new SimpleArgument(Arg, Attr, "unsigned");
992 else if (ArgName == "VariadicUnsignedArgument")
993 Ptr = new VariadicArgument(Arg, Attr, "unsigned");
994 else if (ArgName == "VariadicEnumArgument")
995 Ptr = new VariadicEnumArgument(Arg, Attr);
996 else if (ArgName == "VariadicExprArgument")
997 Ptr = new VariadicExprArgument(Arg, Attr);
998 else if (ArgName == "VersionArgument")
999 Ptr = new VersionArgument(Arg, Attr);
1002 // Search in reverse order so that the most-derived type is handled first.
1003 std::vector<Record*> Bases = Search->getSuperClasses();
1004 for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
1005 Ptr = createArgument(Arg, Attr, Base).release();
1011 if (Ptr && Arg.getValueAsBit("Optional"))
1012 Ptr->setOptional(true);
1014 return std::unique_ptr<Argument>(Ptr);
1017 static void writeAvailabilityValue(raw_ostream &OS) {
1018 OS << "\" << getPlatform()->getName();\n"
1019 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1020 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1021 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1022 << " if (getUnavailable()) OS << \", unavailable\";\n"
1026 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1027 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1029 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1030 if (Spellings.empty()) {
1031 OS << " return \"(No spelling)\";\n}\n\n";
1035 OS << " switch (SpellingListIndex) {\n"
1037 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1038 " return \"(No spelling)\";\n";
1040 for (unsigned I = 0; I < Spellings.size(); ++I)
1041 OS << " case " << I << ":\n"
1042 " return \"" << Spellings[I].name() << "\";\n";
1043 // End of the switch statement.
1045 // End of the getSpelling function.
1050 writePrettyPrintFunction(Record &R,
1051 const std::vector<std::unique_ptr<Argument>> &Args,
1053 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1055 OS << "void " << R.getName() << "Attr::printPretty("
1056 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1058 if (Spellings.empty()) {
1064 " switch (SpellingListIndex) {\n"
1066 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1069 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1070 llvm::SmallString<16> Prefix;
1071 llvm::SmallString<8> Suffix;
1072 // The actual spelling of the name and namespace (if applicable)
1073 // of an attribute without considering prefix and suffix.
1074 llvm::SmallString<64> Spelling;
1075 std::string Name = Spellings[I].name();
1076 std::string Variety = Spellings[I].variety();
1078 if (Variety == "GNU") {
1079 Prefix = " __attribute__((";
1081 } else if (Variety == "CXX11") {
1084 std::string Namespace = Spellings[I].nameSpace();
1085 if (!Namespace.empty()) {
1086 Spelling += Namespace;
1089 } else if (Variety == "Declspec") {
1090 Prefix = " __declspec(";
1092 } else if (Variety == "Keyword") {
1095 } else if (Variety == "Pragma") {
1096 Prefix = "#pragma ";
1098 std::string Namespace = Spellings[I].nameSpace();
1099 if (!Namespace.empty()) {
1100 Spelling += Namespace;
1104 llvm_unreachable("Unknown attribute syntax variety!");
1110 " case " << I << " : {\n"
1111 " OS << \"" + Prefix.str() + Spelling.str();
1113 if (Variety == "Pragma") {
1115 OS << " printPrettyPragma(OS, Policy);\n";
1123 if (Spelling == "availability") {
1124 writeAvailabilityValue(OS);
1126 for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
1127 if (I != Args.begin()) OS << ", ";
1128 (*I)->writeValue(OS);
1134 OS << Suffix.str() + "\";\n";
1141 // End of the switch statement.
1143 // End of the print function.
1147 /// \brief Return the index of a spelling in a spelling list.
1149 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1150 const FlattenedSpelling &Spelling) {
1151 assert(SpellingList.size() && "Spelling list is empty!");
1153 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1154 const FlattenedSpelling &S = SpellingList[Index];
1155 if (S.variety() != Spelling.variety())
1157 if (S.nameSpace() != Spelling.nameSpace())
1159 if (S.name() != Spelling.name())
1165 llvm_unreachable("Unknown spelling!");
1168 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1169 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1170 for (const auto *Accessor : Accessors) {
1171 std::string Name = Accessor->getValueAsString("Name");
1172 std::vector<FlattenedSpelling> Spellings =
1173 GetFlattenedSpellings(*Accessor);
1174 std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1175 assert(SpellingList.size() &&
1176 "Attribute with empty spelling list can't have accessors!");
1178 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1179 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1180 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1181 if (Index != Spellings.size() -1)
1182 OS << " ||\n SpellingListIndex == ";
1190 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1191 assert(!Spellings.empty() && "An empty list of spellings was provided");
1192 std::string FirstName = NormalizeNameForSpellingComparison(
1193 Spellings.front().name());
1194 for (const auto &Spelling :
1195 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1196 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1197 if (Name != FirstName)
1203 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1205 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1206 SemanticSpellingMap &Map) {
1207 // The enumerants are automatically generated based on the variety,
1208 // namespace (if present) and name for each attribute spelling. However,
1209 // care is taken to avoid trampling on the reserved namespace due to
1211 std::string Ret(" enum Spelling {\n");
1212 std::set<std::string> Uniques;
1214 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1215 const FlattenedSpelling &S = *I;
1216 std::string Variety = S.variety();
1217 std::string Spelling = S.name();
1218 std::string Namespace = S.nameSpace();
1219 std::string EnumName = "";
1221 EnumName += (Variety + "_");
1222 if (!Namespace.empty())
1223 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1225 EnumName += NormalizeNameForSpellingComparison(Spelling);
1227 // Even if the name is not unique, this spelling index corresponds to a
1228 // particular enumerant name that we've calculated.
1229 Map[Idx] = EnumName;
1231 // Since we have been stripping underscores to avoid trampling on the
1232 // reserved namespace, we may have inadvertently created duplicate
1233 // enumerant names. These duplicates are not considered part of the
1234 // semantic spelling, and can be elided.
1235 if (Uniques.find(EnumName) != Uniques.end())
1238 Uniques.insert(EnumName);
1239 if (I != Spellings.begin())
1241 Ret += " " + EnumName;
1247 void WriteSemanticSpellingSwitch(const std::string &VarName,
1248 const SemanticSpellingMap &Map,
1250 OS << " switch (" << VarName << ") {\n default: "
1251 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1252 for (const auto &I : Map)
1253 OS << " case " << I.first << ": return " << I.second << ";\n";
1257 // Emits the LateParsed property for attributes.
1258 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1259 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1260 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1262 for (const auto *Attr : Attrs) {
1263 bool LateParsed = Attr->getValueAsBit("LateParsed");
1266 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1268 // FIXME: Handle non-GNU attributes
1269 for (const auto &I : Spellings) {
1270 if (I.variety() != "GNU")
1272 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1276 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1279 /// \brief Emits the first-argument-is-type property for attributes.
1280 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1281 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1282 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1284 for (const auto *Attr : Attrs) {
1285 // Determine whether the first argument is a type.
1286 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1290 if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
1293 // All these spellings take a single type argument.
1294 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1295 std::set<std::string> Emitted;
1296 for (const auto &S : Spellings) {
1297 if (Emitted.insert(S.name()).second)
1298 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1301 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1304 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1306 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1307 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1308 ParsedAttrMap Attrs = getParsedAttrList(Records);
1309 for (const auto &I : Attrs) {
1310 const Record &Attr = *I.second;
1312 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1315 // All these spellings take are parsed unevaluated.
1316 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1317 std::set<std::string> Emitted;
1318 for (const auto &S : Spellings) {
1319 if (Emitted.insert(S.name()).second)
1320 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1323 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1326 static bool isIdentifierArgument(Record *Arg) {
1327 return !Arg->getSuperClasses().empty() &&
1328 llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
1329 .Case("IdentifierArgument", true)
1330 .Case("EnumArgument", true)
1334 // Emits the first-argument-is-identifier property for attributes.
1335 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1336 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1337 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1339 for (const auto *Attr : Attrs) {
1340 // Determine whether the first argument is an identifier.
1341 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1342 if (Args.empty() || !isIdentifierArgument(Args[0]))
1345 // All these spellings take an identifier argument.
1346 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1347 std::set<std::string> Emitted;
1348 for (const auto &S : Spellings) {
1349 if (Emitted.insert(S.name()).second)
1350 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1353 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1358 // Emits the class definitions for attributes.
1359 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1360 emitSourceFileHeader("Attribute classes' definitions", OS);
1362 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1363 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1365 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1367 for (const auto *Attr : Attrs) {
1368 const Record &R = *Attr;
1370 // FIXME: Currently, documentation is generated as-needed due to the fact
1371 // that there is no way to allow a generated project "reach into" the docs
1372 // directory (for instance, it may be an out-of-tree build). However, we want
1373 // to ensure that every attribute has a Documentation field, and produce an
1374 // error if it has been neglected. Otherwise, the on-demand generation which
1375 // happens server-side will fail. This code is ensuring that functionality,
1376 // even though this Emitter doesn't technically need the documentation.
1377 // When attribute documentation can be generated as part of the build
1378 // itself, this code can be removed.
1379 (void)R.getValueAsListOfDefs("Documentation");
1381 if (!R.getValueAsBit("ASTNode"))
1384 const std::vector<Record *> Supers = R.getSuperClasses();
1385 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1386 std::string SuperName;
1387 for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
1388 const Record &R = *Super;
1389 if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
1390 SuperName = R.getName();
1393 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1395 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1396 std::vector<std::unique_ptr<Argument>> Args;
1397 Args.reserve(ArgRecords.size());
1399 for (const auto *ArgRecord : ArgRecords) {
1400 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1401 Args.back()->writeDeclarations(OS);
1405 OS << "\npublic:\n";
1407 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1409 // If there are zero or one spellings, all spelling-related functionality
1410 // can be elided. If all of the spellings share the same name, the spelling
1411 // functionality can also be elided.
1412 bool ElideSpelling = (Spellings.size() <= 1) ||
1413 SpellingNamesAreCommon(Spellings);
1415 // This maps spelling index values to semantic Spelling enumerants.
1416 SemanticSpellingMap SemanticToSyntacticMap;
1419 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1421 OS << " static " << R.getName() << "Attr *CreateImplicit(";
1422 OS << "ASTContext &Ctx";
1424 OS << ", Spelling S";
1425 for (auto const &ai : Args) {
1427 ai->writeCtorParameters(OS);
1429 OS << ", SourceRange Loc = SourceRange()";
1431 OS << " " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
1432 OS << "Attr(Loc, Ctx, ";
1433 for (auto const &ai : Args) {
1434 ai->writeImplicitCtorArgs(OS);
1437 OS << (ElideSpelling ? "0" : "S") << ");\n";
1438 OS << " A->setImplicit(true);\n";
1439 OS << " return A;\n }\n\n";
1441 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1443 bool HasOpt = false;
1444 for (auto const &ai : Args) {
1446 ai->writeCtorParameters(OS);
1448 if (ai->isOptional())
1453 OS << "unsigned SI\n";
1456 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
1458 for (auto const &ai : Args) {
1460 ai->writeCtorInitializers(OS);
1466 for (auto const &ai : Args) {
1467 ai->writeCtorBody(OS);
1472 // If there are optional arguments, write out a constructor that elides the
1473 // optional arguments as well.
1475 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1476 for (auto const &ai : Args) {
1477 if (!ai->isOptional()) {
1479 ai->writeCtorParameters(OS);
1485 OS << "unsigned SI\n";
1488 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI)\n";
1490 for (auto const &ai : Args) {
1492 ai->writeCtorDefaultInitializers(OS);
1498 for (auto const &ai : Args) {
1499 if (!ai->isOptional()) {
1500 ai->writeCtorBody(OS);
1507 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const override;\n";
1508 OS << " void printPretty(raw_ostream &OS,\n"
1509 << " const PrintingPolicy &Policy) const override;\n";
1510 OS << " const char *getSpelling() const override;\n";
1512 if (!ElideSpelling) {
1513 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1514 OS << " Spelling getSemanticSpelling() const {\n";
1515 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1520 writeAttrAccessorDefinition(R, OS);
1522 for (auto const &ai : Args) {
1523 ai->writeAccessors(OS);
1526 if (ai->isEnumArg())
1527 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1528 else if (ai->isVariadicEnumArg())
1529 static_cast<const VariadicEnumArgument *>(ai.get())
1530 ->writeConversion(OS);
1533 OS << R.getValueAsString("AdditionalMembers");
1536 OS << " static bool classof(const Attr *A) { return A->getKind() == "
1537 << "attr::" << R.getName() << "; }\n";
1539 bool LateParsed = R.getValueAsBit("LateParsed");
1540 OS << " bool isLateParsed() const override { return "
1541 << LateParsed << "; }\n";
1543 if (R.getValueAsBit("DuplicatesAllowedWhileMerging"))
1544 OS << " bool duplicatesAllowed() const override { return true; }\n\n";
1552 // Emits the class method definitions for attributes.
1553 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1554 emitSourceFileHeader("Attribute classes' member function definitions", OS);
1556 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1558 for (auto *Attr : Attrs) {
1561 if (!R.getValueAsBit("ASTNode"))
1564 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1565 std::vector<std::unique_ptr<Argument>> Args;
1566 for (const auto *Arg : ArgRecords)
1567 Args.emplace_back(createArgument(*Arg, R.getName()));
1569 for (auto const &ai : Args)
1570 ai->writeAccessorDefinitions(OS);
1572 OS << R.getName() << "Attr *" << R.getName()
1573 << "Attr::clone(ASTContext &C) const {\n";
1574 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
1575 for (auto const &ai : Args) {
1577 ai->writeCloneArgs(OS);
1579 OS << ", getSpellingListIndex());\n";
1580 OS << " A->Inherited = Inherited;\n";
1581 OS << " A->IsPackExpansion = IsPackExpansion;\n";
1582 OS << " A->Implicit = Implicit;\n";
1583 OS << " return A;\n}\n\n";
1585 writePrettyPrintFunction(R, Args, OS);
1586 writeGetSpellingFunction(R, OS);
1590 } // end namespace clang
1592 static void EmitAttrList(raw_ostream &OS, StringRef Class,
1593 const std::vector<Record*> &AttrList) {
1594 std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();
1597 // Move the end iterator back to emit the last attribute.
1598 for(--e; i != e; ++i) {
1599 if (!(*i)->getValueAsBit("ASTNode"))
1602 OS << Class << "(" << (*i)->getName() << ")\n";
1605 OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
1611 // Emits the enumeration list for attributes.
1612 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
1613 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
1615 OS << "#ifndef LAST_ATTR\n";
1616 OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
1619 OS << "#ifndef INHERITABLE_ATTR\n";
1620 OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
1623 OS << "#ifndef LAST_INHERITABLE_ATTR\n";
1624 OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
1627 OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
1628 OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
1631 OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
1632 OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
1633 " INHERITABLE_PARAM_ATTR(NAME)\n";
1636 Record *InhClass = Records.getClass("InheritableAttr");
1637 Record *InhParamClass = Records.getClass("InheritableParamAttr");
1638 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1639 NonInhAttrs, InhAttrs, InhParamAttrs;
1640 for (auto *Attr : Attrs) {
1641 if (!Attr->getValueAsBit("ASTNode"))
1644 if (Attr->isSubClassOf(InhParamClass))
1645 InhParamAttrs.push_back(Attr);
1646 else if (Attr->isSubClassOf(InhClass))
1647 InhAttrs.push_back(Attr);
1649 NonInhAttrs.push_back(Attr);
1652 EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
1653 EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
1654 EmitAttrList(OS, "ATTR", NonInhAttrs);
1656 OS << "#undef LAST_ATTR\n";
1657 OS << "#undef INHERITABLE_ATTR\n";
1658 OS << "#undef LAST_INHERITABLE_ATTR\n";
1659 OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
1660 OS << "#undef ATTR\n";
1663 // Emits the code to read an attribute from a precompiled header.
1664 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
1665 emitSourceFileHeader("Attribute deserialization code", OS);
1667 Record *InhClass = Records.getClass("InheritableAttr");
1668 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1670 std::vector<std::unique_ptr<Argument>> Args;
1672 OS << " switch (Kind) {\n";
1673 OS << " default:\n";
1674 OS << " llvm_unreachable(\"Unknown attribute!\");\n";
1675 for (const auto *Attr : Attrs) {
1676 const Record &R = *Attr;
1677 if (!R.getValueAsBit("ASTNode"))
1680 OS << " case attr::" << R.getName() << ": {\n";
1681 if (R.isSubClassOf(InhClass))
1682 OS << " bool isInherited = Record[Idx++];\n";
1683 OS << " bool isImplicit = Record[Idx++];\n";
1684 OS << " unsigned Spelling = Record[Idx++];\n";
1685 ArgRecords = R.getValueAsListOfDefs("Args");
1687 for (const auto *Arg : ArgRecords) {
1688 Args.emplace_back(createArgument(*Arg, R.getName()));
1689 Args.back()->writePCHReadDecls(OS);
1691 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
1692 for (auto const &ri : Args) {
1694 ri->writePCHReadArgs(OS);
1696 OS << ", Spelling);\n";
1697 if (R.isSubClassOf(InhClass))
1698 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
1699 OS << " New->setImplicit(isImplicit);\n";
1706 // Emits the code to write an attribute to a precompiled header.
1707 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
1708 emitSourceFileHeader("Attribute serialization code", OS);
1710 Record *InhClass = Records.getClass("InheritableAttr");
1711 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
1713 OS << " switch (A->getKind()) {\n";
1714 OS << " default:\n";
1715 OS << " llvm_unreachable(\"Unknown attribute kind!\");\n";
1717 for (const auto *Attr : Attrs) {
1718 const Record &R = *Attr;
1719 if (!R.getValueAsBit("ASTNode"))
1721 OS << " case attr::" << R.getName() << ": {\n";
1722 Args = R.getValueAsListOfDefs("Args");
1723 if (R.isSubClassOf(InhClass) || !Args.empty())
1724 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
1726 if (R.isSubClassOf(InhClass))
1727 OS << " Record.push_back(SA->isInherited());\n";
1728 OS << " Record.push_back(A->isImplicit());\n";
1729 OS << " Record.push_back(A->getSpellingListIndex());\n";
1731 for (const auto *Arg : Args)
1732 createArgument(*Arg, R.getName())->writePCHWrite(OS);
1739 static void GenerateHasAttrSpellingStringSwitch(
1740 const std::vector<Record *> &Attrs, raw_ostream &OS,
1741 const std::string &Variety = "", const std::string &Scope = "") {
1742 for (const auto *Attr : Attrs) {
1743 // It is assumed that there will be an llvm::Triple object named T within
1744 // scope that can be used to determine whether the attribute exists in
1747 if (Attr->isSubClassOf("TargetSpecificAttr")) {
1748 const Record *R = Attr->getValueAsDef("Target");
1749 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
1752 for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
1753 std::string Part = *AI;
1754 Test += "T.getArch() == llvm::Triple::" + Part;
1760 std::vector<std::string> OSes;
1761 if (!R->isValueUnset("OSes")) {
1763 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
1764 for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
1765 std::string Part = *AI;
1767 Test += "T.getOS() == llvm::Triple::" + Part;
1774 // If this is the C++11 variety, also add in the LangOpts test.
1775 if (Variety == "CXX11")
1776 Test += " && LangOpts.CPlusPlus11";
1777 } else if (Variety == "CXX11")
1778 // C++11 mode should be checked against LangOpts, which is presumed to be
1779 // present in the caller.
1780 Test = "LangOpts.CPlusPlus11";
1784 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1785 for (const auto &S : Spellings)
1786 if (Variety.empty() || (Variety == S.variety() &&
1787 (Scope.empty() || Scope == S.nameSpace())))
1788 OS << " .Case(\"" << S.name() << "\", " << Test << ")\n";
1790 OS << " .Default(false);\n";
1793 // Emits the list of spellings for attributes.
1794 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1795 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
1797 // Separate all of the attributes out into four group: generic, C++11, GNU,
1798 // and declspecs. Then generate a big switch statement for each of them.
1799 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1800 std::vector<Record *> Declspec, GNU, Pragma;
1801 std::map<std::string, std::vector<Record *>> CXX;
1803 // Walk over the list of all attributes, and split them out based on the
1804 // spelling variety.
1805 for (auto *R : Attrs) {
1806 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1807 for (const auto &SI : Spellings) {
1808 std::string Variety = SI.variety();
1809 if (Variety == "GNU")
1811 else if (Variety == "Declspec")
1812 Declspec.push_back(R);
1813 else if (Variety == "CXX11")
1814 CXX[SI.nameSpace()].push_back(R);
1815 else if (Variety == "Pragma")
1816 Pragma.push_back(R);
1820 OS << "switch (Syntax) {\n";
1821 OS << "case AttrSyntax::Generic:\n";
1822 OS << " return llvm::StringSwitch<bool>(Name)\n";
1823 GenerateHasAttrSpellingStringSwitch(Attrs, OS);
1824 OS << "case AttrSyntax::GNU:\n";
1825 OS << " return llvm::StringSwitch<bool>(Name)\n";
1826 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
1827 OS << "case AttrSyntax::Declspec:\n";
1828 OS << " return llvm::StringSwitch<bool>(Name)\n";
1829 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
1830 OS << "case AttrSyntax::Pragma:\n";
1831 OS << " return llvm::StringSwitch<bool>(Name)\n";
1832 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
1833 OS << "case AttrSyntax::CXX: {\n";
1834 // C++11-style attributes are further split out based on the Scope.
1835 for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
1838 if (I != CXX.begin())
1840 if (I->first.empty())
1841 OS << "if (!Scope || Scope->getName() == \"\") {\n";
1843 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
1844 OS << " return llvm::StringSwitch<bool>(Name)\n";
1845 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
1852 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
1853 emitSourceFileHeader("Code to translate different attribute spellings "
1854 "into internal identifiers", OS);
1857 " switch (AttrKind) {\n"
1859 " llvm_unreachable(\"Unknown attribute kind!\");\n"
1862 ParsedAttrMap Attrs = getParsedAttrList(Records);
1863 for (const auto &I : Attrs) {
1864 const Record &R = *I.second;
1865 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1866 OS << " case AT_" << I.first << ": {\n";
1867 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1868 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
1870 << StringSwitch<unsigned>(Spellings[I].variety())
1873 .Case("Declspec", 2)
1877 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
1878 << " return " << I << ";\n";
1886 OS << " return 0;\n";
1889 // Emits code used by RecursiveASTVisitor to visit attributes
1890 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
1891 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
1893 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1895 // Write method declarations for Traverse* methods.
1896 // We emit this here because we only generate methods for attributes that
1897 // are declared as ASTNodes.
1898 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
1899 for (const auto *Attr : Attrs) {
1900 const Record &R = *Attr;
1901 if (!R.getValueAsBit("ASTNode"))
1903 OS << " bool Traverse"
1904 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
1906 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
1907 << " return true; \n"
1910 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
1912 // Write individual Traverse* methods for each attribute class.
1913 for (const auto *Attr : Attrs) {
1914 const Record &R = *Attr;
1915 if (!R.getValueAsBit("ASTNode"))
1918 OS << "template <typename Derived>\n"
1919 << "bool VISITORCLASS<Derived>::Traverse"
1920 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
1921 << " if (!getDerived().VisitAttr(A))\n"
1922 << " return false;\n"
1923 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
1924 << " return false;\n";
1926 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1927 for (const auto *Arg : ArgRecords)
1928 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
1930 OS << " return true;\n";
1934 // Write generic Traverse routine
1935 OS << "template <typename Derived>\n"
1936 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
1938 << " return true;\n"
1940 << " switch (A->getKind()) {\n"
1942 << " return true;\n";
1944 for (const auto *Attr : Attrs) {
1945 const Record &R = *Attr;
1946 if (!R.getValueAsBit("ASTNode"))
1949 OS << " case attr::" << R.getName() << ":\n"
1950 << " return getDerived().Traverse" << R.getName() << "Attr("
1951 << "cast<" << R.getName() << "Attr>(A));\n";
1953 OS << " }\n"; // end case
1954 OS << "}\n"; // end function
1955 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
1958 // Emits code to instantiate dependent attributes on templates.
1959 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
1960 emitSourceFileHeader("Template instantiation code for attributes", OS);
1962 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1964 OS << "namespace clang {\n"
1965 << "namespace sema {\n\n"
1966 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
1968 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
1969 << " switch (At->getKind()) {\n"
1973 for (const auto *Attr : Attrs) {
1974 const Record &R = *Attr;
1975 if (!R.getValueAsBit("ASTNode"))
1978 OS << " case attr::" << R.getName() << ": {\n";
1979 bool ShouldClone = R.getValueAsBit("Clone");
1982 OS << " return NULL;\n";
1987 OS << " const " << R.getName() << "Attr *A = cast<"
1988 << R.getName() << "Attr>(At);\n";
1989 bool TDependent = R.getValueAsBit("TemplateDependent");
1992 OS << " return A->clone(C);\n";
1997 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1998 std::vector<std::unique_ptr<Argument>> Args;
1999 Args.reserve(ArgRecords.size());
2001 for (const auto *ArgRecord : ArgRecords)
2002 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2004 for (auto const &ai : Args)
2005 ai->writeTemplateInstantiation(OS);
2007 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2008 for (auto const &ai : Args) {
2010 ai->writeTemplateInstantiationArgs(OS);
2012 OS << ", A->getSpellingListIndex());\n }\n";
2014 OS << " } // end switch\n"
2015 << " llvm_unreachable(\"Unknown attribute!\");\n"
2018 << "} // end namespace sema\n"
2019 << "} // end namespace clang\n";
2022 // Emits the list of parsed attributes.
2023 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2024 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2026 OS << "#ifndef PARSED_ATTR\n";
2027 OS << "#define PARSED_ATTR(NAME) NAME\n";
2030 ParsedAttrMap Names = getParsedAttrList(Records);
2031 for (const auto &I : Names) {
2032 OS << "PARSED_ATTR(" << I.first << ")\n";
2036 static void emitArgInfo(const Record &R, std::stringstream &OS) {
2037 // This function will count the number of arguments specified for the
2038 // attribute and emit the number of required arguments followed by the
2039 // number of optional arguments.
2040 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
2041 unsigned ArgCount = 0, OptCount = 0;
2042 for (const auto *Arg : Args) {
2043 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
2045 OS << ArgCount << ", " << OptCount;
2048 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
2049 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
2050 OS << "const Decl *) {\n";
2051 OS << " return true;\n";
2055 static std::string CalculateDiagnostic(const Record &S) {
2056 // If the SubjectList object has a custom diagnostic associated with it,
2057 // return that directly.
2058 std::string CustomDiag = S.getValueAsString("CustomDiag");
2059 if (!CustomDiag.empty())
2062 // Given the list of subjects, determine what diagnostic best fits.
2066 ObjCMethod = 1U << 2,
2069 GenericRecord = 1U << 5,
2073 ObjCInterface = 1U << 9,
2075 Namespace = 1U << 11,
2077 CXXMethod = 1U << 13,
2078 ObjCProtocol = 1U << 14
2080 uint32_t SubMask = 0;
2082 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2083 for (const auto *Subject : Subjects) {
2084 const Record &R = *Subject;
2087 if (R.isSubClassOf("SubsetSubject")) {
2088 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2089 // As a fallback, look through the SubsetSubject to see what its base
2090 // type is, and use that. This needs to be updated if SubsetSubjects
2091 // are allowed within other SubsetSubjects.
2092 Name = R.getValueAsDef("Base")->getName();
2096 uint32_t V = StringSwitch<uint32_t>(Name)
2097 .Case("Function", Func)
2099 .Case("ObjCMethod", ObjCMethod)
2100 .Case("ParmVar", Param)
2101 .Case("TypedefName", Type)
2102 .Case("ObjCIvar", ObjCIVar)
2103 .Case("ObjCProperty", ObjCProp)
2104 .Case("Record", GenericRecord)
2105 .Case("ObjCInterface", ObjCInterface)
2106 .Case("ObjCProtocol", ObjCProtocol)
2107 .Case("Block", Block)
2108 .Case("CXXRecord", Class)
2109 .Case("Namespace", Namespace)
2110 .Case("Field", Field)
2111 .Case("CXXMethod", CXXMethod)
2114 // Something wasn't in our mapping, so be helpful and let the developer
2116 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2124 // For the simple cases where there's only a single entry in the mask, we
2125 // don't have to resort to bit fiddling.
2126 case Func: return "ExpectedFunction";
2127 case Var: return "ExpectedVariable";
2128 case Param: return "ExpectedParameter";
2129 case Class: return "ExpectedClass";
2131 // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2132 // but should map to something a bit more accurate at some point.
2133 case ObjCMethod: return "ExpectedMethod";
2134 case Type: return "ExpectedType";
2135 case ObjCInterface: return "ExpectedObjectiveCInterface";
2136 case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2138 // "GenericRecord" means struct, union or class; check the language options
2139 // and if not compiling for C++, strip off the class part. Note that this
2140 // relies on the fact that the context for this declares "Sema &S".
2142 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2143 "ExpectedStructOrUnion)";
2144 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2145 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2147 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2148 case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2149 case Func | Var: return "ExpectedVariableOrFunction";
2151 // If not compiling for C++, the class portion does not apply.
2152 case Func | Var | Class:
2153 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2154 "ExpectedVariableOrFunction)";
2156 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2157 case ObjCProtocol | ObjCInterface:
2158 return "ExpectedObjectiveCInterfaceOrProtocol";
2159 case Field | Var: return "ExpectedFieldOrGlobalVar";
2162 PrintFatalError(S.getLoc(),
2163 "Could not deduce diagnostic argument for Attr subjects");
2168 static std::string GetSubjectWithSuffix(const Record *R) {
2169 std::string B = R->getName();
2170 if (B == "DeclBase")
2174 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2176 std::string FnName = "is" + Subject.getName();
2178 // If this code has already been generated, simply return the previous
2180 static std::set<std::string> CustomSubjectSet;
2181 std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
2182 if (I != CustomSubjectSet.end())
2185 Record *Base = Subject.getValueAsDef("Base");
2187 // Not currently support custom subjects within custom subjects.
2188 if (Base->isSubClassOf("SubsetSubject")) {
2189 PrintFatalError(Subject.getLoc(),
2190 "SubsetSubjects within SubsetSubjects is not supported");
2194 OS << "static bool " << FnName << "(const Decl *D) {\n";
2195 OS << " if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
2196 OS << GetSubjectWithSuffix(Base);
2198 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
2199 OS << " return false;\n";
2202 CustomSubjectSet.insert(FnName);
2206 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2207 // If the attribute does not contain a Subjects definition, then use the
2208 // default appertainsTo logic.
2209 if (Attr.isValueUnset("Subjects"))
2210 return "defaultAppertainsTo";
2212 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2213 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2215 // If the list of subjects is empty, it is assumed that the attribute
2216 // appertains to everything.
2217 if (Subjects.empty())
2218 return "defaultAppertainsTo";
2220 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2222 // Otherwise, generate an appertainsTo check specific to this attribute which
2223 // checks all of the given subjects against the Decl passed in. Return the
2224 // name of that check to the caller.
2225 std::string FnName = "check" + Attr.getName() + "AppertainsTo";
2226 std::stringstream SS;
2227 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2228 SS << "const Decl *D) {\n";
2230 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2231 // If the subject has custom code associated with it, generate a function
2232 // for it. The function cannot be inlined into this check (yet) because it
2233 // requires the subject to be of a specific type, and were that information
2234 // inlined here, it would not support an attribute with multiple custom
2236 if ((*I)->isSubClassOf("SubsetSubject")) {
2237 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2239 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2246 SS << " S.Diag(Attr.getLoc(), diag::";
2247 SS << (Warn ? "warn_attribute_wrong_decl_type" :
2248 "err_attribute_wrong_decl_type");
2250 SS << " << Attr.getName() << ";
2251 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2252 SS << " return false;\n";
2254 SS << " return true;\n";
2261 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2262 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2263 OS << "const AttributeList &) {\n";
2264 OS << " return true;\n";
2268 static std::string GenerateLangOptRequirements(const Record &R,
2270 // If the attribute has an empty or unset list of language requirements,
2271 // return the default handler.
2272 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2273 if (LangOpts.empty())
2274 return "defaultDiagnoseLangOpts";
2276 // Generate the test condition, as well as a unique function name for the
2277 // diagnostic test. The list of options should usually be short (one or two
2278 // options), and the uniqueness isn't strictly necessary (it is just for
2279 // codegen efficiency).
2280 std::string FnName = "check", Test;
2281 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2282 std::string Part = (*I)->getValueAsString("Name");
2283 Test += "S.LangOpts." + Part;
2288 FnName += "LangOpts";
2290 // If this code has already been generated, simply return the previous
2292 static std::set<std::string> CustomLangOptsSet;
2293 std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
2294 if (I != CustomLangOptsSet.end())
2297 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2298 OS << " if (" << Test << ")\n";
2299 OS << " return true;\n\n";
2300 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2301 OS << "<< Attr.getName();\n";
2302 OS << " return false;\n";
2305 CustomLangOptsSet.insert(FnName);
2309 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2310 OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
2311 OS << " return true;\n";
2315 static std::string GenerateTargetRequirements(const Record &Attr,
2316 const ParsedAttrMap &Dupes,
2318 // If the attribute is not a target specific attribute, return the default
2320 if (!Attr.isSubClassOf("TargetSpecificAttr"))
2321 return "defaultTargetRequirements";
2323 // Get the list of architectures to be tested for.
2324 const Record *R = Attr.getValueAsDef("Target");
2325 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2326 if (Arches.empty()) {
2327 PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2328 "target-specific attr");
2329 return "defaultTargetRequirements";
2332 // If there are other attributes which share the same parsed attribute kind,
2333 // such as target-specific attributes with a shared spelling, collapse the
2334 // duplicate architectures. This is required because a shared target-specific
2335 // attribute has only one AttributeList::Kind enumeration value, but it
2336 // applies to multiple target architectures. In order for the attribute to be
2337 // considered valid, all of its architectures need to be included.
2338 if (!Attr.isValueUnset("ParseKind")) {
2339 std::string APK = Attr.getValueAsString("ParseKind");
2340 for (const auto &I : Dupes) {
2341 if (I.first == APK) {
2342 std::vector<std::string> DA = I.second->getValueAsDef("Target")
2343 ->getValueAsListOfStrings("Arches");
2344 std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
2349 std::string FnName = "isTarget", Test = "(";
2350 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2351 std::string Part = *I;
2352 Test += "Arch == llvm::Triple::" + Part;
2359 // If the target also requires OS testing, generate those tests as well.
2360 bool UsesOS = false;
2361 if (!R->isValueUnset("OSes")) {
2364 // We know that there was at least one arch test, so we need to and in the
2367 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
2368 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
2369 std::string Part = *I;
2371 Test += "OS == llvm::Triple::" + Part;
2379 // If this code has already been generated, simply return the previous
2381 static std::set<std::string> CustomTargetSet;
2382 std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
2383 if (I != CustomTargetSet.end())
2386 OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
2387 OS << " llvm::Triple::ArchType Arch = T.getArch();\n";
2389 OS << " llvm::Triple::OSType OS = T.getOS();\n";
2390 OS << " return " << Test << ";\n";
2393 CustomTargetSet.insert(FnName);
2397 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2398 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2399 << "const AttributeList &Attr) {\n";
2400 OS << " return UINT_MAX;\n";
2404 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2406 // If the attribute does not have a semantic form, we can bail out early.
2407 if (!Attr.getValueAsBit("ASTNode"))
2408 return "defaultSpellingIndexToSemanticSpelling";
2410 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2412 // If there are zero or one spellings, or all of the spellings share the same
2413 // name, we can also bail out early.
2414 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2415 return "defaultSpellingIndexToSemanticSpelling";
2417 // Generate the enumeration we will use for the mapping.
2418 SemanticSpellingMap SemanticToSyntacticMap;
2419 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2420 std::string Name = Attr.getName() + "AttrSpellingMap";
2422 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2424 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2425 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2431 static bool IsKnownToGCC(const Record &Attr) {
2432 // Look at the spellings for this subject; if there are any spellings which
2433 // claim to be known to GCC, the attribute is known to GCC.
2434 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2435 for (const auto &I : Spellings) {
2442 /// Emits the parsed attribute helpers
2443 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2444 emitSourceFileHeader("Parsed attribute helpers", OS);
2446 // Get the list of parsed attributes, and accept the optional list of
2447 // duplicates due to the ParseKind.
2448 ParsedAttrMap Dupes;
2449 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2451 // Generate the default appertainsTo, target and language option diagnostic,
2452 // and spelling list index mapping methods.
2453 GenerateDefaultAppertainsTo(OS);
2454 GenerateDefaultLangOptRequirements(OS);
2455 GenerateDefaultTargetRequirements(OS);
2456 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2458 // Generate the appertainsTo diagnostic methods and write their names into
2459 // another mapping. At the same time, generate the AttrInfoMap object
2460 // contents. Due to the reliance on generated code, use separate streams so
2461 // that code will not be interleaved.
2462 std::stringstream SS;
2463 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2464 // TODO: If the attribute's kind appears in the list of duplicates, that is
2465 // because it is a target-specific attribute that appears multiple times.
2466 // It would be beneficial to test whether the duplicates are "similar
2467 // enough" to each other to not cause problems. For instance, check that
2468 // the spellings are identical, and custom parsing rules match, etc.
2470 // We need to generate struct instances based off ParsedAttrInfo from
2471 // AttributeList.cpp.
2473 emitArgInfo(*I->second, SS);
2474 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2475 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2476 SS << ", " << I->second->isSubClassOf("TypeAttr");
2477 SS << ", " << IsKnownToGCC(*I->second);
2478 SS << ", " << GenerateAppertainsTo(*I->second, OS);
2479 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2480 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2481 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2487 SS << " // AT_" << I->first << "\n";
2490 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2495 // Emits the kind list of parsed attributes
2496 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2497 emitSourceFileHeader("Attribute name matcher", OS);
2499 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2500 std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
2501 std::set<std::string> Seen;
2502 for (const auto *A : Attrs) {
2503 const Record &Attr = *A;
2505 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
2506 bool Ignored = Attr.getValueAsBit("Ignored");
2507 if (SemaHandler || Ignored) {
2508 // Attribute spellings can be shared between target-specific attributes,
2509 // and can be shared between syntaxes for the same attribute. For
2510 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
2511 // specific attribute, or MSP430-specific attribute. Additionally, an
2512 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
2513 // for the same semantic attribute. Ultimately, we need to map each of
2514 // these to a single AttributeList::Kind value, but the StringMatcher
2515 // class cannot handle duplicate match strings. So we generate a list of
2516 // string to match based on the syntax, and emit multiple string matchers
2517 // depending on the syntax used.
2518 std::string AttrName;
2519 if (Attr.isSubClassOf("TargetSpecificAttr") &&
2520 !Attr.isValueUnset("ParseKind")) {
2521 AttrName = Attr.getValueAsString("ParseKind");
2522 if (Seen.find(AttrName) != Seen.end())
2524 Seen.insert(AttrName);
2526 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
2528 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2529 for (const auto &S : Spellings) {
2530 std::string RawSpelling = S.name();
2531 std::vector<StringMatcher::StringPair> *Matches = nullptr;
2532 std::string Spelling, Variety = S.variety();
2533 if (Variety == "CXX11") {
2535 Spelling += S.nameSpace();
2537 } else if (Variety == "GNU")
2539 else if (Variety == "Declspec")
2540 Matches = &Declspec;
2541 else if (Variety == "Keyword")
2542 Matches = &Keywords;
2543 else if (Variety == "Pragma")
2546 assert(Matches && "Unsupported spelling variety found");
2548 Spelling += NormalizeAttrSpelling(RawSpelling);
2550 Matches->push_back(StringMatcher::StringPair(Spelling,
2551 "return AttributeList::AT_" + AttrName + ";"));
2553 Matches->push_back(StringMatcher::StringPair(Spelling,
2554 "return AttributeList::IgnoredAttribute;"));
2559 OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
2560 OS << "AttributeList::Syntax Syntax) {\n";
2561 OS << " if (AttributeList::AS_GNU == Syntax) {\n";
2562 StringMatcher("Name", GNU, OS).Emit();
2563 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
2564 StringMatcher("Name", Declspec, OS).Emit();
2565 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
2566 StringMatcher("Name", CXX11, OS).Emit();
2567 OS << " } else if (AttributeList::AS_Keyword == Syntax) {\n";
2568 StringMatcher("Name", Keywords, OS).Emit();
2569 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
2570 StringMatcher("Name", Pragma, OS).Emit();
2572 OS << " return AttributeList::UnknownAttribute;\n"
2576 // Emits the code to dump an attribute.
2577 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
2578 emitSourceFileHeader("Attribute dumper", OS);
2581 " switch (A->getKind()) {\n"
2583 " llvm_unreachable(\"Unknown attribute kind!\");\n"
2585 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2586 for (const auto *Attr : Attrs) {
2587 const Record &R = *Attr;
2588 if (!R.getValueAsBit("ASTNode"))
2590 OS << " case attr::" << R.getName() << ": {\n";
2592 // If the attribute has a semantically-meaningful name (which is determined
2593 // by whether there is a Spelling enumeration for it), then write out the
2594 // spelling used for the attribute.
2595 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2596 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
2597 OS << " OS << \" \" << A->getSpelling();\n";
2599 Args = R.getValueAsListOfDefs("Args");
2600 if (!Args.empty()) {
2601 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
2603 for (const auto *Arg : Args)
2604 createArgument(*Arg, R.getName())->writeDump(OS);
2606 // Code for detecting the last child.
2607 OS << " bool OldMoreChildren = hasMoreChildren();\n";
2608 OS << " bool MoreChildren;\n";
2610 for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) {
2611 // More code for detecting the last child.
2612 OS << " MoreChildren = OldMoreChildren";
2613 for (auto Next = AI + 1; Next != AE; ++Next) {
2615 createArgument(**Next, R.getName())->writeHasChildren(OS);
2618 OS << " setMoreChildren(MoreChildren);\n";
2620 createArgument(**AI, R.getName())->writeDumpChildren(OS);
2623 // Reset the last child.
2624 OS << " setMoreChildren(OldMoreChildren);\n";
2633 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
2635 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
2636 emitClangAttrArgContextList(Records, OS);
2637 emitClangAttrIdentifierArgList(Records, OS);
2638 emitClangAttrTypeArgList(Records, OS);
2639 emitClangAttrLateParsedList(Records, OS);
2642 class DocumentationData {
2644 const Record *Documentation;
2645 const Record *Attribute;
2647 DocumentationData(const Record &Documentation, const Record &Attribute)
2648 : Documentation(&Documentation), Attribute(&Attribute) {}
2651 static void WriteCategoryHeader(const Record *DocCategory,
2653 const std::string &Name = DocCategory->getValueAsString("Name");
2654 OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
2656 // If there is content, print that as well.
2657 std::string ContentStr = DocCategory->getValueAsString("Content");
2658 if (!ContentStr.empty()) {
2659 // Trim leading and trailing newlines and spaces.
2660 StringRef Content(ContentStr);
2661 while (Content.startswith("\r") || Content.startswith("\n") ||
2662 Content.startswith(" ") || Content.startswith("\t"))
2663 Content = Content.substr(1);
2664 while (Content.endswith("\r") || Content.endswith("\n") ||
2665 Content.endswith(" ") || Content.endswith("\t"))
2666 Content = Content.substr(0, Content.size() - 1);
2680 static void WriteDocumentation(const DocumentationData &Doc,
2682 // FIXME: there is no way to have a per-spelling category for the attribute
2683 // documentation. This may not be a limiting factor since the spellings
2684 // should generally be consistently applied across the category.
2686 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
2688 // Determine the heading to be used for this attribute.
2689 std::string Heading = Doc.Documentation->getValueAsString("Heading");
2690 bool CustomHeading = !Heading.empty();
2691 if (Heading.empty()) {
2692 // If there's only one spelling, we can simply use that.
2693 if (Spellings.size() == 1)
2694 Heading = Spellings.begin()->name();
2696 std::set<std::string> Uniques;
2697 for (auto I = Spellings.begin(), E = Spellings.end();
2698 I != E && Uniques.size() <= 1; ++I) {
2699 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
2700 Uniques.insert(Spelling);
2702 // If the semantic map has only one spelling, that is sufficient for our
2704 if (Uniques.size() == 1)
2705 Heading = *Uniques.begin();
2709 // If the heading is still empty, it is an error.
2710 if (Heading.empty())
2711 PrintFatalError(Doc.Attribute->getLoc(),
2712 "This attribute requires a heading to be specified");
2714 // Gather a list of unique spellings; this is not the same as the semantic
2715 // spelling for the attribute. Variations in underscores and other non-
2716 // semantic characters are still acceptable.
2717 std::vector<std::string> Names;
2719 unsigned SupportedSpellings = 0;
2720 for (const auto &I : Spellings) {
2721 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
2723 .Case("CXX11", CXX11)
2724 .Case("Declspec", Declspec)
2725 .Case("Keyword", Keyword)
2726 .Case("Pragma", Pragma);
2728 // Mask in the supported spelling.
2729 SupportedSpellings |= Kind;
2732 if (Kind == CXX11 && !I.nameSpace().empty())
2733 Name = I.nameSpace() + "::";
2736 // If this name is the same as the heading, do not add it.
2737 if (Name != Heading)
2738 Names.push_back(Name);
2741 // Print out the heading for the attribute. If there are alternate spellings,
2742 // then display those after the heading.
2743 if (!CustomHeading && !Names.empty()) {
2745 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
2746 if (I != Names.begin())
2752 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
2754 if (!SupportedSpellings)
2755 PrintFatalError(Doc.Attribute->getLoc(),
2756 "Attribute has no supported spellings; cannot be "
2759 // List what spelling syntaxes the attribute supports.
2760 OS << ".. csv-table:: Supported Syntaxes\n";
2761 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
2762 OS << " \"Pragma\"\n\n";
2764 if (SupportedSpellings & GNU) OS << "X";
2766 if (SupportedSpellings & CXX11) OS << "X";
2768 if (SupportedSpellings & Declspec) OS << "X";
2770 if (SupportedSpellings & Keyword) OS << "X";
2772 if (SupportedSpellings & Pragma) OS << "X";
2775 // If the attribute is deprecated, print a message about it, and possibly
2776 // provide a replacement attribute.
2777 if (!Doc.Documentation->isValueUnset("Deprecated")) {
2778 OS << "This attribute has been deprecated, and may be removed in a future "
2779 << "version of Clang.";
2780 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
2781 std::string Replacement = Deprecated.getValueAsString("Replacement");
2782 if (!Replacement.empty())
2783 OS << " This attribute has been superseded by ``"
2784 << Replacement << "``.";
2788 std::string ContentStr = Doc.Documentation->getValueAsString("Content");
2789 // Trim leading and trailing newlines and spaces.
2790 StringRef Content(ContentStr);
2791 while (Content.startswith("\r") || Content.startswith("\n") ||
2792 Content.startswith(" ") || Content.startswith("\t"))
2793 Content = Content.substr(1);
2794 while (Content.endswith("\r") || Content.endswith("\n") ||
2795 Content.endswith(" ") || Content.endswith("\t"))
2796 Content = Content.substr(0, Content.size() - 1);
2802 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
2803 // Get the documentation introduction paragraph.
2804 const Record *Documentation = Records.getDef("GlobalDocumentation");
2805 if (!Documentation) {
2806 PrintFatalError("The Documentation top-level definition is missing, "
2807 "no documentation will be generated.");
2811 OS << Documentation->getValueAsString("Intro") << "\n";
2813 // Gather the Documentation lists from each of the attributes, based on the
2814 // category provided.
2815 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2816 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
2817 for (const auto *A : Attrs) {
2818 const Record &Attr = *A;
2819 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
2820 for (const auto *D : Docs) {
2821 const Record &Doc = *D;
2822 const Record *Category = Doc.getValueAsDef("Category");
2823 // If the category is "undocumented", then there cannot be any other
2824 // documentation categories (otherwise, the attribute would become
2826 std::string Cat = Category->getValueAsString("Name");
2827 bool Undocumented = Cat == "Undocumented";
2828 if (Undocumented && Docs.size() > 1)
2829 PrintFatalError(Doc.getLoc(),
2830 "Attribute is \"Undocumented\", but has multiple "
2831 "documentation categories");
2834 SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
2838 // Having split the attributes out based on what documentation goes where,
2839 // we can begin to generate sections of documentation.
2840 for (const auto &I : SplitDocs) {
2841 WriteCategoryHeader(I.first, OS);
2843 // Walk over each of the attributes in the category and write out their
2845 for (const auto &Doc : I.second)
2846 WriteDocumentation(Doc, OS);
2850 } // end namespace clang