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/StringExtras.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/TableGen/Error.h"
20 #include "llvm/TableGen/Record.h"
21 #include "llvm/TableGen/StringMatcher.h"
22 #include "llvm/TableGen/TableGenBackend.h"
32 class FlattenedSpelling {
37 FlattenedSpelling(const std::string &Variety, const std::string &Name,
38 const std::string &Namespace, bool KnownToGCC) :
39 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
40 explicit FlattenedSpelling(const Record &Spelling) :
41 V(Spelling.getValueAsString("Variety")),
42 N(Spelling.getValueAsString("Name")) {
44 assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been"
46 if (V == "CXX11" || V == "Pragma")
47 NS = Spelling.getValueAsString("Namespace");
49 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
52 const std::string &variety() const { return V; }
53 const std::string &name() const { return N; }
54 const std::string &nameSpace() const { return NS; }
55 bool knownToGCC() const { return K; }
59 static std::vector<FlattenedSpelling>
60 GetFlattenedSpellings(const Record &Attr) {
61 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
62 std::vector<FlattenedSpelling> Ret;
64 for (const auto &Spelling : Spellings) {
65 if (Spelling->getValueAsString("Variety") == "GCC") {
66 // Gin up two new spelling objects to add into the list.
67 Ret.emplace_back("GNU", Spelling->getValueAsString("Name"), "", true);
68 Ret.emplace_back("CXX11", Spelling->getValueAsString("Name"), "gnu",
71 Ret.push_back(FlattenedSpelling(*Spelling));
77 static std::string ReadPCHRecord(StringRef type) {
78 return StringSwitch<std::string>(type)
79 .EndsWith("Decl *", "GetLocalDeclAs<"
80 + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])")
81 .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)")
82 .Case("Expr *", "ReadExpr(F)")
83 .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)")
84 .Case("std::string", "ReadString(Record, Idx)")
85 .Default("Record[Idx++]");
88 // Assumes that the way to get the value is SA->getname()
89 static std::string WritePCHRecord(StringRef type, StringRef name) {
90 return StringSwitch<std::string>(type)
91 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) +
93 .Case("TypeSourceInfo *",
94 "AddTypeSourceInfo(" + std::string(name) + ", Record);\n")
95 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
96 .Case("IdentifierInfo *",
97 "AddIdentifierRef(" + std::string(name) + ", Record);\n")
98 .Case("std::string", "AddString(" + std::string(name) + ", Record);\n")
99 .Default("Record.push_back(" + std::string(name) + ");\n");
102 // Normalize attribute name by removing leading and trailing
103 // underscores. For example, __foo, foo__, __foo__ would
105 static StringRef NormalizeAttrName(StringRef AttrName) {
106 if (AttrName.startswith("__"))
107 AttrName = AttrName.substr(2, AttrName.size());
109 if (AttrName.endswith("__"))
110 AttrName = AttrName.substr(0, AttrName.size() - 2);
115 // Normalize the name by removing any and all leading and trailing underscores.
116 // This is different from NormalizeAttrName in that it also handles names like
117 // _pascal and __pascal.
118 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
119 return Name.trim("_");
122 // Normalize attribute spelling only if the spelling has both leading
123 // and trailing underscores. For example, __ms_struct__ will be
124 // normalized to "ms_struct"; __cdecl will remain intact.
125 static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) {
126 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
127 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
133 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
135 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
136 ParsedAttrMap *Dupes = nullptr) {
137 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
138 std::set<std::string> Seen;
140 for (const auto *Attr : Attrs) {
141 if (Attr->getValueAsBit("SemaHandler")) {
143 if (Attr->isSubClassOf("TargetSpecificAttr") &&
144 !Attr->isValueUnset("ParseKind")) {
145 AN = Attr->getValueAsString("ParseKind");
147 // If this attribute has already been handled, it does not need to be
149 if (Seen.find(AN) != Seen.end()) {
151 Dupes->push_back(std::make_pair(AN, Attr));
156 AN = NormalizeAttrName(Attr->getName()).str();
158 R.push_back(std::make_pair(AN, Attr));
166 std::string lowerName, upperName;
171 Argument(const Record &Arg, StringRef Attr)
172 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
173 attrName(Attr), isOpt(false) {
174 if (!lowerName.empty()) {
175 lowerName[0] = std::tolower(lowerName[0]);
176 upperName[0] = std::toupper(upperName[0]);
179 virtual ~Argument() {}
181 StringRef getLowerName() const { return lowerName; }
182 StringRef getUpperName() const { return upperName; }
183 StringRef getAttrName() const { return attrName; }
185 bool isOptional() const { return isOpt; }
186 void setOptional(bool set) { isOpt = set; }
188 // These functions print the argument contents formatted in different ways.
189 virtual void writeAccessors(raw_ostream &OS) const = 0;
190 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
191 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
192 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
193 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
194 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
195 virtual void writeCtorBody(raw_ostream &OS) const {}
196 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
197 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
198 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
199 virtual void writeDeclarations(raw_ostream &OS) const = 0;
200 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
201 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
202 virtual void writePCHWrite(raw_ostream &OS) const = 0;
203 virtual void writeValue(raw_ostream &OS) const = 0;
204 virtual void writeDump(raw_ostream &OS) const = 0;
205 virtual void writeDumpChildren(raw_ostream &OS) const {}
206 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
208 virtual bool isEnumArg() const { return false; }
209 virtual bool isVariadicEnumArg() const { return false; }
210 virtual bool isVariadic() const { return false; }
212 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
213 OS << getUpperName();
217 class SimpleArgument : public Argument {
221 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
222 : Argument(Arg, Attr), type(T)
225 std::string getType() const { return type; }
227 void writeAccessors(raw_ostream &OS) const override {
228 OS << " " << type << " get" << getUpperName() << "() const {\n";
229 OS << " return " << getLowerName() << ";\n";
232 void writeCloneArgs(raw_ostream &OS) const override {
233 OS << getLowerName();
235 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
236 OS << "A->get" << getUpperName() << "()";
238 void writeCtorInitializers(raw_ostream &OS) const override {
239 OS << getLowerName() << "(" << getUpperName() << ")";
241 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
242 OS << getLowerName() << "()";
244 void writeCtorParameters(raw_ostream &OS) const override {
245 OS << type << " " << getUpperName();
247 void writeDeclarations(raw_ostream &OS) const override {
248 OS << type << " " << getLowerName() << ";";
250 void writePCHReadDecls(raw_ostream &OS) const override {
251 std::string read = ReadPCHRecord(type);
252 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
254 void writePCHReadArgs(raw_ostream &OS) const override {
255 OS << getLowerName();
257 void writePCHWrite(raw_ostream &OS) const override {
258 OS << " " << WritePCHRecord(type, "SA->get" +
259 std::string(getUpperName()) + "()");
261 void writeValue(raw_ostream &OS) const override {
262 if (type == "FunctionDecl *") {
263 OS << "\" << get" << getUpperName()
264 << "()->getNameInfo().getAsString() << \"";
265 } else if (type == "IdentifierInfo *") {
266 OS << "\" << get" << getUpperName() << "()->getName() << \"";
267 } else if (type == "TypeSourceInfo *") {
268 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
270 OS << "\" << get" << getUpperName() << "() << \"";
273 void writeDump(raw_ostream &OS) const override {
274 if (type == "FunctionDecl *") {
275 OS << " OS << \" \";\n";
276 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
277 } else if (type == "IdentifierInfo *") {
278 OS << " OS << \" \" << SA->get" << getUpperName()
279 << "()->getName();\n";
280 } else if (type == "TypeSourceInfo *") {
281 OS << " OS << \" \" << SA->get" << getUpperName()
282 << "().getAsString();\n";
283 } else if (type == "bool") {
284 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
285 << getUpperName() << "\";\n";
286 } else if (type == "int" || type == "unsigned") {
287 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
289 llvm_unreachable("Unknown SimpleArgument type!");
294 class DefaultSimpleArgument : public SimpleArgument {
298 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
299 std::string T, int64_t Default)
300 : SimpleArgument(Arg, Attr, T), Default(Default) {}
302 void writeAccessors(raw_ostream &OS) const override {
303 SimpleArgument::writeAccessors(OS);
305 OS << "\n\n static const " << getType() << " Default" << getUpperName()
306 << " = " << Default << ";";
310 class StringArgument : public Argument {
312 StringArgument(const Record &Arg, StringRef Attr)
313 : Argument(Arg, Attr)
316 void writeAccessors(raw_ostream &OS) const override {
317 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
318 OS << " return llvm::StringRef(" << getLowerName() << ", "
319 << getLowerName() << "Length);\n";
321 OS << " unsigned get" << getUpperName() << "Length() const {\n";
322 OS << " return " << getLowerName() << "Length;\n";
324 OS << " void set" << getUpperName()
325 << "(ASTContext &C, llvm::StringRef S) {\n";
326 OS << " " << getLowerName() << "Length = S.size();\n";
327 OS << " this->" << getLowerName() << " = new (C, 1) char ["
328 << getLowerName() << "Length];\n";
329 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
330 << getLowerName() << "Length);\n";
333 void writeCloneArgs(raw_ostream &OS) const override {
334 OS << "get" << getUpperName() << "()";
336 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
337 OS << "A->get" << getUpperName() << "()";
339 void writeCtorBody(raw_ostream &OS) const override {
340 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
341 << ".data(), " << getLowerName() << "Length);";
343 void writeCtorInitializers(raw_ostream &OS) const override {
344 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
345 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
348 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
349 OS << getLowerName() << "Length(0)," << getLowerName() << "(0)";
351 void writeCtorParameters(raw_ostream &OS) const override {
352 OS << "llvm::StringRef " << getUpperName();
354 void writeDeclarations(raw_ostream &OS) const override {
355 OS << "unsigned " << getLowerName() << "Length;\n";
356 OS << "char *" << getLowerName() << ";";
358 void writePCHReadDecls(raw_ostream &OS) const override {
359 OS << " std::string " << getLowerName()
360 << "= ReadString(Record, Idx);\n";
362 void writePCHReadArgs(raw_ostream &OS) const override {
363 OS << getLowerName();
365 void writePCHWrite(raw_ostream &OS) const override {
366 OS << " AddString(SA->get" << getUpperName() << "(), Record);\n";
368 void writeValue(raw_ostream &OS) const override {
369 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
371 void writeDump(raw_ostream &OS) const override {
372 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
373 << "() << \"\\\"\";\n";
377 class AlignedArgument : public Argument {
379 AlignedArgument(const Record &Arg, StringRef Attr)
380 : Argument(Arg, Attr)
383 void writeAccessors(raw_ostream &OS) const override {
384 OS << " bool is" << getUpperName() << "Dependent() const;\n";
386 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
388 OS << " bool is" << getUpperName() << "Expr() const {\n";
389 OS << " return is" << getLowerName() << "Expr;\n";
392 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
393 OS << " assert(is" << getLowerName() << "Expr);\n";
394 OS << " return " << getLowerName() << "Expr;\n";
397 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
398 OS << " assert(!is" << getLowerName() << "Expr);\n";
399 OS << " return " << getLowerName() << "Type;\n";
402 void writeAccessorDefinitions(raw_ostream &OS) const override {
403 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
404 << "Dependent() const {\n";
405 OS << " if (is" << getLowerName() << "Expr)\n";
406 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
407 << "Expr->isValueDependent() || " << getLowerName()
408 << "Expr->isTypeDependent());\n";
410 OS << " return " << getLowerName()
411 << "Type->getType()->isDependentType();\n";
414 // FIXME: Do not do the calculation here
415 // FIXME: Handle types correctly
416 // A null pointer means maximum alignment
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()"
423 << " * Ctx.getCharWidth() : "
424 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
426 OS << " return 0; // FIXME\n";
429 void writeCloneArgs(raw_ostream &OS) const override {
430 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
431 << "Expr ? static_cast<void*>(" << getLowerName()
432 << "Expr) : " << getLowerName()
435 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
436 // FIXME: move the definition in Sema::InstantiateAttrs to here.
437 // In the meantime, aligned attributes are cloned.
439 void writeCtorBody(raw_ostream &OS) const override {
440 OS << " if (is" << getLowerName() << "Expr)\n";
441 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
442 << getUpperName() << ");\n";
444 OS << " " << getLowerName()
445 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
448 void writeCtorInitializers(raw_ostream &OS) const override {
449 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
451 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
452 OS << "is" << getLowerName() << "Expr(false)";
454 void writeCtorParameters(raw_ostream &OS) const override {
455 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
457 void writeImplicitCtorArgs(raw_ostream &OS) const override {
458 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
460 void writeDeclarations(raw_ostream &OS) const override {
461 OS << "bool is" << getLowerName() << "Expr;\n";
463 OS << "Expr *" << getLowerName() << "Expr;\n";
464 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
467 void writePCHReadArgs(raw_ostream &OS) const override {
468 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
470 void writePCHReadDecls(raw_ostream &OS) const override {
471 OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
472 OS << " void *" << getLowerName() << "Ptr;\n";
473 OS << " if (is" << getLowerName() << "Expr)\n";
474 OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
476 OS << " " << getLowerName()
477 << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
479 void writePCHWrite(raw_ostream &OS) const override {
480 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
481 OS << " if (SA->is" << getUpperName() << "Expr())\n";
482 OS << " AddStmt(SA->get" << getUpperName() << "Expr());\n";
484 OS << " AddTypeSourceInfo(SA->get" << getUpperName()
485 << "Type(), Record);\n";
487 void writeValue(raw_ostream &OS) const override {
489 // The aligned attribute argument expression is optional.
490 OS << " if (is" << getLowerName() << "Expr && "
491 << getLowerName() << "Expr)\n";
492 OS << " " << getLowerName() << "Expr->printPretty(OS, 0, Policy);\n";
495 void writeDump(raw_ostream &OS) const override {
497 void writeDumpChildren(raw_ostream &OS) const override {
498 OS << " if (SA->is" << getUpperName() << "Expr())\n";
499 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
501 OS << " dumpType(SA->get" << getUpperName()
502 << "Type()->getType());\n";
504 void writeHasChildren(raw_ostream &OS) const override {
505 OS << "SA->is" << getUpperName() << "Expr()";
509 class VariadicArgument : public Argument {
510 std::string Type, ArgName, ArgSizeName, RangeName;
513 // Assumed to receive a parameter: raw_ostream OS.
514 virtual void writeValueImpl(raw_ostream &OS) const {
515 OS << " OS << Val;\n";
519 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
520 : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
521 ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}
523 std::string getType() const { return Type; }
524 bool isVariadic() const override { return true; }
526 void writeAccessors(raw_ostream &OS) const override {
527 std::string IteratorType = getLowerName().str() + "_iterator";
528 std::string BeginFn = getLowerName().str() + "_begin()";
529 std::string EndFn = getLowerName().str() + "_end()";
531 OS << " typedef " << Type << "* " << IteratorType << ";\n";
532 OS << " " << IteratorType << " " << BeginFn << " const {"
533 << " return " << ArgName << "; }\n";
534 OS << " " << IteratorType << " " << EndFn << " const {"
535 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
536 OS << " unsigned " << getLowerName() << "_size() const {"
537 << " return " << ArgSizeName << "; }\n";
538 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
539 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
542 void writeCloneArgs(raw_ostream &OS) const override {
543 OS << ArgName << ", " << ArgSizeName;
545 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
546 // This isn't elegant, but we have to go through public methods...
547 OS << "A->" << getLowerName() << "_begin(), "
548 << "A->" << getLowerName() << "_size()";
550 void writeCtorBody(raw_ostream &OS) const override {
551 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
552 << " + " << ArgSizeName << ", " << ArgName << ");";
554 void writeCtorInitializers(raw_ostream &OS) const override {
555 OS << ArgSizeName << "(" << getUpperName() << "Size), "
556 << ArgName << "(new (Ctx, 16) " << getType() << "["
557 << ArgSizeName << "])";
559 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
560 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
562 void writeCtorParameters(raw_ostream &OS) const override {
563 OS << getType() << " *" << getUpperName() << ", unsigned "
564 << getUpperName() << "Size";
566 void writeImplicitCtorArgs(raw_ostream &OS) const override {
567 OS << getUpperName() << ", " << getUpperName() << "Size";
569 void writeDeclarations(raw_ostream &OS) const override {
570 OS << " unsigned " << ArgSizeName << ";\n";
571 OS << " " << getType() << " *" << ArgName << ";";
573 void writePCHReadDecls(raw_ostream &OS) const override {
574 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
575 OS << " SmallVector<" << Type << ", 4> " << getLowerName()
577 OS << " " << getLowerName() << ".reserve(" << getLowerName()
579 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
581 std::string read = ReadPCHRecord(Type);
582 OS << " " << getLowerName() << ".push_back(" << read << ");\n";
584 void writePCHReadArgs(raw_ostream &OS) const override {
585 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
587 void writePCHWrite(raw_ostream &OS) const override {
588 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
589 OS << " for (auto &Val : SA->" << RangeName << "())\n";
590 OS << " " << WritePCHRecord(Type, "Val");
592 void writeValue(raw_ostream &OS) const override {
594 OS << " bool isFirst = true;\n"
595 << " for (const auto &Val : " << RangeName << "()) {\n"
596 << " if (isFirst) isFirst = false;\n"
597 << " else OS << \", \";\n";
602 void writeDump(raw_ostream &OS) const override {
603 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
604 OS << " OS << \" \" << Val;\n";
608 // Unique the enums, but maintain the original declaration ordering.
609 std::vector<std::string>
610 uniqueEnumsInOrder(const std::vector<std::string> &enums) {
611 std::vector<std::string> uniques;
612 std::set<std::string> unique_set(enums.begin(), enums.end());
613 for (const auto &i : enums) {
614 std::set<std::string>::iterator set_i = unique_set.find(i);
615 if (set_i != unique_set.end()) {
616 uniques.push_back(i);
617 unique_set.erase(set_i);
623 class EnumArgument : public Argument {
625 std::vector<std::string> values, enums, uniques;
627 EnumArgument(const Record &Arg, StringRef Attr)
628 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
629 values(Arg.getValueAsListOfStrings("Values")),
630 enums(Arg.getValueAsListOfStrings("Enums")),
631 uniques(uniqueEnumsInOrder(enums))
633 // FIXME: Emit a proper error
634 assert(!uniques.empty());
637 bool isEnumArg() const override { return true; }
639 void writeAccessors(raw_ostream &OS) const override {
640 OS << " " << type << " get" << getUpperName() << "() const {\n";
641 OS << " return " << getLowerName() << ";\n";
644 void writeCloneArgs(raw_ostream &OS) const override {
645 OS << getLowerName();
647 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
648 OS << "A->get" << getUpperName() << "()";
650 void writeCtorInitializers(raw_ostream &OS) const override {
651 OS << getLowerName() << "(" << getUpperName() << ")";
653 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
654 OS << getLowerName() << "(" << type << "(0))";
656 void writeCtorParameters(raw_ostream &OS) const override {
657 OS << type << " " << getUpperName();
659 void writeDeclarations(raw_ostream &OS) const override {
660 std::vector<std::string>::const_iterator i = uniques.begin(),
662 // The last one needs to not have a comma.
666 OS << " enum " << type << " {\n";
668 OS << " " << *i << ",\n";
669 OS << " " << *e << "\n";
672 OS << " " << type << " " << getLowerName() << ";";
674 void writePCHReadDecls(raw_ostream &OS) const override {
675 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
676 << "(static_cast<" << getAttrName() << "Attr::" << type
677 << ">(Record[Idx++]));\n";
679 void writePCHReadArgs(raw_ostream &OS) const override {
680 OS << getLowerName();
682 void writePCHWrite(raw_ostream &OS) const override {
683 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
685 void writeValue(raw_ostream &OS) const override {
686 // FIXME: this isn't 100% correct -- some enum arguments require printing
687 // as a string literal, while others require printing as an identifier.
688 // Tablegen currently does not distinguish between the two forms.
689 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
690 << getUpperName() << "()) << \"\\\"";
692 void writeDump(raw_ostream &OS) const override {
693 OS << " switch(SA->get" << getUpperName() << "()) {\n";
694 for (const auto &I : uniques) {
695 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
696 OS << " OS << \" " << I << "\";\n";
702 void writeConversion(raw_ostream &OS) const {
703 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
704 OS << type << " &Out) {\n";
705 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
706 OS << type << ">>(Val)\n";
707 for (size_t I = 0; I < enums.size(); ++I) {
708 OS << " .Case(\"" << values[I] << "\", ";
709 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
711 OS << " .Default(Optional<" << type << ">());\n";
713 OS << " Out = *R;\n return true;\n }\n";
714 OS << " return false;\n";
717 // Mapping from enumeration values back to enumeration strings isn't
718 // trivial because some enumeration values have multiple named
719 // enumerators, such as type_visibility(internal) and
720 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
721 OS << " static const char *Convert" << type << "ToStr("
722 << type << " Val) {\n"
723 << " switch(Val) {\n";
724 std::set<std::string> Uniques;
725 for (size_t I = 0; I < enums.size(); ++I) {
726 if (Uniques.insert(enums[I]).second)
727 OS << " case " << getAttrName() << "Attr::" << enums[I]
728 << ": return \"" << values[I] << "\";\n";
731 << " llvm_unreachable(\"No enumerator with that value\");\n"
736 class VariadicEnumArgument: public VariadicArgument {
737 std::string type, QualifiedTypeName;
738 std::vector<std::string> values, enums, uniques;
741 void writeValueImpl(raw_ostream &OS) const override {
742 // FIXME: this isn't 100% correct -- some enum arguments require printing
743 // as a string literal, while others require printing as an identifier.
744 // Tablegen currently does not distinguish between the two forms.
745 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
746 << "ToStr(Val)" << "<< \"\\\"\";\n";
750 VariadicEnumArgument(const Record &Arg, StringRef Attr)
751 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
752 type(Arg.getValueAsString("Type")),
753 values(Arg.getValueAsListOfStrings("Values")),
754 enums(Arg.getValueAsListOfStrings("Enums")),
755 uniques(uniqueEnumsInOrder(enums))
757 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
759 // FIXME: Emit a proper error
760 assert(!uniques.empty());
763 bool isVariadicEnumArg() const override { return true; }
765 void writeDeclarations(raw_ostream &OS) const override {
766 std::vector<std::string>::const_iterator i = uniques.begin(),
768 // The last one needs to not have a comma.
772 OS << " enum " << type << " {\n";
774 OS << " " << *i << ",\n";
775 OS << " " << *e << "\n";
779 VariadicArgument::writeDeclarations(OS);
781 void writeDump(raw_ostream &OS) const override {
782 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
783 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
784 << getLowerName() << "_end(); I != E; ++I) {\n";
785 OS << " switch(*I) {\n";
786 for (const auto &UI : uniques) {
787 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
788 OS << " OS << \" " << UI << "\";\n";
794 void writePCHReadDecls(raw_ostream &OS) const override {
795 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
796 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
798 OS << " " << getLowerName() << ".reserve(" << getLowerName()
800 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
801 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
802 << QualifiedTypeName << ">(Record[Idx++]));\n";
804 void writePCHWrite(raw_ostream &OS) const override {
805 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
806 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
807 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
808 << getLowerName() << "_end(); i != e; ++i)\n";
809 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
811 void writeConversion(raw_ostream &OS) const {
812 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
813 OS << type << " &Out) {\n";
814 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
815 OS << type << ">>(Val)\n";
816 for (size_t I = 0; I < enums.size(); ++I) {
817 OS << " .Case(\"" << values[I] << "\", ";
818 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
820 OS << " .Default(Optional<" << type << ">());\n";
822 OS << " Out = *R;\n return true;\n }\n";
823 OS << " return false;\n";
826 OS << " static const char *Convert" << type << "ToStr("
827 << type << " Val) {\n"
828 << " switch(Val) {\n";
829 std::set<std::string> Uniques;
830 for (size_t I = 0; I < enums.size(); ++I) {
831 if (Uniques.insert(enums[I]).second)
832 OS << " case " << getAttrName() << "Attr::" << enums[I]
833 << ": return \"" << values[I] << "\";\n";
836 << " llvm_unreachable(\"No enumerator with that value\");\n"
841 class VersionArgument : public Argument {
843 VersionArgument(const Record &Arg, StringRef Attr)
844 : Argument(Arg, Attr)
847 void writeAccessors(raw_ostream &OS) const override {
848 OS << " VersionTuple get" << getUpperName() << "() const {\n";
849 OS << " return " << getLowerName() << ";\n";
851 OS << " void set" << getUpperName()
852 << "(ASTContext &C, VersionTuple V) {\n";
853 OS << " " << getLowerName() << " = V;\n";
856 void writeCloneArgs(raw_ostream &OS) const override {
857 OS << "get" << getUpperName() << "()";
859 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
860 OS << "A->get" << getUpperName() << "()";
862 void writeCtorInitializers(raw_ostream &OS) const override {
863 OS << getLowerName() << "(" << getUpperName() << ")";
865 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
866 OS << getLowerName() << "()";
868 void writeCtorParameters(raw_ostream &OS) const override {
869 OS << "VersionTuple " << getUpperName();
871 void writeDeclarations(raw_ostream &OS) const override {
872 OS << "VersionTuple " << getLowerName() << ";\n";
874 void writePCHReadDecls(raw_ostream &OS) const override {
875 OS << " VersionTuple " << getLowerName()
876 << "= ReadVersionTuple(Record, Idx);\n";
878 void writePCHReadArgs(raw_ostream &OS) const override {
879 OS << getLowerName();
881 void writePCHWrite(raw_ostream &OS) const override {
882 OS << " AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
884 void writeValue(raw_ostream &OS) const override {
885 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
887 void writeDump(raw_ostream &OS) const override {
888 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
892 class ExprArgument : public SimpleArgument {
894 ExprArgument(const Record &Arg, StringRef Attr)
895 : SimpleArgument(Arg, Attr, "Expr *")
898 void writeASTVisitorTraversal(raw_ostream &OS) const override {
900 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
901 OS << " return false;\n";
904 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
905 OS << "tempInst" << getUpperName();
908 void writeTemplateInstantiation(raw_ostream &OS) const override {
909 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
911 OS << " EnterExpressionEvaluationContext "
912 << "Unevaluated(S, Sema::Unevaluated);\n";
913 OS << " ExprResult " << "Result = S.SubstExpr("
914 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
915 OS << " tempInst" << getUpperName() << " = "
916 << "Result.getAs<Expr>();\n";
920 void writeDump(raw_ostream &OS) const override {}
922 void writeDumpChildren(raw_ostream &OS) const override {
923 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
925 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
928 class VariadicExprArgument : public VariadicArgument {
930 VariadicExprArgument(const Record &Arg, StringRef Attr)
931 : VariadicArgument(Arg, Attr, "Expr *")
934 void writeASTVisitorTraversal(raw_ostream &OS) const override {
936 OS << " " << getType() << " *I = A->" << getLowerName()
938 OS << " " << getType() << " *E = A->" << getLowerName()
940 OS << " for (; I != E; ++I) {\n";
941 OS << " if (!getDerived().TraverseStmt(*I))\n";
942 OS << " return false;\n";
947 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
948 OS << "tempInst" << getUpperName() << ", "
949 << "A->" << getLowerName() << "_size()";
952 void writeTemplateInstantiation(raw_ostream &OS) const override {
953 OS << " " << getType() << " *tempInst" << getUpperName()
954 << " = new (C, 16) " << getType()
955 << "[A->" << getLowerName() << "_size()];\n";
957 OS << " EnterExpressionEvaluationContext "
958 << "Unevaluated(S, Sema::Unevaluated);\n";
959 OS << " " << getType() << " *TI = tempInst" << getUpperName()
961 OS << " " << getType() << " *I = A->" << getLowerName()
963 OS << " " << getType() << " *E = A->" << getLowerName()
965 OS << " for (; I != E; ++I, ++TI) {\n";
966 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
967 OS << " *TI = Result.getAs<Expr>();\n";
972 void writeDump(raw_ostream &OS) const override {}
974 void writeDumpChildren(raw_ostream &OS) const override {
975 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
976 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
977 << getLowerName() << "_end(); I != E; ++I)\n";
978 OS << " dumpStmt(*I);\n";
981 void writeHasChildren(raw_ostream &OS) const override {
982 OS << "SA->" << getLowerName() << "_begin() != "
983 << "SA->" << getLowerName() << "_end()";
987 class VariadicStringArgument : public VariadicArgument {
989 VariadicStringArgument(const Record &Arg, StringRef Attr)
990 : VariadicArgument(Arg, Attr, "std::string")
992 void writeValueImpl(raw_ostream &OS) const override {
993 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
997 class TypeArgument : public SimpleArgument {
999 TypeArgument(const Record &Arg, StringRef Attr)
1000 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1003 void writeAccessors(raw_ostream &OS) const override {
1004 OS << " QualType get" << getUpperName() << "() const {\n";
1005 OS << " return " << getLowerName() << "->getType();\n";
1007 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1008 OS << " return " << getLowerName() << ";\n";
1011 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1012 OS << "A->get" << getUpperName() << "Loc()";
1014 void writePCHWrite(raw_ostream &OS) const override {
1015 OS << " " << WritePCHRecord(
1016 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1021 static std::unique_ptr<Argument>
1022 createArgument(const Record &Arg, StringRef Attr,
1023 const Record *Search = nullptr) {
1027 std::unique_ptr<Argument> Ptr;
1028 llvm::StringRef ArgName = Search->getName();
1030 if (ArgName == "AlignedArgument")
1031 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1032 else if (ArgName == "EnumArgument")
1033 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1034 else if (ArgName == "ExprArgument")
1035 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1036 else if (ArgName == "FunctionArgument")
1037 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1038 else if (ArgName == "IdentifierArgument")
1039 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1040 else if (ArgName == "DefaultBoolArgument")
1041 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1042 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1043 else if (ArgName == "BoolArgument")
1044 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1045 else if (ArgName == "DefaultIntArgument")
1046 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1047 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1048 else if (ArgName == "IntArgument")
1049 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1050 else if (ArgName == "StringArgument")
1051 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1052 else if (ArgName == "TypeArgument")
1053 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1054 else if (ArgName == "UnsignedArgument")
1055 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1056 else if (ArgName == "VariadicUnsignedArgument")
1057 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1058 else if (ArgName == "VariadicStringArgument")
1059 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1060 else if (ArgName == "VariadicEnumArgument")
1061 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1062 else if (ArgName == "VariadicExprArgument")
1063 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1064 else if (ArgName == "VersionArgument")
1065 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1068 // Search in reverse order so that the most-derived type is handled first.
1069 std::vector<Record*> Bases = Search->getSuperClasses();
1070 for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
1071 if ((Ptr = createArgument(Arg, Attr, Base)))
1076 if (Ptr && Arg.getValueAsBit("Optional"))
1077 Ptr->setOptional(true);
1082 static void writeAvailabilityValue(raw_ostream &OS) {
1083 OS << "\" << getPlatform()->getName();\n"
1084 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1085 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1086 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1087 << " if (getUnavailable()) OS << \", unavailable\";\n"
1091 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1092 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1094 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1095 if (Spellings.empty()) {
1096 OS << " return \"(No spelling)\";\n}\n\n";
1100 OS << " switch (SpellingListIndex) {\n"
1102 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1103 " return \"(No spelling)\";\n";
1105 for (unsigned I = 0; I < Spellings.size(); ++I)
1106 OS << " case " << I << ":\n"
1107 " return \"" << Spellings[I].name() << "\";\n";
1108 // End of the switch statement.
1110 // End of the getSpelling function.
1115 writePrettyPrintFunction(Record &R,
1116 const std::vector<std::unique_ptr<Argument>> &Args,
1118 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1120 OS << "void " << R.getName() << "Attr::printPretty("
1121 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1123 if (Spellings.empty()) {
1129 " switch (SpellingListIndex) {\n"
1131 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1134 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1135 llvm::SmallString<16> Prefix;
1136 llvm::SmallString<8> Suffix;
1137 // The actual spelling of the name and namespace (if applicable)
1138 // of an attribute without considering prefix and suffix.
1139 llvm::SmallString<64> Spelling;
1140 std::string Name = Spellings[I].name();
1141 std::string Variety = Spellings[I].variety();
1143 if (Variety == "GNU") {
1144 Prefix = " __attribute__((";
1146 } else if (Variety == "CXX11") {
1149 std::string Namespace = Spellings[I].nameSpace();
1150 if (!Namespace.empty()) {
1151 Spelling += Namespace;
1154 } else if (Variety == "Declspec") {
1155 Prefix = " __declspec(";
1157 } else if (Variety == "Keyword") {
1160 } else if (Variety == "Pragma") {
1161 Prefix = "#pragma ";
1163 std::string Namespace = Spellings[I].nameSpace();
1164 if (!Namespace.empty()) {
1165 Spelling += Namespace;
1169 llvm_unreachable("Unknown attribute syntax variety!");
1175 " case " << I << " : {\n"
1176 " OS << \"" << Prefix << Spelling;
1178 if (Variety == "Pragma") {
1180 OS << " printPrettyPragma(OS, Policy);\n";
1186 // FIXME: always printing the parenthesis isn't the correct behavior for
1187 // attributes which have optional arguments that were not provided. For
1188 // instance: __attribute__((aligned)) will be pretty printed as
1189 // __attribute__((aligned())). The logic should check whether there is only
1190 // a single argument, and if it is optional, whether it has been provided.
1193 if (Spelling == "availability") {
1194 writeAvailabilityValue(OS);
1196 for (auto I = Args.begin(), E = Args.end(); I != E; ++ I) {
1197 if (I != Args.begin()) OS << ", ";
1198 (*I)->writeValue(OS);
1204 OS << Suffix + "\";\n";
1211 // End of the switch statement.
1213 // End of the print function.
1217 /// \brief Return the index of a spelling in a spelling list.
1219 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1220 const FlattenedSpelling &Spelling) {
1221 assert(!SpellingList.empty() && "Spelling list is empty!");
1223 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1224 const FlattenedSpelling &S = SpellingList[Index];
1225 if (S.variety() != Spelling.variety())
1227 if (S.nameSpace() != Spelling.nameSpace())
1229 if (S.name() != Spelling.name())
1235 llvm_unreachable("Unknown spelling!");
1238 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1239 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1240 for (const auto *Accessor : Accessors) {
1241 std::string Name = Accessor->getValueAsString("Name");
1242 std::vector<FlattenedSpelling> Spellings =
1243 GetFlattenedSpellings(*Accessor);
1244 std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1245 assert(!SpellingList.empty() &&
1246 "Attribute with empty spelling list can't have accessors!");
1248 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1249 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1250 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1251 if (Index != Spellings.size() -1)
1252 OS << " ||\n SpellingListIndex == ";
1260 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1261 assert(!Spellings.empty() && "An empty list of spellings was provided");
1262 std::string FirstName = NormalizeNameForSpellingComparison(
1263 Spellings.front().name());
1264 for (const auto &Spelling :
1265 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1266 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1267 if (Name != FirstName)
1273 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1275 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1276 SemanticSpellingMap &Map) {
1277 // The enumerants are automatically generated based on the variety,
1278 // namespace (if present) and name for each attribute spelling. However,
1279 // care is taken to avoid trampling on the reserved namespace due to
1281 std::string Ret(" enum Spelling {\n");
1282 std::set<std::string> Uniques;
1284 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1285 const FlattenedSpelling &S = *I;
1286 std::string Variety = S.variety();
1287 std::string Spelling = S.name();
1288 std::string Namespace = S.nameSpace();
1289 std::string EnumName = "";
1291 EnumName += (Variety + "_");
1292 if (!Namespace.empty())
1293 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1295 EnumName += NormalizeNameForSpellingComparison(Spelling);
1297 // Even if the name is not unique, this spelling index corresponds to a
1298 // particular enumerant name that we've calculated.
1299 Map[Idx] = EnumName;
1301 // Since we have been stripping underscores to avoid trampling on the
1302 // reserved namespace, we may have inadvertently created duplicate
1303 // enumerant names. These duplicates are not considered part of the
1304 // semantic spelling, and can be elided.
1305 if (Uniques.find(EnumName) != Uniques.end())
1308 Uniques.insert(EnumName);
1309 if (I != Spellings.begin())
1311 // Duplicate spellings are not considered part of the semantic spelling
1312 // enumeration, but the spelling index and semantic spelling values are
1313 // meant to be equivalent, so we must specify a concrete value for each
1315 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1321 void WriteSemanticSpellingSwitch(const std::string &VarName,
1322 const SemanticSpellingMap &Map,
1324 OS << " switch (" << VarName << ") {\n default: "
1325 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1326 for (const auto &I : Map)
1327 OS << " case " << I.first << ": return " << I.second << ";\n";
1331 // Emits the LateParsed property for attributes.
1332 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1333 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1334 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1336 for (const auto *Attr : Attrs) {
1337 bool LateParsed = Attr->getValueAsBit("LateParsed");
1340 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1342 // FIXME: Handle non-GNU attributes
1343 for (const auto &I : Spellings) {
1344 if (I.variety() != "GNU")
1346 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1350 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1353 /// \brief Emits the first-argument-is-type property for attributes.
1354 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1355 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1356 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1358 for (const auto *Attr : Attrs) {
1359 // Determine whether the first argument is a type.
1360 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1364 if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
1367 // All these spellings take a single type argument.
1368 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1369 std::set<std::string> Emitted;
1370 for (const auto &S : Spellings) {
1371 if (Emitted.insert(S.name()).second)
1372 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1375 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1378 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1380 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1381 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1382 ParsedAttrMap Attrs = getParsedAttrList(Records);
1383 for (const auto &I : Attrs) {
1384 const Record &Attr = *I.second;
1386 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1389 // All these spellings take are parsed unevaluated.
1390 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1391 std::set<std::string> Emitted;
1392 for (const auto &S : Spellings) {
1393 if (Emitted.insert(S.name()).second)
1394 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1397 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1400 static bool isIdentifierArgument(Record *Arg) {
1401 return !Arg->getSuperClasses().empty() &&
1402 llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
1403 .Case("IdentifierArgument", true)
1404 .Case("EnumArgument", true)
1405 .Case("VariadicEnumArgument", true)
1409 // Emits the first-argument-is-identifier property for attributes.
1410 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1411 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1412 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1414 for (const auto *Attr : Attrs) {
1415 // Determine whether the first argument is an identifier.
1416 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1417 if (Args.empty() || !isIdentifierArgument(Args[0]))
1420 // All these spellings take an identifier argument.
1421 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1422 std::set<std::string> Emitted;
1423 for (const auto &S : Spellings) {
1424 if (Emitted.insert(S.name()).second)
1425 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1428 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1433 // Emits the class definitions for attributes.
1434 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1435 emitSourceFileHeader("Attribute classes' definitions", OS);
1437 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1438 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1440 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1442 for (const auto *Attr : Attrs) {
1443 const Record &R = *Attr;
1445 // FIXME: Currently, documentation is generated as-needed due to the fact
1446 // that there is no way to allow a generated project "reach into" the docs
1447 // directory (for instance, it may be an out-of-tree build). However, we want
1448 // to ensure that every attribute has a Documentation field, and produce an
1449 // error if it has been neglected. Otherwise, the on-demand generation which
1450 // happens server-side will fail. This code is ensuring that functionality,
1451 // even though this Emitter doesn't technically need the documentation.
1452 // When attribute documentation can be generated as part of the build
1453 // itself, this code can be removed.
1454 (void)R.getValueAsListOfDefs("Documentation");
1456 if (!R.getValueAsBit("ASTNode"))
1459 const std::vector<Record *> Supers = R.getSuperClasses();
1460 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1461 std::string SuperName;
1462 for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
1463 const Record &R = *Super;
1464 if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
1465 SuperName = R.getName();
1468 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1470 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1471 std::vector<std::unique_ptr<Argument>> Args;
1472 Args.reserve(ArgRecords.size());
1474 for (const auto *ArgRecord : ArgRecords) {
1475 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1476 Args.back()->writeDeclarations(OS);
1480 OS << "\npublic:\n";
1482 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1484 // If there are zero or one spellings, all spelling-related functionality
1485 // can be elided. If all of the spellings share the same name, the spelling
1486 // functionality can also be elided.
1487 bool ElideSpelling = (Spellings.size() <= 1) ||
1488 SpellingNamesAreCommon(Spellings);
1490 // This maps spelling index values to semantic Spelling enumerants.
1491 SemanticSpellingMap SemanticToSyntacticMap;
1494 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1496 OS << " static " << R.getName() << "Attr *CreateImplicit(";
1497 OS << "ASTContext &Ctx";
1499 OS << ", Spelling S";
1500 for (auto const &ai : Args) {
1502 ai->writeCtorParameters(OS);
1504 OS << ", SourceRange Loc = SourceRange()";
1506 OS << " " << R.getName() << "Attr *A = new (Ctx) " << R.getName();
1507 OS << "Attr(Loc, Ctx, ";
1508 for (auto const &ai : Args) {
1509 ai->writeImplicitCtorArgs(OS);
1512 OS << (ElideSpelling ? "0" : "S") << ");\n";
1513 OS << " A->setImplicit(true);\n";
1514 OS << " return A;\n }\n\n";
1516 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1518 bool HasOpt = false;
1519 for (auto const &ai : Args) {
1521 ai->writeCtorParameters(OS);
1523 if (ai->isOptional())
1528 OS << "unsigned SI\n";
1531 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1532 << R.getValueAsBit("LateParsed") << ", "
1533 << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
1535 for (auto const &ai : Args) {
1537 ai->writeCtorInitializers(OS);
1543 for (auto const &ai : Args) {
1544 ai->writeCtorBody(OS);
1549 // If there are optional arguments, write out a constructor that elides the
1550 // optional arguments as well.
1552 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1553 for (auto const &ai : Args) {
1554 if (!ai->isOptional()) {
1556 ai->writeCtorParameters(OS);
1562 OS << "unsigned SI\n";
1565 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1566 << R.getValueAsBit("LateParsed") << ", "
1567 << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
1569 for (auto const &ai : Args) {
1571 ai->writeCtorDefaultInitializers(OS);
1577 for (auto const &ai : Args) {
1578 if (!ai->isOptional()) {
1579 ai->writeCtorBody(OS);
1586 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
1587 OS << " void printPretty(raw_ostream &OS,\n"
1588 << " const PrintingPolicy &Policy) const;\n";
1589 OS << " const char *getSpelling() const;\n";
1591 if (!ElideSpelling) {
1592 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1593 OS << " Spelling getSemanticSpelling() const {\n";
1594 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1599 writeAttrAccessorDefinition(R, OS);
1601 for (auto const &ai : Args) {
1602 ai->writeAccessors(OS);
1605 if (ai->isEnumArg())
1606 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1607 else if (ai->isVariadicEnumArg())
1608 static_cast<const VariadicEnumArgument *>(ai.get())
1609 ->writeConversion(OS);
1612 OS << R.getValueAsString("AdditionalMembers");
1615 OS << " static bool classof(const Attr *A) { return A->getKind() == "
1616 << "attr::" << R.getName() << "; }\n";
1624 // Emits the class method definitions for attributes.
1625 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1626 emitSourceFileHeader("Attribute classes' member function definitions", OS);
1628 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1630 for (auto *Attr : Attrs) {
1633 if (!R.getValueAsBit("ASTNode"))
1636 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1637 std::vector<std::unique_ptr<Argument>> Args;
1638 for (const auto *Arg : ArgRecords)
1639 Args.emplace_back(createArgument(*Arg, R.getName()));
1641 for (auto const &ai : Args)
1642 ai->writeAccessorDefinitions(OS);
1644 OS << R.getName() << "Attr *" << R.getName()
1645 << "Attr::clone(ASTContext &C) const {\n";
1646 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
1647 for (auto const &ai : Args) {
1649 ai->writeCloneArgs(OS);
1651 OS << ", getSpellingListIndex());\n";
1652 OS << " A->Inherited = Inherited;\n";
1653 OS << " A->IsPackExpansion = IsPackExpansion;\n";
1654 OS << " A->Implicit = Implicit;\n";
1655 OS << " return A;\n}\n\n";
1657 writePrettyPrintFunction(R, Args, OS);
1658 writeGetSpellingFunction(R, OS);
1661 // Instead of relying on virtual dispatch we just create a huge dispatch
1662 // switch. This is both smaller and faster than virtual functions.
1663 auto EmitFunc = [&](const char *Method) {
1664 OS << " switch (getKind()) {\n";
1665 for (const auto *Attr : Attrs) {
1666 const Record &R = *Attr;
1667 if (!R.getValueAsBit("ASTNode"))
1670 OS << " case attr::" << R.getName() << ":\n";
1671 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
1674 OS << " case attr::NUM_ATTRS:\n";
1677 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
1681 OS << "const char *Attr::getSpelling() const {\n";
1682 EmitFunc("getSpelling()");
1684 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
1685 EmitFunc("clone(C)");
1687 OS << "void Attr::printPretty(raw_ostream &OS, "
1688 "const PrintingPolicy &Policy) const {\n";
1689 EmitFunc("printPretty(OS, Policy)");
1692 } // end namespace clang
1694 static void EmitAttrList(raw_ostream &OS, StringRef Class,
1695 const std::vector<Record*> &AttrList) {
1696 std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end();
1699 // Move the end iterator back to emit the last attribute.
1700 for(--e; i != e; ++i) {
1701 if (!(*i)->getValueAsBit("ASTNode"))
1704 OS << Class << "(" << (*i)->getName() << ")\n";
1707 OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
1711 // Determines if an attribute has a Pragma spelling.
1712 static bool AttrHasPragmaSpelling(const Record *R) {
1713 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1714 return std::find_if(Spellings.begin(), Spellings.end(),
1715 [](const FlattenedSpelling &S) {
1716 return S.variety() == "Pragma";
1717 }) != Spellings.end();
1721 // Emits the enumeration list for attributes.
1722 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
1723 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
1725 OS << "#ifndef LAST_ATTR\n";
1726 OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
1729 OS << "#ifndef INHERITABLE_ATTR\n";
1730 OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
1733 OS << "#ifndef LAST_INHERITABLE_ATTR\n";
1734 OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
1737 OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
1738 OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
1741 OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
1742 OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
1743 " INHERITABLE_PARAM_ATTR(NAME)\n";
1746 OS << "#ifndef PRAGMA_SPELLING_ATTR\n";
1747 OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n";
1750 OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n";
1751 OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n";
1754 Record *InhClass = Records.getClass("InheritableAttr");
1755 Record *InhParamClass = Records.getClass("InheritableParamAttr");
1756 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"),
1757 NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs;
1758 for (auto *Attr : Attrs) {
1759 if (!Attr->getValueAsBit("ASTNode"))
1762 if (AttrHasPragmaSpelling(Attr))
1763 PragmaAttrs.push_back(Attr);
1765 if (Attr->isSubClassOf(InhParamClass))
1766 InhParamAttrs.push_back(Attr);
1767 else if (Attr->isSubClassOf(InhClass))
1768 InhAttrs.push_back(Attr);
1770 NonInhAttrs.push_back(Attr);
1773 EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
1774 EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
1775 EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
1776 EmitAttrList(OS, "ATTR", NonInhAttrs);
1778 OS << "#undef LAST_ATTR\n";
1779 OS << "#undef INHERITABLE_ATTR\n";
1780 OS << "#undef LAST_INHERITABLE_ATTR\n";
1781 OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
1782 OS << "#undef LAST_PRAGMA_ATTR\n";
1783 OS << "#undef PRAGMA_SPELLING_ATTR\n";
1784 OS << "#undef ATTR\n";
1787 // Emits the code to read an attribute from a precompiled header.
1788 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
1789 emitSourceFileHeader("Attribute deserialization code", OS);
1791 Record *InhClass = Records.getClass("InheritableAttr");
1792 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1794 std::vector<std::unique_ptr<Argument>> Args;
1796 OS << " switch (Kind) {\n";
1797 OS << " default:\n";
1798 OS << " llvm_unreachable(\"Unknown attribute!\");\n";
1799 for (const auto *Attr : Attrs) {
1800 const Record &R = *Attr;
1801 if (!R.getValueAsBit("ASTNode"))
1804 OS << " case attr::" << R.getName() << ": {\n";
1805 if (R.isSubClassOf(InhClass))
1806 OS << " bool isInherited = Record[Idx++];\n";
1807 OS << " bool isImplicit = Record[Idx++];\n";
1808 OS << " unsigned Spelling = Record[Idx++];\n";
1809 ArgRecords = R.getValueAsListOfDefs("Args");
1811 for (const auto *Arg : ArgRecords) {
1812 Args.emplace_back(createArgument(*Arg, R.getName()));
1813 Args.back()->writePCHReadDecls(OS);
1815 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
1816 for (auto const &ri : Args) {
1818 ri->writePCHReadArgs(OS);
1820 OS << ", Spelling);\n";
1821 if (R.isSubClassOf(InhClass))
1822 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
1823 OS << " New->setImplicit(isImplicit);\n";
1830 // Emits the code to write an attribute to a precompiled header.
1831 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
1832 emitSourceFileHeader("Attribute serialization code", OS);
1834 Record *InhClass = Records.getClass("InheritableAttr");
1835 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
1837 OS << " switch (A->getKind()) {\n";
1838 OS << " default:\n";
1839 OS << " llvm_unreachable(\"Unknown attribute kind!\");\n";
1841 for (const auto *Attr : Attrs) {
1842 const Record &R = *Attr;
1843 if (!R.getValueAsBit("ASTNode"))
1845 OS << " case attr::" << R.getName() << ": {\n";
1846 Args = R.getValueAsListOfDefs("Args");
1847 if (R.isSubClassOf(InhClass) || !Args.empty())
1848 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
1850 if (R.isSubClassOf(InhClass))
1851 OS << " Record.push_back(SA->isInherited());\n";
1852 OS << " Record.push_back(A->isImplicit());\n";
1853 OS << " Record.push_back(A->getSpellingListIndex());\n";
1855 for (const auto *Arg : Args)
1856 createArgument(*Arg, R.getName())->writePCHWrite(OS);
1863 static void GenerateHasAttrSpellingStringSwitch(
1864 const std::vector<Record *> &Attrs, raw_ostream &OS,
1865 const std::string &Variety = "", const std::string &Scope = "") {
1866 for (const auto *Attr : Attrs) {
1867 // C++11-style attributes have specific version information associated with
1868 // them. If the attribute has no scope, the version information must not
1869 // have the default value (1), as that's incorrect. Instead, the unscoped
1870 // attribute version information should be taken from the SD-6 standing
1871 // document, which can be found at:
1872 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
1875 if (Variety == "CXX11") {
1876 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
1877 for (const auto &Spelling : Spellings) {
1878 if (Spelling->getValueAsString("Variety") == "CXX11") {
1879 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
1880 if (Scope.empty() && Version == 1)
1881 PrintError(Spelling->getLoc(), "C++ standard attributes must "
1882 "have valid version information.");
1888 // It is assumed that there will be an llvm::Triple object named T within
1889 // scope that can be used to determine whether the attribute exists in
1892 if (Attr->isSubClassOf("TargetSpecificAttr")) {
1893 const Record *R = Attr->getValueAsDef("Target");
1894 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
1897 for (auto AI = Arches.begin(), AE = Arches.end(); AI != AE; ++AI) {
1898 std::string Part = *AI;
1899 Test += "T.getArch() == llvm::Triple::" + Part;
1905 std::vector<std::string> OSes;
1906 if (!R->isValueUnset("OSes")) {
1908 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
1909 for (auto AI = OSes.begin(), AE = OSes.end(); AI != AE; ++AI) {
1910 std::string Part = *AI;
1912 Test += "T.getOS() == llvm::Triple::" + Part;
1919 // If this is the C++11 variety, also add in the LangOpts test.
1920 if (Variety == "CXX11")
1921 Test += " && LangOpts.CPlusPlus11";
1922 } else if (Variety == "CXX11")
1923 // C++11 mode should be checked against LangOpts, which is presumed to be
1924 // present in the caller.
1925 Test = "LangOpts.CPlusPlus11";
1927 std::string TestStr =
1928 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
1929 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1930 for (const auto &S : Spellings)
1931 if (Variety.empty() || (Variety == S.variety() &&
1932 (Scope.empty() || Scope == S.nameSpace())))
1933 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
1935 OS << " .Default(0);\n";
1938 // Emits the list of spellings for attributes.
1939 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1940 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
1942 // Separate all of the attributes out into four group: generic, C++11, GNU,
1943 // and declspecs. Then generate a big switch statement for each of them.
1944 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1945 std::vector<Record *> Declspec, GNU, Pragma;
1946 std::map<std::string, std::vector<Record *>> CXX;
1948 // Walk over the list of all attributes, and split them out based on the
1949 // spelling variety.
1950 for (auto *R : Attrs) {
1951 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1952 for (const auto &SI : Spellings) {
1953 std::string Variety = SI.variety();
1954 if (Variety == "GNU")
1956 else if (Variety == "Declspec")
1957 Declspec.push_back(R);
1958 else if (Variety == "CXX11")
1959 CXX[SI.nameSpace()].push_back(R);
1960 else if (Variety == "Pragma")
1961 Pragma.push_back(R);
1965 OS << "switch (Syntax) {\n";
1966 OS << "case AttrSyntax::GNU:\n";
1967 OS << " return llvm::StringSwitch<int>(Name)\n";
1968 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
1969 OS << "case AttrSyntax::Declspec:\n";
1970 OS << " return llvm::StringSwitch<int>(Name)\n";
1971 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
1972 OS << "case AttrSyntax::Pragma:\n";
1973 OS << " return llvm::StringSwitch<int>(Name)\n";
1974 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
1975 OS << "case AttrSyntax::CXX: {\n";
1976 // C++11-style attributes are further split out based on the Scope.
1977 for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(),
1980 if (I != CXX.begin())
1982 if (I->first.empty())
1983 OS << "if (!Scope || Scope->getName() == \"\") {\n";
1985 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
1986 OS << " return llvm::StringSwitch<int>(Name)\n";
1987 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
1994 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
1995 emitSourceFileHeader("Code to translate different attribute spellings "
1996 "into internal identifiers", OS);
1999 " switch (AttrKind) {\n"
2001 " llvm_unreachable(\"Unknown attribute kind!\");\n"
2004 ParsedAttrMap Attrs = getParsedAttrList(Records);
2005 for (const auto &I : Attrs) {
2006 const Record &R = *I.second;
2007 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2008 OS << " case AT_" << I.first << ": {\n";
2009 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2010 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2012 << StringSwitch<unsigned>(Spellings[I].variety())
2015 .Case("Declspec", 2)
2019 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2020 << " return " << I << ";\n";
2028 OS << " return 0;\n";
2031 // Emits code used by RecursiveASTVisitor to visit attributes
2032 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2033 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2035 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2037 // Write method declarations for Traverse* methods.
2038 // We emit this here because we only generate methods for attributes that
2039 // are declared as ASTNodes.
2040 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2041 for (const auto *Attr : Attrs) {
2042 const Record &R = *Attr;
2043 if (!R.getValueAsBit("ASTNode"))
2045 OS << " bool Traverse"
2046 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2048 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2049 << " return true; \n"
2052 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2054 // Write individual Traverse* methods for each attribute class.
2055 for (const auto *Attr : Attrs) {
2056 const Record &R = *Attr;
2057 if (!R.getValueAsBit("ASTNode"))
2060 OS << "template <typename Derived>\n"
2061 << "bool VISITORCLASS<Derived>::Traverse"
2062 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2063 << " if (!getDerived().VisitAttr(A))\n"
2064 << " return false;\n"
2065 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2066 << " return false;\n";
2068 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2069 for (const auto *Arg : ArgRecords)
2070 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
2072 OS << " return true;\n";
2076 // Write generic Traverse routine
2077 OS << "template <typename Derived>\n"
2078 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
2080 << " return true;\n"
2082 << " switch (A->getKind()) {\n"
2084 << " return true;\n";
2086 for (const auto *Attr : Attrs) {
2087 const Record &R = *Attr;
2088 if (!R.getValueAsBit("ASTNode"))
2091 OS << " case attr::" << R.getName() << ":\n"
2092 << " return getDerived().Traverse" << R.getName() << "Attr("
2093 << "cast<" << R.getName() << "Attr>(A));\n";
2095 OS << " }\n"; // end case
2096 OS << "}\n"; // end function
2097 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
2100 // Emits code to instantiate dependent attributes on templates.
2101 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
2102 emitSourceFileHeader("Template instantiation code for attributes", OS);
2104 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2106 OS << "namespace clang {\n"
2107 << "namespace sema {\n\n"
2108 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
2110 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
2111 << " switch (At->getKind()) {\n"
2115 for (const auto *Attr : Attrs) {
2116 const Record &R = *Attr;
2117 if (!R.getValueAsBit("ASTNode"))
2120 OS << " case attr::" << R.getName() << ": {\n";
2121 bool ShouldClone = R.getValueAsBit("Clone");
2124 OS << " return NULL;\n";
2129 OS << " const " << R.getName() << "Attr *A = cast<"
2130 << R.getName() << "Attr>(At);\n";
2131 bool TDependent = R.getValueAsBit("TemplateDependent");
2134 OS << " return A->clone(C);\n";
2139 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2140 std::vector<std::unique_ptr<Argument>> Args;
2141 Args.reserve(ArgRecords.size());
2143 for (const auto *ArgRecord : ArgRecords)
2144 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2146 for (auto const &ai : Args)
2147 ai->writeTemplateInstantiation(OS);
2149 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2150 for (auto const &ai : Args) {
2152 ai->writeTemplateInstantiationArgs(OS);
2154 OS << ", A->getSpellingListIndex());\n }\n";
2156 OS << " } // end switch\n"
2157 << " llvm_unreachable(\"Unknown attribute!\");\n"
2160 << "} // end namespace sema\n"
2161 << "} // end namespace clang\n";
2164 // Emits the list of parsed attributes.
2165 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2166 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2168 OS << "#ifndef PARSED_ATTR\n";
2169 OS << "#define PARSED_ATTR(NAME) NAME\n";
2172 ParsedAttrMap Names = getParsedAttrList(Records);
2173 for (const auto &I : Names) {
2174 OS << "PARSED_ATTR(" << I.first << ")\n";
2178 static bool isArgVariadic(const Record &R, StringRef AttrName) {
2179 return createArgument(R, AttrName)->isVariadic();
2182 static void emitArgInfo(const Record &R, std::stringstream &OS) {
2183 // This function will count the number of arguments specified for the
2184 // attribute and emit the number of required arguments followed by the
2185 // number of optional arguments.
2186 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
2187 unsigned ArgCount = 0, OptCount = 0;
2188 bool HasVariadic = false;
2189 for (const auto *Arg : Args) {
2190 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
2191 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
2195 // If there is a variadic argument, we will set the optional argument count
2196 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
2197 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
2200 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
2201 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
2202 OS << "const Decl *) {\n";
2203 OS << " return true;\n";
2207 static std::string CalculateDiagnostic(const Record &S) {
2208 // If the SubjectList object has a custom diagnostic associated with it,
2209 // return that directly.
2210 std::string CustomDiag = S.getValueAsString("CustomDiag");
2211 if (!CustomDiag.empty())
2214 // Given the list of subjects, determine what diagnostic best fits.
2218 ObjCMethod = 1U << 2,
2221 GenericRecord = 1U << 5,
2225 ObjCInterface = 1U << 9,
2227 Namespace = 1U << 11,
2229 CXXMethod = 1U << 13,
2230 ObjCProtocol = 1U << 14,
2233 uint32_t SubMask = 0;
2235 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2236 for (const auto *Subject : Subjects) {
2237 const Record &R = *Subject;
2240 if (R.isSubClassOf("SubsetSubject")) {
2241 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2242 // As a fallback, look through the SubsetSubject to see what its base
2243 // type is, and use that. This needs to be updated if SubsetSubjects
2244 // are allowed within other SubsetSubjects.
2245 Name = R.getValueAsDef("Base")->getName();
2249 uint32_t V = StringSwitch<uint32_t>(Name)
2250 .Case("Function", Func)
2252 .Case("ObjCMethod", ObjCMethod)
2253 .Case("ParmVar", Param)
2254 .Case("TypedefName", Type)
2255 .Case("ObjCIvar", ObjCIVar)
2256 .Case("ObjCProperty", ObjCProp)
2257 .Case("Record", GenericRecord)
2258 .Case("ObjCInterface", ObjCInterface)
2259 .Case("ObjCProtocol", ObjCProtocol)
2260 .Case("Block", Block)
2261 .Case("CXXRecord", Class)
2262 .Case("Namespace", Namespace)
2263 .Case("Field", Field)
2264 .Case("CXXMethod", CXXMethod)
2268 // Something wasn't in our mapping, so be helpful and let the developer
2270 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2278 // For the simple cases where there's only a single entry in the mask, we
2279 // don't have to resort to bit fiddling.
2280 case Func: return "ExpectedFunction";
2281 case Var: return "ExpectedVariable";
2282 case Param: return "ExpectedParameter";
2283 case Class: return "ExpectedClass";
2284 case Enum: return "ExpectedEnum";
2286 // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2287 // but should map to something a bit more accurate at some point.
2288 case ObjCMethod: return "ExpectedMethod";
2289 case Type: return "ExpectedType";
2290 case ObjCInterface: return "ExpectedObjectiveCInterface";
2291 case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2293 // "GenericRecord" means struct, union or class; check the language options
2294 // and if not compiling for C++, strip off the class part. Note that this
2295 // relies on the fact that the context for this declares "Sema &S".
2297 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2298 "ExpectedStructOrUnion)";
2299 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2300 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2302 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2303 case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2304 case Func | Var: return "ExpectedVariableOrFunction";
2306 // If not compiling for C++, the class portion does not apply.
2307 case Func | Var | Class:
2308 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2309 "ExpectedVariableOrFunction)";
2311 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2312 case ObjCProtocol | ObjCInterface:
2313 return "ExpectedObjectiveCInterfaceOrProtocol";
2314 case Field | Var: return "ExpectedFieldOrGlobalVar";
2317 PrintFatalError(S.getLoc(),
2318 "Could not deduce diagnostic argument for Attr subjects");
2323 static std::string GetSubjectWithSuffix(const Record *R) {
2324 std::string B = R->getName();
2325 if (B == "DeclBase")
2329 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2331 std::string FnName = "is" + Subject.getName();
2333 // If this code has already been generated, simply return the previous
2335 static std::set<std::string> CustomSubjectSet;
2336 std::set<std::string>::iterator I = CustomSubjectSet.find(FnName);
2337 if (I != CustomSubjectSet.end())
2340 Record *Base = Subject.getValueAsDef("Base");
2342 // Not currently support custom subjects within custom subjects.
2343 if (Base->isSubClassOf("SubsetSubject")) {
2344 PrintFatalError(Subject.getLoc(),
2345 "SubsetSubjects within SubsetSubjects is not supported");
2349 OS << "static bool " << FnName << "(const Decl *D) {\n";
2350 OS << " if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<";
2351 OS << GetSubjectWithSuffix(Base);
2353 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
2354 OS << " return false;\n";
2357 CustomSubjectSet.insert(FnName);
2361 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2362 // If the attribute does not contain a Subjects definition, then use the
2363 // default appertainsTo logic.
2364 if (Attr.isValueUnset("Subjects"))
2365 return "defaultAppertainsTo";
2367 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2368 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2370 // If the list of subjects is empty, it is assumed that the attribute
2371 // appertains to everything.
2372 if (Subjects.empty())
2373 return "defaultAppertainsTo";
2375 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2377 // Otherwise, generate an appertainsTo check specific to this attribute which
2378 // checks all of the given subjects against the Decl passed in. Return the
2379 // name of that check to the caller.
2380 std::string FnName = "check" + Attr.getName() + "AppertainsTo";
2381 std::stringstream SS;
2382 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2383 SS << "const Decl *D) {\n";
2385 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2386 // If the subject has custom code associated with it, generate a function
2387 // for it. The function cannot be inlined into this check (yet) because it
2388 // requires the subject to be of a specific type, and were that information
2389 // inlined here, it would not support an attribute with multiple custom
2391 if ((*I)->isSubClassOf("SubsetSubject")) {
2392 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2394 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2401 SS << " S.Diag(Attr.getLoc(), diag::";
2402 SS << (Warn ? "warn_attribute_wrong_decl_type" :
2403 "err_attribute_wrong_decl_type");
2405 SS << " << Attr.getName() << ";
2406 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2407 SS << " return false;\n";
2409 SS << " return true;\n";
2416 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2417 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2418 OS << "const AttributeList &) {\n";
2419 OS << " return true;\n";
2423 static std::string GenerateLangOptRequirements(const Record &R,
2425 // If the attribute has an empty or unset list of language requirements,
2426 // return the default handler.
2427 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2428 if (LangOpts.empty())
2429 return "defaultDiagnoseLangOpts";
2431 // Generate the test condition, as well as a unique function name for the
2432 // diagnostic test. The list of options should usually be short (one or two
2433 // options), and the uniqueness isn't strictly necessary (it is just for
2434 // codegen efficiency).
2435 std::string FnName = "check", Test;
2436 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2437 std::string Part = (*I)->getValueAsString("Name");
2438 if ((*I)->getValueAsBit("Negated"))
2440 Test += "S.LangOpts." + Part;
2445 FnName += "LangOpts";
2447 // If this code has already been generated, simply return the previous
2449 static std::set<std::string> CustomLangOptsSet;
2450 std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName);
2451 if (I != CustomLangOptsSet.end())
2454 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2455 OS << " if (" << Test << ")\n";
2456 OS << " return true;\n\n";
2457 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2458 OS << "<< Attr.getName();\n";
2459 OS << " return false;\n";
2462 CustomLangOptsSet.insert(FnName);
2466 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2467 OS << "static bool defaultTargetRequirements(const llvm::Triple &) {\n";
2468 OS << " return true;\n";
2472 static std::string GenerateTargetRequirements(const Record &Attr,
2473 const ParsedAttrMap &Dupes,
2475 // If the attribute is not a target specific attribute, return the default
2477 if (!Attr.isSubClassOf("TargetSpecificAttr"))
2478 return "defaultTargetRequirements";
2480 // Get the list of architectures to be tested for.
2481 const Record *R = Attr.getValueAsDef("Target");
2482 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2483 if (Arches.empty()) {
2484 PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2485 "target-specific attr");
2486 return "defaultTargetRequirements";
2489 // If there are other attributes which share the same parsed attribute kind,
2490 // such as target-specific attributes with a shared spelling, collapse the
2491 // duplicate architectures. This is required because a shared target-specific
2492 // attribute has only one AttributeList::Kind enumeration value, but it
2493 // applies to multiple target architectures. In order for the attribute to be
2494 // considered valid, all of its architectures need to be included.
2495 if (!Attr.isValueUnset("ParseKind")) {
2496 std::string APK = Attr.getValueAsString("ParseKind");
2497 for (const auto &I : Dupes) {
2498 if (I.first == APK) {
2499 std::vector<std::string> DA = I.second->getValueAsDef("Target")
2500 ->getValueAsListOfStrings("Arches");
2501 std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
2506 std::string FnName = "isTarget", Test = "(";
2507 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2508 std::string Part = *I;
2509 Test += "Arch == llvm::Triple::" + Part;
2516 // If the target also requires OS testing, generate those tests as well.
2517 bool UsesOS = false;
2518 if (!R->isValueUnset("OSes")) {
2521 // We know that there was at least one arch test, so we need to and in the
2524 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
2525 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
2526 std::string Part = *I;
2528 Test += "OS == llvm::Triple::" + Part;
2536 // If this code has already been generated, simply return the previous
2538 static std::set<std::string> CustomTargetSet;
2539 std::set<std::string>::iterator I = CustomTargetSet.find(FnName);
2540 if (I != CustomTargetSet.end())
2543 OS << "static bool " << FnName << "(const llvm::Triple &T) {\n";
2544 OS << " llvm::Triple::ArchType Arch = T.getArch();\n";
2546 OS << " llvm::Triple::OSType OS = T.getOS();\n";
2547 OS << " return " << Test << ";\n";
2550 CustomTargetSet.insert(FnName);
2554 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2555 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2556 << "const AttributeList &Attr) {\n";
2557 OS << " return UINT_MAX;\n";
2561 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2563 // If the attribute does not have a semantic form, we can bail out early.
2564 if (!Attr.getValueAsBit("ASTNode"))
2565 return "defaultSpellingIndexToSemanticSpelling";
2567 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2569 // If there are zero or one spellings, or all of the spellings share the same
2570 // name, we can also bail out early.
2571 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2572 return "defaultSpellingIndexToSemanticSpelling";
2574 // Generate the enumeration we will use for the mapping.
2575 SemanticSpellingMap SemanticToSyntacticMap;
2576 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2577 std::string Name = Attr.getName() + "AttrSpellingMap";
2579 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2581 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2582 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2588 static bool IsKnownToGCC(const Record &Attr) {
2589 // Look at the spellings for this subject; if there are any spellings which
2590 // claim to be known to GCC, the attribute is known to GCC.
2591 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2592 for (const auto &I : Spellings) {
2599 /// Emits the parsed attribute helpers
2600 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2601 emitSourceFileHeader("Parsed attribute helpers", OS);
2603 // Get the list of parsed attributes, and accept the optional list of
2604 // duplicates due to the ParseKind.
2605 ParsedAttrMap Dupes;
2606 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2608 // Generate the default appertainsTo, target and language option diagnostic,
2609 // and spelling list index mapping methods.
2610 GenerateDefaultAppertainsTo(OS);
2611 GenerateDefaultLangOptRequirements(OS);
2612 GenerateDefaultTargetRequirements(OS);
2613 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2615 // Generate the appertainsTo diagnostic methods and write their names into
2616 // another mapping. At the same time, generate the AttrInfoMap object
2617 // contents. Due to the reliance on generated code, use separate streams so
2618 // that code will not be interleaved.
2619 std::stringstream SS;
2620 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2621 // TODO: If the attribute's kind appears in the list of duplicates, that is
2622 // because it is a target-specific attribute that appears multiple times.
2623 // It would be beneficial to test whether the duplicates are "similar
2624 // enough" to each other to not cause problems. For instance, check that
2625 // the spellings are identical, and custom parsing rules match, etc.
2627 // We need to generate struct instances based off ParsedAttrInfo from
2628 // AttributeList.cpp.
2630 emitArgInfo(*I->second, SS);
2631 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2632 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2633 SS << ", " << I->second->isSubClassOf("TypeAttr");
2634 SS << ", " << IsKnownToGCC(*I->second);
2635 SS << ", " << GenerateAppertainsTo(*I->second, OS);
2636 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2637 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2638 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2644 SS << " // AT_" << I->first << "\n";
2647 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2652 // Emits the kind list of parsed attributes
2653 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2654 emitSourceFileHeader("Attribute name matcher", OS);
2656 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2657 std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
2658 std::set<std::string> Seen;
2659 for (const auto *A : Attrs) {
2660 const Record &Attr = *A;
2662 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
2663 bool Ignored = Attr.getValueAsBit("Ignored");
2664 if (SemaHandler || Ignored) {
2665 // Attribute spellings can be shared between target-specific attributes,
2666 // and can be shared between syntaxes for the same attribute. For
2667 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
2668 // specific attribute, or MSP430-specific attribute. Additionally, an
2669 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
2670 // for the same semantic attribute. Ultimately, we need to map each of
2671 // these to a single AttributeList::Kind value, but the StringMatcher
2672 // class cannot handle duplicate match strings. So we generate a list of
2673 // string to match based on the syntax, and emit multiple string matchers
2674 // depending on the syntax used.
2675 std::string AttrName;
2676 if (Attr.isSubClassOf("TargetSpecificAttr") &&
2677 !Attr.isValueUnset("ParseKind")) {
2678 AttrName = Attr.getValueAsString("ParseKind");
2679 if (Seen.find(AttrName) != Seen.end())
2681 Seen.insert(AttrName);
2683 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
2685 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2686 for (const auto &S : Spellings) {
2687 std::string RawSpelling = S.name();
2688 std::vector<StringMatcher::StringPair> *Matches = nullptr;
2689 std::string Spelling, Variety = S.variety();
2690 if (Variety == "CXX11") {
2692 Spelling += S.nameSpace();
2694 } else if (Variety == "GNU")
2696 else if (Variety == "Declspec")
2697 Matches = &Declspec;
2698 else if (Variety == "Keyword")
2699 Matches = &Keywords;
2700 else if (Variety == "Pragma")
2703 assert(Matches && "Unsupported spelling variety found");
2705 Spelling += NormalizeAttrSpelling(RawSpelling);
2707 Matches->push_back(StringMatcher::StringPair(Spelling,
2708 "return AttributeList::AT_" + AttrName + ";"));
2710 Matches->push_back(StringMatcher::StringPair(Spelling,
2711 "return AttributeList::IgnoredAttribute;"));
2716 OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
2717 OS << "AttributeList::Syntax Syntax) {\n";
2718 OS << " if (AttributeList::AS_GNU == Syntax) {\n";
2719 StringMatcher("Name", GNU, OS).Emit();
2720 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
2721 StringMatcher("Name", Declspec, OS).Emit();
2722 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
2723 StringMatcher("Name", CXX11, OS).Emit();
2724 OS << " } else if (AttributeList::AS_Keyword == Syntax) {\n";
2725 StringMatcher("Name", Keywords, OS).Emit();
2726 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
2727 StringMatcher("Name", Pragma, OS).Emit();
2729 OS << " return AttributeList::UnknownAttribute;\n"
2733 // Emits the code to dump an attribute.
2734 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
2735 emitSourceFileHeader("Attribute dumper", OS);
2738 " switch (A->getKind()) {\n"
2740 " llvm_unreachable(\"Unknown attribute kind!\");\n"
2742 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2743 for (const auto *Attr : Attrs) {
2744 const Record &R = *Attr;
2745 if (!R.getValueAsBit("ASTNode"))
2747 OS << " case attr::" << R.getName() << ": {\n";
2749 // If the attribute has a semantically-meaningful name (which is determined
2750 // by whether there is a Spelling enumeration for it), then write out the
2751 // spelling used for the attribute.
2752 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2753 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
2754 OS << " OS << \" \" << A->getSpelling();\n";
2756 Args = R.getValueAsListOfDefs("Args");
2757 if (!Args.empty()) {
2758 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName()
2760 for (const auto *Arg : Args)
2761 createArgument(*Arg, R.getName())->writeDump(OS);
2763 for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI)
2764 createArgument(**AI, R.getName())->writeDumpChildren(OS);
2773 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
2775 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
2776 emitClangAttrArgContextList(Records, OS);
2777 emitClangAttrIdentifierArgList(Records, OS);
2778 emitClangAttrTypeArgList(Records, OS);
2779 emitClangAttrLateParsedList(Records, OS);
2782 class DocumentationData {
2784 const Record *Documentation;
2785 const Record *Attribute;
2787 DocumentationData(const Record &Documentation, const Record &Attribute)
2788 : Documentation(&Documentation), Attribute(&Attribute) {}
2791 static void WriteCategoryHeader(const Record *DocCategory,
2793 const std::string &Name = DocCategory->getValueAsString("Name");
2794 OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
2796 // If there is content, print that as well.
2797 std::string ContentStr = DocCategory->getValueAsString("Content");
2798 // Trim leading and trailing newlines and spaces.
2799 OS << StringRef(ContentStr).trim();
2812 static void WriteDocumentation(const DocumentationData &Doc,
2814 // FIXME: there is no way to have a per-spelling category for the attribute
2815 // documentation. This may not be a limiting factor since the spellings
2816 // should generally be consistently applied across the category.
2818 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
2820 // Determine the heading to be used for this attribute.
2821 std::string Heading = Doc.Documentation->getValueAsString("Heading");
2822 bool CustomHeading = !Heading.empty();
2823 if (Heading.empty()) {
2824 // If there's only one spelling, we can simply use that.
2825 if (Spellings.size() == 1)
2826 Heading = Spellings.begin()->name();
2828 std::set<std::string> Uniques;
2829 for (auto I = Spellings.begin(), E = Spellings.end();
2830 I != E && Uniques.size() <= 1; ++I) {
2831 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
2832 Uniques.insert(Spelling);
2834 // If the semantic map has only one spelling, that is sufficient for our
2836 if (Uniques.size() == 1)
2837 Heading = *Uniques.begin();
2841 // If the heading is still empty, it is an error.
2842 if (Heading.empty())
2843 PrintFatalError(Doc.Attribute->getLoc(),
2844 "This attribute requires a heading to be specified");
2846 // Gather a list of unique spellings; this is not the same as the semantic
2847 // spelling for the attribute. Variations in underscores and other non-
2848 // semantic characters are still acceptable.
2849 std::vector<std::string> Names;
2851 unsigned SupportedSpellings = 0;
2852 for (const auto &I : Spellings) {
2853 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
2855 .Case("CXX11", CXX11)
2856 .Case("Declspec", Declspec)
2857 .Case("Keyword", Keyword)
2858 .Case("Pragma", Pragma);
2860 // Mask in the supported spelling.
2861 SupportedSpellings |= Kind;
2864 if (Kind == CXX11 && !I.nameSpace().empty())
2865 Name = I.nameSpace() + "::";
2868 // If this name is the same as the heading, do not add it.
2869 if (Name != Heading)
2870 Names.push_back(Name);
2873 // Print out the heading for the attribute. If there are alternate spellings,
2874 // then display those after the heading.
2875 if (!CustomHeading && !Names.empty()) {
2877 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
2878 if (I != Names.begin())
2884 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
2886 if (!SupportedSpellings)
2887 PrintFatalError(Doc.Attribute->getLoc(),
2888 "Attribute has no supported spellings; cannot be "
2891 // List what spelling syntaxes the attribute supports.
2892 OS << ".. csv-table:: Supported Syntaxes\n";
2893 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
2894 OS << " \"Pragma\"\n\n";
2896 if (SupportedSpellings & GNU) OS << "X";
2898 if (SupportedSpellings & CXX11) OS << "X";
2900 if (SupportedSpellings & Declspec) OS << "X";
2902 if (SupportedSpellings & Keyword) OS << "X";
2904 if (SupportedSpellings & Pragma) OS << "X";
2907 // If the attribute is deprecated, print a message about it, and possibly
2908 // provide a replacement attribute.
2909 if (!Doc.Documentation->isValueUnset("Deprecated")) {
2910 OS << "This attribute has been deprecated, and may be removed in a future "
2911 << "version of Clang.";
2912 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
2913 std::string Replacement = Deprecated.getValueAsString("Replacement");
2914 if (!Replacement.empty())
2915 OS << " This attribute has been superseded by ``"
2916 << Replacement << "``.";
2920 std::string ContentStr = Doc.Documentation->getValueAsString("Content");
2921 // Trim leading and trailing newlines and spaces.
2922 OS << StringRef(ContentStr).trim();
2927 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
2928 // Get the documentation introduction paragraph.
2929 const Record *Documentation = Records.getDef("GlobalDocumentation");
2930 if (!Documentation) {
2931 PrintFatalError("The Documentation top-level definition is missing, "
2932 "no documentation will be generated.");
2936 OS << Documentation->getValueAsString("Intro") << "\n";
2938 // Gather the Documentation lists from each of the attributes, based on the
2939 // category provided.
2940 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2941 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
2942 for (const auto *A : Attrs) {
2943 const Record &Attr = *A;
2944 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
2945 for (const auto *D : Docs) {
2946 const Record &Doc = *D;
2947 const Record *Category = Doc.getValueAsDef("Category");
2948 // If the category is "undocumented", then there cannot be any other
2949 // documentation categories (otherwise, the attribute would become
2951 std::string Cat = Category->getValueAsString("Name");
2952 bool Undocumented = Cat == "Undocumented";
2953 if (Undocumented && Docs.size() > 1)
2954 PrintFatalError(Doc.getLoc(),
2955 "Attribute is \"Undocumented\", but has multiple "
2956 "documentation categories");
2959 SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
2963 // Having split the attributes out based on what documentation goes where,
2964 // we can begin to generate sections of documentation.
2965 for (const auto &I : SplitDocs) {
2966 WriteCategoryHeader(I.first, OS);
2968 // Walk over each of the attributes in the category and write out their
2970 for (const auto &Doc : I.second)
2971 WriteDocumentation(Doc, OS);
2975 } // end namespace clang