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; }
57 } // end anonymous namespace
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;
172 Argument(const Record &Arg, StringRef Attr)
173 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
174 attrName(Attr), isOpt(false), Fake(false) {
175 if (!lowerName.empty()) {
176 lowerName[0] = std::tolower(lowerName[0]);
177 upperName[0] = std::toupper(upperName[0]);
180 virtual ~Argument() = default;
182 StringRef getLowerName() const { return lowerName; }
183 StringRef getUpperName() const { return upperName; }
184 StringRef getAttrName() const { return attrName; }
186 bool isOptional() const { return isOpt; }
187 void setOptional(bool set) { isOpt = set; }
189 bool isFake() const { return Fake; }
190 void setFake(bool fake) { Fake = fake; }
192 // These functions print the argument contents formatted in different ways.
193 virtual void writeAccessors(raw_ostream &OS) const = 0;
194 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
195 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
196 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
197 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
198 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
199 virtual void writeCtorBody(raw_ostream &OS) const {}
200 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
201 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
202 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
203 virtual void writeDeclarations(raw_ostream &OS) const = 0;
204 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
205 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
206 virtual void writePCHWrite(raw_ostream &OS) const = 0;
207 virtual void writeValue(raw_ostream &OS) const = 0;
208 virtual void writeDump(raw_ostream &OS) const = 0;
209 virtual void writeDumpChildren(raw_ostream &OS) const {}
210 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
212 virtual bool isEnumArg() const { return false; }
213 virtual bool isVariadicEnumArg() const { return false; }
214 virtual bool isVariadic() const { return false; }
216 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
217 OS << getUpperName();
221 class SimpleArgument : public Argument {
225 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
226 : Argument(Arg, Attr), type(T)
229 std::string getType() const { return type; }
231 void writeAccessors(raw_ostream &OS) const override {
232 OS << " " << type << " get" << getUpperName() << "() const {\n";
233 OS << " return " << getLowerName() << ";\n";
236 void writeCloneArgs(raw_ostream &OS) const override {
237 OS << getLowerName();
239 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
240 OS << "A->get" << getUpperName() << "()";
242 void writeCtorInitializers(raw_ostream &OS) const override {
243 OS << getLowerName() << "(" << getUpperName() << ")";
245 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
246 OS << getLowerName() << "()";
248 void writeCtorParameters(raw_ostream &OS) const override {
249 OS << type << " " << getUpperName();
251 void writeDeclarations(raw_ostream &OS) const override {
252 OS << type << " " << getLowerName() << ";";
254 void writePCHReadDecls(raw_ostream &OS) const override {
255 std::string read = ReadPCHRecord(type);
256 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
258 void writePCHReadArgs(raw_ostream &OS) const override {
259 OS << getLowerName();
261 void writePCHWrite(raw_ostream &OS) const override {
262 OS << " " << WritePCHRecord(type, "SA->get" +
263 std::string(getUpperName()) + "()");
265 void writeValue(raw_ostream &OS) const override {
266 if (type == "FunctionDecl *") {
267 OS << "\" << get" << getUpperName()
268 << "()->getNameInfo().getAsString() << \"";
269 } else if (type == "IdentifierInfo *") {
270 OS << "\" << get" << getUpperName() << "()->getName() << \"";
271 } else if (type == "TypeSourceInfo *") {
272 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
274 OS << "\" << get" << getUpperName() << "() << \"";
277 void writeDump(raw_ostream &OS) const override {
278 if (type == "FunctionDecl *") {
279 OS << " OS << \" \";\n";
280 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
281 } else if (type == "IdentifierInfo *") {
283 OS << " if (SA->get" << getUpperName() << "())\n ";
284 OS << " OS << \" \" << SA->get" << getUpperName()
285 << "()->getName();\n";
286 } else if (type == "TypeSourceInfo *") {
287 OS << " OS << \" \" << SA->get" << getUpperName()
288 << "().getAsString();\n";
289 } else if (type == "bool") {
290 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
291 << getUpperName() << "\";\n";
292 } else if (type == "int" || type == "unsigned") {
293 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
295 llvm_unreachable("Unknown SimpleArgument type!");
300 class DefaultSimpleArgument : public SimpleArgument {
304 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
305 std::string T, int64_t Default)
306 : SimpleArgument(Arg, Attr, T), Default(Default) {}
308 void writeAccessors(raw_ostream &OS) const override {
309 SimpleArgument::writeAccessors(OS);
311 OS << "\n\n static const " << getType() << " Default" << getUpperName()
312 << " = " << Default << ";";
316 class StringArgument : public Argument {
318 StringArgument(const Record &Arg, StringRef Attr)
319 : Argument(Arg, Attr)
322 void writeAccessors(raw_ostream &OS) const override {
323 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
324 OS << " return llvm::StringRef(" << getLowerName() << ", "
325 << getLowerName() << "Length);\n";
327 OS << " unsigned get" << getUpperName() << "Length() const {\n";
328 OS << " return " << getLowerName() << "Length;\n";
330 OS << " void set" << getUpperName()
331 << "(ASTContext &C, llvm::StringRef S) {\n";
332 OS << " " << getLowerName() << "Length = S.size();\n";
333 OS << " this->" << getLowerName() << " = new (C, 1) char ["
334 << getLowerName() << "Length];\n";
335 OS << " if (!S.empty())\n";
336 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
337 << getLowerName() << "Length);\n";
340 void writeCloneArgs(raw_ostream &OS) const override {
341 OS << "get" << getUpperName() << "()";
343 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
344 OS << "A->get" << getUpperName() << "()";
346 void writeCtorBody(raw_ostream &OS) const override {
347 OS << " if (!" << getUpperName() << ".empty())\n";
348 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
349 << ".data(), " << getLowerName() << "Length);";
351 void writeCtorInitializers(raw_ostream &OS) const override {
352 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
353 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
356 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
357 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
359 void writeCtorParameters(raw_ostream &OS) const override {
360 OS << "llvm::StringRef " << getUpperName();
362 void writeDeclarations(raw_ostream &OS) const override {
363 OS << "unsigned " << getLowerName() << "Length;\n";
364 OS << "char *" << getLowerName() << ";";
366 void writePCHReadDecls(raw_ostream &OS) const override {
367 OS << " std::string " << getLowerName()
368 << "= ReadString(Record, Idx);\n";
370 void writePCHReadArgs(raw_ostream &OS) const override {
371 OS << getLowerName();
373 void writePCHWrite(raw_ostream &OS) const override {
374 OS << " AddString(SA->get" << getUpperName() << "(), Record);\n";
376 void writeValue(raw_ostream &OS) const override {
377 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
379 void writeDump(raw_ostream &OS) const override {
380 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
381 << "() << \"\\\"\";\n";
385 class AlignedArgument : public Argument {
387 AlignedArgument(const Record &Arg, StringRef Attr)
388 : Argument(Arg, Attr)
391 void writeAccessors(raw_ostream &OS) const override {
392 OS << " bool is" << getUpperName() << "Dependent() const;\n";
394 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
396 OS << " bool is" << getUpperName() << "Expr() const {\n";
397 OS << " return is" << getLowerName() << "Expr;\n";
400 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
401 OS << " assert(is" << getLowerName() << "Expr);\n";
402 OS << " return " << getLowerName() << "Expr;\n";
405 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
406 OS << " assert(!is" << getLowerName() << "Expr);\n";
407 OS << " return " << getLowerName() << "Type;\n";
410 void writeAccessorDefinitions(raw_ostream &OS) const override {
411 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
412 << "Dependent() const {\n";
413 OS << " if (is" << getLowerName() << "Expr)\n";
414 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
415 << "Expr->isValueDependent() || " << getLowerName()
416 << "Expr->isTypeDependent());\n";
418 OS << " return " << getLowerName()
419 << "Type->getType()->isDependentType();\n";
422 // FIXME: Do not do the calculation here
423 // FIXME: Handle types correctly
424 // A null pointer means maximum alignment
425 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
426 << "(ASTContext &Ctx) const {\n";
427 OS << " assert(!is" << getUpperName() << "Dependent());\n";
428 OS << " if (is" << getLowerName() << "Expr)\n";
429 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
430 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
431 << " * Ctx.getCharWidth() : "
432 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
434 OS << " return 0; // FIXME\n";
437 void writeCloneArgs(raw_ostream &OS) const override {
438 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
439 << "Expr ? static_cast<void*>(" << getLowerName()
440 << "Expr) : " << getLowerName()
443 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
444 // FIXME: move the definition in Sema::InstantiateAttrs to here.
445 // In the meantime, aligned attributes are cloned.
447 void writeCtorBody(raw_ostream &OS) const override {
448 OS << " if (is" << getLowerName() << "Expr)\n";
449 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
450 << getUpperName() << ");\n";
452 OS << " " << getLowerName()
453 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
456 void writeCtorInitializers(raw_ostream &OS) const override {
457 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
459 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
460 OS << "is" << getLowerName() << "Expr(false)";
462 void writeCtorParameters(raw_ostream &OS) const override {
463 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
465 void writeImplicitCtorArgs(raw_ostream &OS) const override {
466 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
468 void writeDeclarations(raw_ostream &OS) const override {
469 OS << "bool is" << getLowerName() << "Expr;\n";
471 OS << "Expr *" << getLowerName() << "Expr;\n";
472 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
475 void writePCHReadArgs(raw_ostream &OS) const override {
476 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
478 void writePCHReadDecls(raw_ostream &OS) const override {
479 OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n";
480 OS << " void *" << getLowerName() << "Ptr;\n";
481 OS << " if (is" << getLowerName() << "Expr)\n";
482 OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n";
484 OS << " " << getLowerName()
485 << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n";
487 void writePCHWrite(raw_ostream &OS) const override {
488 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
489 OS << " if (SA->is" << getUpperName() << "Expr())\n";
490 OS << " AddStmt(SA->get" << getUpperName() << "Expr());\n";
492 OS << " AddTypeSourceInfo(SA->get" << getUpperName()
493 << "Type(), Record);\n";
495 void writeValue(raw_ostream &OS) const override {
497 // The aligned attribute argument expression is optional.
498 OS << " if (is" << getLowerName() << "Expr && "
499 << getLowerName() << "Expr)\n";
500 OS << " " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n";
503 void writeDump(raw_ostream &OS) const override {
505 void writeDumpChildren(raw_ostream &OS) const override {
506 OS << " if (SA->is" << getUpperName() << "Expr())\n";
507 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
509 OS << " dumpType(SA->get" << getUpperName()
510 << "Type()->getType());\n";
512 void writeHasChildren(raw_ostream &OS) const override {
513 OS << "SA->is" << getUpperName() << "Expr()";
517 class VariadicArgument : public Argument {
518 std::string Type, ArgName, ArgSizeName, RangeName;
521 // Assumed to receive a parameter: raw_ostream OS.
522 virtual void writeValueImpl(raw_ostream &OS) const {
523 OS << " OS << Val;\n";
527 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
528 : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"),
529 ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {}
531 std::string getType() const { return Type; }
532 bool isVariadic() const override { return true; }
534 void writeAccessors(raw_ostream &OS) const override {
535 std::string IteratorType = getLowerName().str() + "_iterator";
536 std::string BeginFn = getLowerName().str() + "_begin()";
537 std::string EndFn = getLowerName().str() + "_end()";
539 OS << " typedef " << Type << "* " << IteratorType << ";\n";
540 OS << " " << IteratorType << " " << BeginFn << " const {"
541 << " return " << ArgName << "; }\n";
542 OS << " " << IteratorType << " " << EndFn << " const {"
543 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
544 OS << " unsigned " << getLowerName() << "_size() const {"
545 << " return " << ArgSizeName << "; }\n";
546 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
547 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
550 void writeCloneArgs(raw_ostream &OS) const override {
551 OS << ArgName << ", " << ArgSizeName;
553 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
554 // This isn't elegant, but we have to go through public methods...
555 OS << "A->" << getLowerName() << "_begin(), "
556 << "A->" << getLowerName() << "_size()";
558 void writeCtorBody(raw_ostream &OS) const override {
559 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
560 << " + " << ArgSizeName << ", " << ArgName << ");";
562 void writeCtorInitializers(raw_ostream &OS) const override {
563 OS << ArgSizeName << "(" << getUpperName() << "Size), "
564 << ArgName << "(new (Ctx, 16) " << getType() << "["
565 << ArgSizeName << "])";
567 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
568 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
570 void writeCtorParameters(raw_ostream &OS) const override {
571 OS << getType() << " *" << getUpperName() << ", unsigned "
572 << getUpperName() << "Size";
574 void writeImplicitCtorArgs(raw_ostream &OS) const override {
575 OS << getUpperName() << ", " << getUpperName() << "Size";
577 void writeDeclarations(raw_ostream &OS) const override {
578 OS << " unsigned " << ArgSizeName << ";\n";
579 OS << " " << getType() << " *" << ArgName << ";";
581 void writePCHReadDecls(raw_ostream &OS) const override {
582 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
583 OS << " SmallVector<" << Type << ", 4> " << getLowerName()
585 OS << " " << getLowerName() << ".reserve(" << getLowerName()
587 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
589 std::string read = ReadPCHRecord(Type);
590 OS << " " << getLowerName() << ".push_back(" << read << ");\n";
592 void writePCHReadArgs(raw_ostream &OS) const override {
593 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
595 void writePCHWrite(raw_ostream &OS) const override {
596 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
597 OS << " for (auto &Val : SA->" << RangeName << "())\n";
598 OS << " " << WritePCHRecord(Type, "Val");
600 void writeValue(raw_ostream &OS) const override {
602 OS << " bool isFirst = true;\n"
603 << " for (const auto &Val : " << RangeName << "()) {\n"
604 << " if (isFirst) isFirst = false;\n"
605 << " else OS << \", \";\n";
610 void writeDump(raw_ostream &OS) const override {
611 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
612 OS << " OS << \" \" << Val;\n";
616 // Unique the enums, but maintain the original declaration ordering.
617 std::vector<std::string>
618 uniqueEnumsInOrder(const std::vector<std::string> &enums) {
619 std::vector<std::string> uniques;
620 std::set<std::string> unique_set(enums.begin(), enums.end());
621 for (const auto &i : enums) {
622 auto set_i = unique_set.find(i);
623 if (set_i != unique_set.end()) {
624 uniques.push_back(i);
625 unique_set.erase(set_i);
631 class EnumArgument : public Argument {
633 std::vector<std::string> values, enums, uniques;
635 EnumArgument(const Record &Arg, StringRef Attr)
636 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
637 values(Arg.getValueAsListOfStrings("Values")),
638 enums(Arg.getValueAsListOfStrings("Enums")),
639 uniques(uniqueEnumsInOrder(enums))
641 // FIXME: Emit a proper error
642 assert(!uniques.empty());
645 bool isEnumArg() const override { return true; }
647 void writeAccessors(raw_ostream &OS) const override {
648 OS << " " << type << " get" << getUpperName() << "() const {\n";
649 OS << " return " << getLowerName() << ";\n";
652 void writeCloneArgs(raw_ostream &OS) const override {
653 OS << getLowerName();
655 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
656 OS << "A->get" << getUpperName() << "()";
658 void writeCtorInitializers(raw_ostream &OS) const override {
659 OS << getLowerName() << "(" << getUpperName() << ")";
661 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
662 OS << getLowerName() << "(" << type << "(0))";
664 void writeCtorParameters(raw_ostream &OS) const override {
665 OS << type << " " << getUpperName();
667 void writeDeclarations(raw_ostream &OS) const override {
668 auto i = uniques.cbegin(), e = uniques.cend();
669 // The last one needs to not have a comma.
673 OS << " enum " << type << " {\n";
675 OS << " " << *i << ",\n";
676 OS << " " << *e << "\n";
679 OS << " " << type << " " << getLowerName() << ";";
681 void writePCHReadDecls(raw_ostream &OS) const override {
682 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
683 << "(static_cast<" << getAttrName() << "Attr::" << type
684 << ">(Record[Idx++]));\n";
686 void writePCHReadArgs(raw_ostream &OS) const override {
687 OS << getLowerName();
689 void writePCHWrite(raw_ostream &OS) const override {
690 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
692 void writeValue(raw_ostream &OS) const override {
693 // FIXME: this isn't 100% correct -- some enum arguments require printing
694 // as a string literal, while others require printing as an identifier.
695 // Tablegen currently does not distinguish between the two forms.
696 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
697 << getUpperName() << "()) << \"\\\"";
699 void writeDump(raw_ostream &OS) const override {
700 OS << " switch(SA->get" << getUpperName() << "()) {\n";
701 for (const auto &I : uniques) {
702 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
703 OS << " OS << \" " << I << "\";\n";
709 void writeConversion(raw_ostream &OS) const {
710 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
711 OS << type << " &Out) {\n";
712 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
713 OS << type << ">>(Val)\n";
714 for (size_t I = 0; I < enums.size(); ++I) {
715 OS << " .Case(\"" << values[I] << "\", ";
716 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
718 OS << " .Default(Optional<" << type << ">());\n";
720 OS << " Out = *R;\n return true;\n }\n";
721 OS << " return false;\n";
724 // Mapping from enumeration values back to enumeration strings isn't
725 // trivial because some enumeration values have multiple named
726 // enumerators, such as type_visibility(internal) and
727 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
728 OS << " static const char *Convert" << type << "ToStr("
729 << type << " Val) {\n"
730 << " switch(Val) {\n";
731 std::set<std::string> Uniques;
732 for (size_t I = 0; I < enums.size(); ++I) {
733 if (Uniques.insert(enums[I]).second)
734 OS << " case " << getAttrName() << "Attr::" << enums[I]
735 << ": return \"" << values[I] << "\";\n";
738 << " llvm_unreachable(\"No enumerator with that value\");\n"
743 class VariadicEnumArgument: public VariadicArgument {
744 std::string type, QualifiedTypeName;
745 std::vector<std::string> values, enums, uniques;
748 void writeValueImpl(raw_ostream &OS) const override {
749 // FIXME: this isn't 100% correct -- some enum arguments require printing
750 // as a string literal, while others require printing as an identifier.
751 // Tablegen currently does not distinguish between the two forms.
752 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
753 << "ToStr(Val)" << "<< \"\\\"\";\n";
757 VariadicEnumArgument(const Record &Arg, StringRef Attr)
758 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
759 type(Arg.getValueAsString("Type")),
760 values(Arg.getValueAsListOfStrings("Values")),
761 enums(Arg.getValueAsListOfStrings("Enums")),
762 uniques(uniqueEnumsInOrder(enums))
764 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
766 // FIXME: Emit a proper error
767 assert(!uniques.empty());
770 bool isVariadicEnumArg() const override { return true; }
772 void writeDeclarations(raw_ostream &OS) const override {
773 auto i = uniques.cbegin(), e = uniques.cend();
774 // The last one needs to not have a comma.
778 OS << " enum " << type << " {\n";
780 OS << " " << *i << ",\n";
781 OS << " " << *e << "\n";
785 VariadicArgument::writeDeclarations(OS);
787 void writeDump(raw_ostream &OS) const override {
788 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
789 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
790 << getLowerName() << "_end(); I != E; ++I) {\n";
791 OS << " switch(*I) {\n";
792 for (const auto &UI : uniques) {
793 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
794 OS << " OS << \" " << UI << "\";\n";
800 void writePCHReadDecls(raw_ostream &OS) const override {
801 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n";
802 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
804 OS << " " << getLowerName() << ".reserve(" << getLowerName()
806 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
807 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
808 << QualifiedTypeName << ">(Record[Idx++]));\n";
810 void writePCHWrite(raw_ostream &OS) const override {
811 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
812 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
813 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
814 << getLowerName() << "_end(); i != e; ++i)\n";
815 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
817 void writeConversion(raw_ostream &OS) const {
818 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
819 OS << type << " &Out) {\n";
820 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
821 OS << type << ">>(Val)\n";
822 for (size_t I = 0; I < enums.size(); ++I) {
823 OS << " .Case(\"" << values[I] << "\", ";
824 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
826 OS << " .Default(Optional<" << type << ">());\n";
828 OS << " Out = *R;\n return true;\n }\n";
829 OS << " return false;\n";
832 OS << " static const char *Convert" << type << "ToStr("
833 << type << " Val) {\n"
834 << " switch(Val) {\n";
835 std::set<std::string> Uniques;
836 for (size_t I = 0; I < enums.size(); ++I) {
837 if (Uniques.insert(enums[I]).second)
838 OS << " case " << getAttrName() << "Attr::" << enums[I]
839 << ": return \"" << values[I] << "\";\n";
842 << " llvm_unreachable(\"No enumerator with that value\");\n"
847 class VersionArgument : public Argument {
849 VersionArgument(const Record &Arg, StringRef Attr)
850 : Argument(Arg, Attr)
853 void writeAccessors(raw_ostream &OS) const override {
854 OS << " VersionTuple get" << getUpperName() << "() const {\n";
855 OS << " return " << getLowerName() << ";\n";
857 OS << " void set" << getUpperName()
858 << "(ASTContext &C, VersionTuple V) {\n";
859 OS << " " << getLowerName() << " = V;\n";
862 void writeCloneArgs(raw_ostream &OS) const override {
863 OS << "get" << getUpperName() << "()";
865 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
866 OS << "A->get" << getUpperName() << "()";
868 void writeCtorInitializers(raw_ostream &OS) const override {
869 OS << getLowerName() << "(" << getUpperName() << ")";
871 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
872 OS << getLowerName() << "()";
874 void writeCtorParameters(raw_ostream &OS) const override {
875 OS << "VersionTuple " << getUpperName();
877 void writeDeclarations(raw_ostream &OS) const override {
878 OS << "VersionTuple " << getLowerName() << ";\n";
880 void writePCHReadDecls(raw_ostream &OS) const override {
881 OS << " VersionTuple " << getLowerName()
882 << "= ReadVersionTuple(Record, Idx);\n";
884 void writePCHReadArgs(raw_ostream &OS) const override {
885 OS << getLowerName();
887 void writePCHWrite(raw_ostream &OS) const override {
888 OS << " AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n";
890 void writeValue(raw_ostream &OS) const override {
891 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
893 void writeDump(raw_ostream &OS) const override {
894 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
898 class ExprArgument : public SimpleArgument {
900 ExprArgument(const Record &Arg, StringRef Attr)
901 : SimpleArgument(Arg, Attr, "Expr *")
904 void writeASTVisitorTraversal(raw_ostream &OS) const override {
906 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
907 OS << " return false;\n";
910 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
911 OS << "tempInst" << getUpperName();
914 void writeTemplateInstantiation(raw_ostream &OS) const override {
915 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
917 OS << " EnterExpressionEvaluationContext "
918 << "Unevaluated(S, Sema::Unevaluated);\n";
919 OS << " ExprResult " << "Result = S.SubstExpr("
920 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
921 OS << " tempInst" << getUpperName() << " = "
922 << "Result.getAs<Expr>();\n";
926 void writeDump(raw_ostream &OS) const override {}
928 void writeDumpChildren(raw_ostream &OS) const override {
929 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
931 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
934 class VariadicExprArgument : public VariadicArgument {
936 VariadicExprArgument(const Record &Arg, StringRef Attr)
937 : VariadicArgument(Arg, Attr, "Expr *")
940 void writeASTVisitorTraversal(raw_ostream &OS) const override {
942 OS << " " << getType() << " *I = A->" << getLowerName()
944 OS << " " << getType() << " *E = A->" << getLowerName()
946 OS << " for (; I != E; ++I) {\n";
947 OS << " if (!getDerived().TraverseStmt(*I))\n";
948 OS << " return false;\n";
953 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
954 OS << "tempInst" << getUpperName() << ", "
955 << "A->" << getLowerName() << "_size()";
958 void writeTemplateInstantiation(raw_ostream &OS) const override {
959 OS << " auto *tempInst" << getUpperName()
960 << " = new (C, 16) " << getType()
961 << "[A->" << getLowerName() << "_size()];\n";
963 OS << " EnterExpressionEvaluationContext "
964 << "Unevaluated(S, Sema::Unevaluated);\n";
965 OS << " " << getType() << " *TI = tempInst" << getUpperName()
967 OS << " " << getType() << " *I = A->" << getLowerName()
969 OS << " " << getType() << " *E = A->" << getLowerName()
971 OS << " for (; I != E; ++I, ++TI) {\n";
972 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
973 OS << " *TI = Result.getAs<Expr>();\n";
978 void writeDump(raw_ostream &OS) const override {}
980 void writeDumpChildren(raw_ostream &OS) const override {
981 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
982 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
983 << getLowerName() << "_end(); I != E; ++I)\n";
984 OS << " dumpStmt(*I);\n";
987 void writeHasChildren(raw_ostream &OS) const override {
988 OS << "SA->" << getLowerName() << "_begin() != "
989 << "SA->" << getLowerName() << "_end()";
993 class VariadicStringArgument : public VariadicArgument {
995 VariadicStringArgument(const Record &Arg, StringRef Attr)
996 : VariadicArgument(Arg, Attr, "std::string")
998 void writeValueImpl(raw_ostream &OS) const override {
999 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1003 class TypeArgument : public SimpleArgument {
1005 TypeArgument(const Record &Arg, StringRef Attr)
1006 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1009 void writeAccessors(raw_ostream &OS) const override {
1010 OS << " QualType get" << getUpperName() << "() const {\n";
1011 OS << " return " << getLowerName() << "->getType();\n";
1013 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1014 OS << " return " << getLowerName() << ";\n";
1017 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1018 OS << "A->get" << getUpperName() << "Loc()";
1020 void writePCHWrite(raw_ostream &OS) const override {
1021 OS << " " << WritePCHRecord(
1022 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1025 } // end anonymous namespace
1027 static std::unique_ptr<Argument>
1028 createArgument(const Record &Arg, StringRef Attr,
1029 const Record *Search = nullptr) {
1033 std::unique_ptr<Argument> Ptr;
1034 llvm::StringRef ArgName = Search->getName();
1036 if (ArgName == "AlignedArgument")
1037 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1038 else if (ArgName == "EnumArgument")
1039 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1040 else if (ArgName == "ExprArgument")
1041 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1042 else if (ArgName == "FunctionArgument")
1043 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1044 else if (ArgName == "IdentifierArgument")
1045 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1046 else if (ArgName == "DefaultBoolArgument")
1047 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1048 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1049 else if (ArgName == "BoolArgument")
1050 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1051 else if (ArgName == "DefaultIntArgument")
1052 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1053 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1054 else if (ArgName == "IntArgument")
1055 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1056 else if (ArgName == "StringArgument")
1057 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1058 else if (ArgName == "TypeArgument")
1059 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1060 else if (ArgName == "UnsignedArgument")
1061 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1062 else if (ArgName == "VariadicUnsignedArgument")
1063 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1064 else if (ArgName == "VariadicStringArgument")
1065 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1066 else if (ArgName == "VariadicEnumArgument")
1067 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1068 else if (ArgName == "VariadicExprArgument")
1069 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1070 else if (ArgName == "VersionArgument")
1071 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1074 // Search in reverse order so that the most-derived type is handled first.
1075 ArrayRef<Record*> Bases = Search->getSuperClasses();
1076 for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) {
1077 if ((Ptr = createArgument(Arg, Attr, Base)))
1082 if (Ptr && Arg.getValueAsBit("Optional"))
1083 Ptr->setOptional(true);
1085 if (Ptr && Arg.getValueAsBit("Fake"))
1091 static void writeAvailabilityValue(raw_ostream &OS) {
1092 OS << "\" << getPlatform()->getName();\n"
1093 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1094 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1095 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1096 << " if (getUnavailable()) OS << \", unavailable\";\n"
1100 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1101 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1103 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1104 if (Spellings.empty()) {
1105 OS << " return \"(No spelling)\";\n}\n\n";
1109 OS << " switch (SpellingListIndex) {\n"
1111 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1112 " return \"(No spelling)\";\n";
1114 for (unsigned I = 0; I < Spellings.size(); ++I)
1115 OS << " case " << I << ":\n"
1116 " return \"" << Spellings[I].name() << "\";\n";
1117 // End of the switch statement.
1119 // End of the getSpelling function.
1124 writePrettyPrintFunction(Record &R,
1125 const std::vector<std::unique_ptr<Argument>> &Args,
1127 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1129 OS << "void " << R.getName() << "Attr::printPretty("
1130 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1132 if (Spellings.empty()) {
1138 " switch (SpellingListIndex) {\n"
1140 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1143 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1144 llvm::SmallString<16> Prefix;
1145 llvm::SmallString<8> Suffix;
1146 // The actual spelling of the name and namespace (if applicable)
1147 // of an attribute without considering prefix and suffix.
1148 llvm::SmallString<64> Spelling;
1149 std::string Name = Spellings[I].name();
1150 std::string Variety = Spellings[I].variety();
1152 if (Variety == "GNU") {
1153 Prefix = " __attribute__((";
1155 } else if (Variety == "CXX11") {
1158 std::string Namespace = Spellings[I].nameSpace();
1159 if (!Namespace.empty()) {
1160 Spelling += Namespace;
1163 } else if (Variety == "Declspec") {
1164 Prefix = " __declspec(";
1166 } else if (Variety == "Keyword") {
1169 } else if (Variety == "Pragma") {
1170 Prefix = "#pragma ";
1172 std::string Namespace = Spellings[I].nameSpace();
1173 if (!Namespace.empty()) {
1174 Spelling += Namespace;
1178 llvm_unreachable("Unknown attribute syntax variety!");
1184 " case " << I << " : {\n"
1185 " OS << \"" << Prefix << Spelling;
1187 if (Variety == "Pragma") {
1189 OS << " printPrettyPragma(OS, Policy);\n";
1190 OS << " OS << \"\\n\";";
1196 // Fake arguments aren't part of the parsed form and should not be
1198 bool hasNonFakeArgs = false;
1199 for (const auto &arg : Args) {
1200 if (arg->isFake()) continue;
1201 hasNonFakeArgs = true;
1204 // FIXME: always printing the parenthesis isn't the correct behavior for
1205 // attributes which have optional arguments that were not provided. For
1206 // instance: __attribute__((aligned)) will be pretty printed as
1207 // __attribute__((aligned())). The logic should check whether there is only
1208 // a single argument, and if it is optional, whether it has been provided.
1211 if (Spelling == "availability") {
1212 writeAvailabilityValue(OS);
1215 for (const auto &arg : Args) {
1216 if (arg->isFake()) continue;
1217 if (index++) OS << ", ";
1218 arg->writeValue(OS);
1224 OS << Suffix + "\";\n";
1231 // End of the switch statement.
1233 // End of the print function.
1237 /// \brief Return the index of a spelling in a spelling list.
1239 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1240 const FlattenedSpelling &Spelling) {
1241 assert(!SpellingList.empty() && "Spelling list is empty!");
1243 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1244 const FlattenedSpelling &S = SpellingList[Index];
1245 if (S.variety() != Spelling.variety())
1247 if (S.nameSpace() != Spelling.nameSpace())
1249 if (S.name() != Spelling.name())
1255 llvm_unreachable("Unknown spelling!");
1258 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1259 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1260 for (const auto *Accessor : Accessors) {
1261 std::string Name = Accessor->getValueAsString("Name");
1262 std::vector<FlattenedSpelling> Spellings =
1263 GetFlattenedSpellings(*Accessor);
1264 std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1265 assert(!SpellingList.empty() &&
1266 "Attribute with empty spelling list can't have accessors!");
1268 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1269 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1270 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1271 if (Index != Spellings.size() -1)
1272 OS << " ||\n SpellingListIndex == ";
1280 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1281 assert(!Spellings.empty() && "An empty list of spellings was provided");
1282 std::string FirstName = NormalizeNameForSpellingComparison(
1283 Spellings.front().name());
1284 for (const auto &Spelling :
1285 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1286 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1287 if (Name != FirstName)
1293 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1295 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1296 SemanticSpellingMap &Map) {
1297 // The enumerants are automatically generated based on the variety,
1298 // namespace (if present) and name for each attribute spelling. However,
1299 // care is taken to avoid trampling on the reserved namespace due to
1301 std::string Ret(" enum Spelling {\n");
1302 std::set<std::string> Uniques;
1304 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1305 const FlattenedSpelling &S = *I;
1306 std::string Variety = S.variety();
1307 std::string Spelling = S.name();
1308 std::string Namespace = S.nameSpace();
1309 std::string EnumName = "";
1311 EnumName += (Variety + "_");
1312 if (!Namespace.empty())
1313 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1315 EnumName += NormalizeNameForSpellingComparison(Spelling);
1317 // Even if the name is not unique, this spelling index corresponds to a
1318 // particular enumerant name that we've calculated.
1319 Map[Idx] = EnumName;
1321 // Since we have been stripping underscores to avoid trampling on the
1322 // reserved namespace, we may have inadvertently created duplicate
1323 // enumerant names. These duplicates are not considered part of the
1324 // semantic spelling, and can be elided.
1325 if (Uniques.find(EnumName) != Uniques.end())
1328 Uniques.insert(EnumName);
1329 if (I != Spellings.begin())
1331 // Duplicate spellings are not considered part of the semantic spelling
1332 // enumeration, but the spelling index and semantic spelling values are
1333 // meant to be equivalent, so we must specify a concrete value for each
1335 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1341 void WriteSemanticSpellingSwitch(const std::string &VarName,
1342 const SemanticSpellingMap &Map,
1344 OS << " switch (" << VarName << ") {\n default: "
1345 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1346 for (const auto &I : Map)
1347 OS << " case " << I.first << ": return " << I.second << ";\n";
1351 // Emits the LateParsed property for attributes.
1352 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1353 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1354 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1356 for (const auto *Attr : Attrs) {
1357 bool LateParsed = Attr->getValueAsBit("LateParsed");
1360 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1362 // FIXME: Handle non-GNU attributes
1363 for (const auto &I : Spellings) {
1364 if (I.variety() != "GNU")
1366 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1370 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1373 /// \brief Emits the first-argument-is-type property for attributes.
1374 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
1375 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
1376 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
1378 for (const auto *Attr : Attrs) {
1379 // Determine whether the first argument is a type.
1380 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1384 if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument")
1387 // All these spellings take a single type argument.
1388 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1389 std::set<std::string> Emitted;
1390 for (const auto &S : Spellings) {
1391 if (Emitted.insert(S.name()).second)
1392 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1395 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
1398 /// \brief Emits the parse-arguments-in-unevaluated-context property for
1400 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
1401 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
1402 ParsedAttrMap Attrs = getParsedAttrList(Records);
1403 for (const auto &I : Attrs) {
1404 const Record &Attr = *I.second;
1406 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
1409 // All these spellings take are parsed unevaluated.
1410 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
1411 std::set<std::string> Emitted;
1412 for (const auto &S : Spellings) {
1413 if (Emitted.insert(S.name()).second)
1414 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1417 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
1420 static bool isIdentifierArgument(Record *Arg) {
1421 return !Arg->getSuperClasses().empty() &&
1422 llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName())
1423 .Case("IdentifierArgument", true)
1424 .Case("EnumArgument", true)
1425 .Case("VariadicEnumArgument", true)
1429 // Emits the first-argument-is-identifier property for attributes.
1430 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
1431 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
1432 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1434 for (const auto *Attr : Attrs) {
1435 // Determine whether the first argument is an identifier.
1436 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
1437 if (Args.empty() || !isIdentifierArgument(Args[0]))
1440 // All these spellings take an identifier argument.
1441 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1442 std::set<std::string> Emitted;
1443 for (const auto &S : Spellings) {
1444 if (Emitted.insert(S.name()).second)
1445 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
1448 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
1453 // Emits the class definitions for attributes.
1454 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
1455 emitSourceFileHeader("Attribute classes' definitions", OS);
1457 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
1458 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
1460 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1462 for (const auto *Attr : Attrs) {
1463 const Record &R = *Attr;
1465 // FIXME: Currently, documentation is generated as-needed due to the fact
1466 // that there is no way to allow a generated project "reach into" the docs
1467 // directory (for instance, it may be an out-of-tree build). However, we want
1468 // to ensure that every attribute has a Documentation field, and produce an
1469 // error if it has been neglected. Otherwise, the on-demand generation which
1470 // happens server-side will fail. This code is ensuring that functionality,
1471 // even though this Emitter doesn't technically need the documentation.
1472 // When attribute documentation can be generated as part of the build
1473 // itself, this code can be removed.
1474 (void)R.getValueAsListOfDefs("Documentation");
1476 if (!R.getValueAsBit("ASTNode"))
1479 ArrayRef<Record *> Supers = R.getSuperClasses();
1480 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
1481 std::string SuperName;
1482 for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) {
1483 const Record &R = *Super;
1484 if (R.getName() != "TargetSpecificAttr" && SuperName.empty())
1485 SuperName = R.getName();
1488 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
1490 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1491 std::vector<std::unique_ptr<Argument>> Args;
1492 Args.reserve(ArgRecords.size());
1494 bool HasOptArg = false;
1495 bool HasFakeArg = false;
1496 for (const auto *ArgRecord : ArgRecords) {
1497 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
1498 Args.back()->writeDeclarations(OS);
1501 // For these purposes, fake takes priority over optional.
1502 if (Args.back()->isFake()) {
1504 } else if (Args.back()->isOptional()) {
1509 OS << "\npublic:\n";
1511 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1513 // If there are zero or one spellings, all spelling-related functionality
1514 // can be elided. If all of the spellings share the same name, the spelling
1515 // functionality can also be elided.
1516 bool ElideSpelling = (Spellings.size() <= 1) ||
1517 SpellingNamesAreCommon(Spellings);
1519 // This maps spelling index values to semantic Spelling enumerants.
1520 SemanticSpellingMap SemanticToSyntacticMap;
1523 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
1525 // Emit CreateImplicit factory methods.
1526 auto emitCreateImplicit = [&](bool emitFake) {
1527 OS << " static " << R.getName() << "Attr *CreateImplicit(";
1528 OS << "ASTContext &Ctx";
1530 OS << ", Spelling S";
1531 for (auto const &ai : Args) {
1532 if (ai->isFake() && !emitFake) continue;
1534 ai->writeCtorParameters(OS);
1536 OS << ", SourceRange Loc = SourceRange()";
1538 OS << " auto *A = new (Ctx) " << R.getName();
1539 OS << "Attr(Loc, Ctx, ";
1540 for (auto const &ai : Args) {
1541 if (ai->isFake() && !emitFake) continue;
1542 ai->writeImplicitCtorArgs(OS);
1545 OS << (ElideSpelling ? "0" : "S") << ");\n";
1546 OS << " A->setImplicit(true);\n";
1547 OS << " return A;\n }\n\n";
1550 // Emit a CreateImplicit that takes all the arguments.
1551 emitCreateImplicit(true);
1553 // Emit a CreateImplicit that takes all the non-fake arguments.
1555 emitCreateImplicit(false);
1558 // Emit constructors.
1559 auto emitCtor = [&](bool emitOpt, bool emitFake) {
1560 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
1561 if (arg->isFake()) return emitFake;
1562 if (arg->isOptional()) return emitOpt;
1566 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
1567 for (auto const &ai : Args) {
1568 if (!shouldEmitArg(ai)) continue;
1570 ai->writeCtorParameters(OS);
1575 OS << "unsigned SI\n";
1578 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
1579 << R.getValueAsBit("LateParsed") << ", "
1580 << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n";
1582 for (auto const &ai : Args) {
1584 if (!shouldEmitArg(ai)) {
1585 ai->writeCtorDefaultInitializers(OS);
1587 ai->writeCtorInitializers(OS);
1594 for (auto const &ai : Args) {
1595 if (!shouldEmitArg(ai)) continue;
1596 ai->writeCtorBody(OS);
1603 // Emit a constructor that includes all the arguments.
1604 // This is necessary for cloning.
1605 emitCtor(true, true);
1607 // Emit a constructor that takes all the non-fake arguments.
1609 emitCtor(true, false);
1612 // Emit a constructor that takes all the non-fake, non-optional arguments.
1614 emitCtor(false, false);
1617 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
1618 OS << " void printPretty(raw_ostream &OS,\n"
1619 << " const PrintingPolicy &Policy) const;\n";
1620 OS << " const char *getSpelling() const;\n";
1622 if (!ElideSpelling) {
1623 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
1624 OS << " Spelling getSemanticSpelling() const {\n";
1625 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
1630 writeAttrAccessorDefinition(R, OS);
1632 for (auto const &ai : Args) {
1633 ai->writeAccessors(OS);
1636 // Don't write conversion routines for fake arguments.
1637 if (ai->isFake()) continue;
1639 if (ai->isEnumArg())
1640 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
1641 else if (ai->isVariadicEnumArg())
1642 static_cast<const VariadicEnumArgument *>(ai.get())
1643 ->writeConversion(OS);
1646 OS << R.getValueAsString("AdditionalMembers");
1649 OS << " static bool classof(const Attr *A) { return A->getKind() == "
1650 << "attr::" << R.getName() << "; }\n";
1655 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
1658 // Emits the class method definitions for attributes.
1659 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
1660 emitSourceFileHeader("Attribute classes' member function definitions", OS);
1662 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1664 for (auto *Attr : Attrs) {
1667 if (!R.getValueAsBit("ASTNode"))
1670 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
1671 std::vector<std::unique_ptr<Argument>> Args;
1672 for (const auto *Arg : ArgRecords)
1673 Args.emplace_back(createArgument(*Arg, R.getName()));
1675 for (auto const &ai : Args)
1676 ai->writeAccessorDefinitions(OS);
1678 OS << R.getName() << "Attr *" << R.getName()
1679 << "Attr::clone(ASTContext &C) const {\n";
1680 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
1681 for (auto const &ai : Args) {
1683 ai->writeCloneArgs(OS);
1685 OS << ", getSpellingListIndex());\n";
1686 OS << " A->Inherited = Inherited;\n";
1687 OS << " A->IsPackExpansion = IsPackExpansion;\n";
1688 OS << " A->Implicit = Implicit;\n";
1689 OS << " return A;\n}\n\n";
1691 writePrettyPrintFunction(R, Args, OS);
1692 writeGetSpellingFunction(R, OS);
1695 // Instead of relying on virtual dispatch we just create a huge dispatch
1696 // switch. This is both smaller and faster than virtual functions.
1697 auto EmitFunc = [&](const char *Method) {
1698 OS << " switch (getKind()) {\n";
1699 for (const auto *Attr : Attrs) {
1700 const Record &R = *Attr;
1701 if (!R.getValueAsBit("ASTNode"))
1704 OS << " case attr::" << R.getName() << ":\n";
1705 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
1708 OS << " case attr::NUM_ATTRS:\n";
1711 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
1715 OS << "const char *Attr::getSpelling() const {\n";
1716 EmitFunc("getSpelling()");
1718 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
1719 EmitFunc("clone(C)");
1721 OS << "void Attr::printPretty(raw_ostream &OS, "
1722 "const PrintingPolicy &Policy) const {\n";
1723 EmitFunc("printPretty(OS, Policy)");
1726 } // end namespace clang
1728 static void EmitAttrList(raw_ostream &OS, StringRef Class,
1729 const std::vector<Record*> &AttrList) {
1730 auto i = AttrList.cbegin(), e = AttrList.cend();
1733 // Move the end iterator back to emit the last attribute.
1734 for(--e; i != e; ++i) {
1735 if (!(*i)->getValueAsBit("ASTNode"))
1738 OS << Class << "(" << (*i)->getName() << ")\n";
1741 OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n";
1745 // Determines if an attribute has a Pragma spelling.
1746 static bool AttrHasPragmaSpelling(const Record *R) {
1747 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
1748 return std::find_if(Spellings.begin(), Spellings.end(),
1749 [](const FlattenedSpelling &S) {
1750 return S.variety() == "Pragma";
1751 }) != Spellings.end();
1755 // Emits the enumeration list for attributes.
1756 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
1757 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
1759 OS << "#ifndef LAST_ATTR\n";
1760 OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n";
1763 OS << "#ifndef INHERITABLE_ATTR\n";
1764 OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n";
1767 OS << "#ifndef LAST_INHERITABLE_ATTR\n";
1768 OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n";
1771 OS << "#ifndef INHERITABLE_PARAM_ATTR\n";
1772 OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n";
1775 OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n";
1776 OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)"
1777 " INHERITABLE_PARAM_ATTR(NAME)\n";
1780 OS << "#ifndef PRAGMA_SPELLING_ATTR\n";
1781 OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n";
1784 OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n";
1785 OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n";
1788 Record *InhClass = Records.getClass("InheritableAttr");
1789 Record *InhParamClass = Records.getClass("InheritableParamAttr");
1790 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"),
1791 NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs;
1792 for (auto *Attr : Attrs) {
1793 if (!Attr->getValueAsBit("ASTNode"))
1796 if (AttrHasPragmaSpelling(Attr))
1797 PragmaAttrs.push_back(Attr);
1799 if (Attr->isSubClassOf(InhParamClass))
1800 InhParamAttrs.push_back(Attr);
1801 else if (Attr->isSubClassOf(InhClass))
1802 InhAttrs.push_back(Attr);
1804 NonInhAttrs.push_back(Attr);
1807 EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
1808 EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs);
1809 EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs);
1810 EmitAttrList(OS, "ATTR", NonInhAttrs);
1812 OS << "#undef LAST_ATTR\n";
1813 OS << "#undef INHERITABLE_ATTR\n";
1814 OS << "#undef LAST_INHERITABLE_ATTR\n";
1815 OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n";
1816 OS << "#undef LAST_PRAGMA_ATTR\n";
1817 OS << "#undef PRAGMA_SPELLING_ATTR\n";
1818 OS << "#undef ATTR\n";
1821 // Emits the code to read an attribute from a precompiled header.
1822 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
1823 emitSourceFileHeader("Attribute deserialization code", OS);
1825 Record *InhClass = Records.getClass("InheritableAttr");
1826 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
1828 std::vector<std::unique_ptr<Argument>> Args;
1830 OS << " switch (Kind) {\n";
1831 OS << " default:\n";
1832 OS << " llvm_unreachable(\"Unknown attribute!\");\n";
1833 for (const auto *Attr : Attrs) {
1834 const Record &R = *Attr;
1835 if (!R.getValueAsBit("ASTNode"))
1838 OS << " case attr::" << R.getName() << ": {\n";
1839 if (R.isSubClassOf(InhClass))
1840 OS << " bool isInherited = Record[Idx++];\n";
1841 OS << " bool isImplicit = Record[Idx++];\n";
1842 OS << " unsigned Spelling = Record[Idx++];\n";
1843 ArgRecords = R.getValueAsListOfDefs("Args");
1845 for (const auto *Arg : ArgRecords) {
1846 Args.emplace_back(createArgument(*Arg, R.getName()));
1847 Args.back()->writePCHReadDecls(OS);
1849 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
1850 for (auto const &ri : Args) {
1852 ri->writePCHReadArgs(OS);
1854 OS << ", Spelling);\n";
1855 if (R.isSubClassOf(InhClass))
1856 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
1857 OS << " New->setImplicit(isImplicit);\n";
1864 // Emits the code to write an attribute to a precompiled header.
1865 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
1866 emitSourceFileHeader("Attribute serialization code", OS);
1868 Record *InhClass = Records.getClass("InheritableAttr");
1869 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
1871 OS << " switch (A->getKind()) {\n";
1872 OS << " default:\n";
1873 OS << " llvm_unreachable(\"Unknown attribute kind!\");\n";
1875 for (const auto *Attr : Attrs) {
1876 const Record &R = *Attr;
1877 if (!R.getValueAsBit("ASTNode"))
1879 OS << " case attr::" << R.getName() << ": {\n";
1880 Args = R.getValueAsListOfDefs("Args");
1881 if (R.isSubClassOf(InhClass) || !Args.empty())
1882 OS << " const auto *SA = cast<" << R.getName()
1884 if (R.isSubClassOf(InhClass))
1885 OS << " Record.push_back(SA->isInherited());\n";
1886 OS << " Record.push_back(A->isImplicit());\n";
1887 OS << " Record.push_back(A->getSpellingListIndex());\n";
1889 for (const auto *Arg : Args)
1890 createArgument(*Arg, R.getName())->writePCHWrite(OS);
1897 // Generate a conditional expression to check if the current target satisfies
1898 // the conditions for a TargetSpecificAttr record, and append the code for
1899 // those checks to the Test string. If the FnName string pointer is non-null,
1900 // append a unique suffix to distinguish this set of target checks from other
1901 // TargetSpecificAttr records.
1902 static void GenerateTargetSpecificAttrChecks(const Record *R,
1903 std::vector<std::string> &Arches,
1905 std::string *FnName) {
1906 // It is assumed that there will be an llvm::Triple object
1907 // named "T" and a TargetInfo object named "Target" within
1908 // scope that can be used to determine whether the attribute exists in
1912 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
1913 std::string Part = *I;
1914 Test += "T.getArch() == llvm::Triple::" + Part;
1922 // If the attribute is specific to particular OSes, check those.
1923 if (!R->isValueUnset("OSes")) {
1924 // We know that there was at least one arch test, so we need to and in the
1927 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes");
1928 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) {
1929 std::string Part = *I;
1931 Test += "T.getOS() == llvm::Triple::" + Part;
1940 // If one or more CXX ABIs are specified, check those as well.
1941 if (!R->isValueUnset("CXXABIs")) {
1943 std::vector<std::string> CXXABIs = R->getValueAsListOfStrings("CXXABIs");
1944 for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) {
1945 std::string Part = *I;
1946 Test += "Target.getCXXABI().getKind() == TargetCXXABI::" + Part;
1956 static void GenerateHasAttrSpellingStringSwitch(
1957 const std::vector<Record *> &Attrs, raw_ostream &OS,
1958 const std::string &Variety = "", const std::string &Scope = "") {
1959 for (const auto *Attr : Attrs) {
1960 // C++11-style attributes have specific version information associated with
1961 // them. If the attribute has no scope, the version information must not
1962 // have the default value (1), as that's incorrect. Instead, the unscoped
1963 // attribute version information should be taken from the SD-6 standing
1964 // document, which can be found at:
1965 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
1968 if (Variety == "CXX11") {
1969 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
1970 for (const auto &Spelling : Spellings) {
1971 if (Spelling->getValueAsString("Variety") == "CXX11") {
1972 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
1973 if (Scope.empty() && Version == 1)
1974 PrintError(Spelling->getLoc(), "C++ standard attributes must "
1975 "have valid version information.");
1982 if (Attr->isSubClassOf("TargetSpecificAttr")) {
1983 const Record *R = Attr->getValueAsDef("Target");
1984 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
1985 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
1987 // If this is the C++11 variety, also add in the LangOpts test.
1988 if (Variety == "CXX11")
1989 Test += " && LangOpts.CPlusPlus11";
1990 } else if (Variety == "CXX11")
1991 // C++11 mode should be checked against LangOpts, which is presumed to be
1992 // present in the caller.
1993 Test = "LangOpts.CPlusPlus11";
1995 std::string TestStr =
1996 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
1997 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1998 for (const auto &S : Spellings)
1999 if (Variety.empty() || (Variety == S.variety() &&
2000 (Scope.empty() || Scope == S.nameSpace())))
2001 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
2003 OS << " .Default(0);\n";
2006 // Emits the list of spellings for attributes.
2007 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2008 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2010 // Separate all of the attributes out into four group: generic, C++11, GNU,
2011 // and declspecs. Then generate a big switch statement for each of them.
2012 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2013 std::vector<Record *> Declspec, GNU, Pragma;
2014 std::map<std::string, std::vector<Record *>> CXX;
2016 // Walk over the list of all attributes, and split them out based on the
2017 // spelling variety.
2018 for (auto *R : Attrs) {
2019 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2020 for (const auto &SI : Spellings) {
2021 std::string Variety = SI.variety();
2022 if (Variety == "GNU")
2024 else if (Variety == "Declspec")
2025 Declspec.push_back(R);
2026 else if (Variety == "CXX11")
2027 CXX[SI.nameSpace()].push_back(R);
2028 else if (Variety == "Pragma")
2029 Pragma.push_back(R);
2033 OS << "const llvm::Triple &T = Target.getTriple();\n";
2034 OS << "switch (Syntax) {\n";
2035 OS << "case AttrSyntax::GNU:\n";
2036 OS << " return llvm::StringSwitch<int>(Name)\n";
2037 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2038 OS << "case AttrSyntax::Declspec:\n";
2039 OS << " return llvm::StringSwitch<int>(Name)\n";
2040 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
2041 OS << "case AttrSyntax::Pragma:\n";
2042 OS << " return llvm::StringSwitch<int>(Name)\n";
2043 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
2044 OS << "case AttrSyntax::CXX: {\n";
2045 // C++11-style attributes are further split out based on the Scope.
2046 for (auto I = CXX.cbegin(), E = CXX.cend(); I != E; ++I) {
2047 if (I != CXX.begin())
2049 if (I->first.empty())
2050 OS << "if (!Scope || Scope->getName() == \"\") {\n";
2052 OS << "if (Scope->getName() == \"" << I->first << "\") {\n";
2053 OS << " return llvm::StringSwitch<int>(Name)\n";
2054 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first);
2061 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
2062 emitSourceFileHeader("Code to translate different attribute spellings "
2063 "into internal identifiers", OS);
2066 " switch (AttrKind) {\n"
2068 " llvm_unreachable(\"Unknown attribute kind!\");\n"
2071 ParsedAttrMap Attrs = getParsedAttrList(Records);
2072 for (const auto &I : Attrs) {
2073 const Record &R = *I.second;
2074 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2075 OS << " case AT_" << I.first << ": {\n";
2076 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2077 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2079 << StringSwitch<unsigned>(Spellings[I].variety())
2082 .Case("Declspec", 2)
2086 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2087 << " return " << I << ";\n";
2095 OS << " return 0;\n";
2098 // Emits code used by RecursiveASTVisitor to visit attributes
2099 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2100 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2102 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2104 // Write method declarations for Traverse* methods.
2105 // We emit this here because we only generate methods for attributes that
2106 // are declared as ASTNodes.
2107 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2108 for (const auto *Attr : Attrs) {
2109 const Record &R = *Attr;
2110 if (!R.getValueAsBit("ASTNode"))
2112 OS << " bool Traverse"
2113 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
2115 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2116 << " return true; \n"
2119 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
2121 // Write individual Traverse* methods for each attribute class.
2122 for (const auto *Attr : Attrs) {
2123 const Record &R = *Attr;
2124 if (!R.getValueAsBit("ASTNode"))
2127 OS << "template <typename Derived>\n"
2128 << "bool VISITORCLASS<Derived>::Traverse"
2129 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
2130 << " if (!getDerived().VisitAttr(A))\n"
2131 << " return false;\n"
2132 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
2133 << " return false;\n";
2135 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2136 for (const auto *Arg : ArgRecords)
2137 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
2139 OS << " return true;\n";
2143 // Write generic Traverse routine
2144 OS << "template <typename Derived>\n"
2145 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
2147 << " return true;\n"
2149 << " switch (A->getKind()) {\n"
2151 << " return true;\n";
2153 for (const auto *Attr : Attrs) {
2154 const Record &R = *Attr;
2155 if (!R.getValueAsBit("ASTNode"))
2158 OS << " case attr::" << R.getName() << ":\n"
2159 << " return getDerived().Traverse" << R.getName() << "Attr("
2160 << "cast<" << R.getName() << "Attr>(A));\n";
2162 OS << " }\n"; // end case
2163 OS << "}\n"; // end function
2164 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
2167 // Emits code to instantiate dependent attributes on templates.
2168 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
2169 emitSourceFileHeader("Template instantiation code for attributes", OS);
2171 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2173 OS << "namespace clang {\n"
2174 << "namespace sema {\n\n"
2175 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
2177 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n"
2178 << " switch (At->getKind()) {\n"
2182 for (const auto *Attr : Attrs) {
2183 const Record &R = *Attr;
2184 if (!R.getValueAsBit("ASTNode"))
2187 OS << " case attr::" << R.getName() << ": {\n";
2188 bool ShouldClone = R.getValueAsBit("Clone");
2191 OS << " return nullptr;\n";
2196 OS << " const auto *A = cast<"
2197 << R.getName() << "Attr>(At);\n";
2198 bool TDependent = R.getValueAsBit("TemplateDependent");
2201 OS << " return A->clone(C);\n";
2206 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2207 std::vector<std::unique_ptr<Argument>> Args;
2208 Args.reserve(ArgRecords.size());
2210 for (const auto *ArgRecord : ArgRecords)
2211 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2213 for (auto const &ai : Args)
2214 ai->writeTemplateInstantiation(OS);
2216 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
2217 for (auto const &ai : Args) {
2219 ai->writeTemplateInstantiationArgs(OS);
2221 OS << ", A->getSpellingListIndex());\n }\n";
2223 OS << " } // end switch\n"
2224 << " llvm_unreachable(\"Unknown attribute!\");\n"
2225 << " return nullptr;\n"
2227 << "} // end namespace sema\n"
2228 << "} // end namespace clang\n";
2231 // Emits the list of parsed attributes.
2232 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
2233 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2235 OS << "#ifndef PARSED_ATTR\n";
2236 OS << "#define PARSED_ATTR(NAME) NAME\n";
2239 ParsedAttrMap Names = getParsedAttrList(Records);
2240 for (const auto &I : Names) {
2241 OS << "PARSED_ATTR(" << I.first << ")\n";
2245 static bool isArgVariadic(const Record &R, StringRef AttrName) {
2246 return createArgument(R, AttrName)->isVariadic();
2249 static void emitArgInfo(const Record &R, std::stringstream &OS) {
2250 // This function will count the number of arguments specified for the
2251 // attribute and emit the number of required arguments followed by the
2252 // number of optional arguments.
2253 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
2254 unsigned ArgCount = 0, OptCount = 0;
2255 bool HasVariadic = false;
2256 for (const auto *Arg : Args) {
2257 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
2258 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
2262 // If there is a variadic argument, we will set the optional argument count
2263 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
2264 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
2267 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
2268 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,";
2269 OS << "const Decl *) {\n";
2270 OS << " return true;\n";
2274 static std::string CalculateDiagnostic(const Record &S) {
2275 // If the SubjectList object has a custom diagnostic associated with it,
2276 // return that directly.
2277 std::string CustomDiag = S.getValueAsString("CustomDiag");
2278 if (!CustomDiag.empty())
2281 // Given the list of subjects, determine what diagnostic best fits.
2285 ObjCMethod = 1U << 2,
2288 GenericRecord = 1U << 5,
2292 ObjCInterface = 1U << 9,
2294 Namespace = 1U << 11,
2296 CXXMethod = 1U << 13,
2297 ObjCProtocol = 1U << 14,
2300 uint32_t SubMask = 0;
2302 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
2303 for (const auto *Subject : Subjects) {
2304 const Record &R = *Subject;
2307 if (R.isSubClassOf("SubsetSubject")) {
2308 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic");
2309 // As a fallback, look through the SubsetSubject to see what its base
2310 // type is, and use that. This needs to be updated if SubsetSubjects
2311 // are allowed within other SubsetSubjects.
2312 Name = R.getValueAsDef("Base")->getName();
2316 uint32_t V = StringSwitch<uint32_t>(Name)
2317 .Case("Function", Func)
2319 .Case("ObjCMethod", ObjCMethod)
2320 .Case("ParmVar", Param)
2321 .Case("TypedefName", Type)
2322 .Case("ObjCIvar", ObjCIVar)
2323 .Case("ObjCProperty", ObjCProp)
2324 .Case("Record", GenericRecord)
2325 .Case("ObjCInterface", ObjCInterface)
2326 .Case("ObjCProtocol", ObjCProtocol)
2327 .Case("Block", Block)
2328 .Case("CXXRecord", Class)
2329 .Case("Namespace", Namespace)
2330 .Case("Field", Field)
2331 .Case("CXXMethod", CXXMethod)
2335 // Something wasn't in our mapping, so be helpful and let the developer
2337 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName());
2345 // For the simple cases where there's only a single entry in the mask, we
2346 // don't have to resort to bit fiddling.
2347 case Func: return "ExpectedFunction";
2348 case Var: return "ExpectedVariable";
2349 case Param: return "ExpectedParameter";
2350 case Class: return "ExpectedClass";
2351 case Enum: return "ExpectedEnum";
2353 // FIXME: Currently, this maps to ExpectedMethod based on existing code,
2354 // but should map to something a bit more accurate at some point.
2355 case ObjCMethod: return "ExpectedMethod";
2356 case Type: return "ExpectedType";
2357 case ObjCInterface: return "ExpectedObjectiveCInterface";
2358 case ObjCProtocol: return "ExpectedObjectiveCProtocol";
2360 // "GenericRecord" means struct, union or class; check the language options
2361 // and if not compiling for C++, strip off the class part. Note that this
2362 // relies on the fact that the context for this declares "Sema &S".
2364 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : "
2365 "ExpectedStructOrUnion)";
2366 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock";
2367 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass";
2369 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter";
2370 case Func | ObjCMethod: return "ExpectedFunctionOrMethod";
2371 case Func | Var: return "ExpectedVariableOrFunction";
2373 // If not compiling for C++, the class portion does not apply.
2374 case Func | Var | Class:
2375 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : "
2376 "ExpectedVariableOrFunction)";
2378 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty";
2379 case ObjCProtocol | ObjCInterface:
2380 return "ExpectedObjectiveCInterfaceOrProtocol";
2381 case Field | Var: return "ExpectedFieldOrGlobalVar";
2384 PrintFatalError(S.getLoc(),
2385 "Could not deduce diagnostic argument for Attr subjects");
2390 static std::string GetSubjectWithSuffix(const Record *R) {
2391 std::string B = R->getName();
2392 if (B == "DeclBase")
2397 static std::string GenerateCustomAppertainsTo(const Record &Subject,
2399 std::string FnName = "is" + Subject.getName();
2401 // If this code has already been generated, simply return the previous
2403 static std::set<std::string> CustomSubjectSet;
2404 auto I = CustomSubjectSet.find(FnName);
2405 if (I != CustomSubjectSet.end())
2408 Record *Base = Subject.getValueAsDef("Base");
2410 // Not currently support custom subjects within custom subjects.
2411 if (Base->isSubClassOf("SubsetSubject")) {
2412 PrintFatalError(Subject.getLoc(),
2413 "SubsetSubjects within SubsetSubjects is not supported");
2417 OS << "static bool " << FnName << "(const Decl *D) {\n";
2418 OS << " if (const auto *S = dyn_cast<";
2419 OS << GetSubjectWithSuffix(Base);
2421 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
2422 OS << " return false;\n";
2425 CustomSubjectSet.insert(FnName);
2429 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
2430 // If the attribute does not contain a Subjects definition, then use the
2431 // default appertainsTo logic.
2432 if (Attr.isValueUnset("Subjects"))
2433 return "defaultAppertainsTo";
2435 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
2436 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
2438 // If the list of subjects is empty, it is assumed that the attribute
2439 // appertains to everything.
2440 if (Subjects.empty())
2441 return "defaultAppertainsTo";
2443 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
2445 // Otherwise, generate an appertainsTo check specific to this attribute which
2446 // checks all of the given subjects against the Decl passed in. Return the
2447 // name of that check to the caller.
2448 std::string FnName = "check" + Attr.getName() + "AppertainsTo";
2449 std::stringstream SS;
2450 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, ";
2451 SS << "const Decl *D) {\n";
2453 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
2454 // If the subject has custom code associated with it, generate a function
2455 // for it. The function cannot be inlined into this check (yet) because it
2456 // requires the subject to be of a specific type, and were that information
2457 // inlined here, it would not support an attribute with multiple custom
2459 if ((*I)->isSubClassOf("SubsetSubject")) {
2460 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
2462 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
2469 SS << " S.Diag(Attr.getLoc(), diag::";
2470 SS << (Warn ? "warn_attribute_wrong_decl_type" :
2471 "err_attribute_wrong_decl_type");
2473 SS << " << Attr.getName() << ";
2474 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
2475 SS << " return false;\n";
2477 SS << " return true;\n";
2484 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
2485 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
2486 OS << "const AttributeList &) {\n";
2487 OS << " return true;\n";
2491 static std::string GenerateLangOptRequirements(const Record &R,
2493 // If the attribute has an empty or unset list of language requirements,
2494 // return the default handler.
2495 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
2496 if (LangOpts.empty())
2497 return "defaultDiagnoseLangOpts";
2499 // Generate the test condition, as well as a unique function name for the
2500 // diagnostic test. The list of options should usually be short (one or two
2501 // options), and the uniqueness isn't strictly necessary (it is just for
2502 // codegen efficiency).
2503 std::string FnName = "check", Test;
2504 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
2505 std::string Part = (*I)->getValueAsString("Name");
2506 if ((*I)->getValueAsBit("Negated"))
2508 Test += "S.LangOpts." + Part;
2513 FnName += "LangOpts";
2515 // If this code has already been generated, simply return the previous
2517 static std::set<std::string> CustomLangOptsSet;
2518 auto I = CustomLangOptsSet.find(FnName);
2519 if (I != CustomLangOptsSet.end())
2522 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n";
2523 OS << " if (" << Test << ")\n";
2524 OS << " return true;\n\n";
2525 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
2526 OS << "<< Attr.getName();\n";
2527 OS << " return false;\n";
2530 CustomLangOptsSet.insert(FnName);
2534 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
2535 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
2536 OS << " return true;\n";
2540 static std::string GenerateTargetRequirements(const Record &Attr,
2541 const ParsedAttrMap &Dupes,
2543 // If the attribute is not a target specific attribute, return the default
2545 if (!Attr.isSubClassOf("TargetSpecificAttr"))
2546 return "defaultTargetRequirements";
2548 // Get the list of architectures to be tested for.
2549 const Record *R = Attr.getValueAsDef("Target");
2550 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches");
2551 if (Arches.empty()) {
2552 PrintError(Attr.getLoc(), "Empty list of target architectures for a "
2553 "target-specific attr");
2554 return "defaultTargetRequirements";
2557 // If there are other attributes which share the same parsed attribute kind,
2558 // such as target-specific attributes with a shared spelling, collapse the
2559 // duplicate architectures. This is required because a shared target-specific
2560 // attribute has only one AttributeList::Kind enumeration value, but it
2561 // applies to multiple target architectures. In order for the attribute to be
2562 // considered valid, all of its architectures need to be included.
2563 if (!Attr.isValueUnset("ParseKind")) {
2564 std::string APK = Attr.getValueAsString("ParseKind");
2565 for (const auto &I : Dupes) {
2566 if (I.first == APK) {
2567 std::vector<std::string> DA = I.second->getValueAsDef("Target")
2568 ->getValueAsListOfStrings("Arches");
2569 std::copy(DA.begin(), DA.end(), std::back_inserter(Arches));
2574 std::string FnName = "isTarget";
2576 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
2578 // If this code has already been generated, simply return the previous
2580 static std::set<std::string> CustomTargetSet;
2581 auto I = CustomTargetSet.find(FnName);
2582 if (I != CustomTargetSet.end())
2585 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
2586 OS << " const llvm::Triple &T = Target.getTriple();\n";
2587 OS << " return " << Test << ";\n";
2590 CustomTargetSet.insert(FnName);
2594 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
2595 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
2596 << "const AttributeList &Attr) {\n";
2597 OS << " return UINT_MAX;\n";
2601 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
2603 // If the attribute does not have a semantic form, we can bail out early.
2604 if (!Attr.getValueAsBit("ASTNode"))
2605 return "defaultSpellingIndexToSemanticSpelling";
2607 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2609 // If there are zero or one spellings, or all of the spellings share the same
2610 // name, we can also bail out early.
2611 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
2612 return "defaultSpellingIndexToSemanticSpelling";
2614 // Generate the enumeration we will use for the mapping.
2615 SemanticSpellingMap SemanticToSyntacticMap;
2616 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2617 std::string Name = Attr.getName() + "AttrSpellingMap";
2619 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n";
2621 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
2622 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
2628 static bool IsKnownToGCC(const Record &Attr) {
2629 // Look at the spellings for this subject; if there are any spellings which
2630 // claim to be known to GCC, the attribute is known to GCC.
2631 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2632 for (const auto &I : Spellings) {
2639 /// Emits the parsed attribute helpers
2640 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2641 emitSourceFileHeader("Parsed attribute helpers", OS);
2643 // Get the list of parsed attributes, and accept the optional list of
2644 // duplicates due to the ParseKind.
2645 ParsedAttrMap Dupes;
2646 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
2648 // Generate the default appertainsTo, target and language option diagnostic,
2649 // and spelling list index mapping methods.
2650 GenerateDefaultAppertainsTo(OS);
2651 GenerateDefaultLangOptRequirements(OS);
2652 GenerateDefaultTargetRequirements(OS);
2653 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
2655 // Generate the appertainsTo diagnostic methods and write their names into
2656 // another mapping. At the same time, generate the AttrInfoMap object
2657 // contents. Due to the reliance on generated code, use separate streams so
2658 // that code will not be interleaved.
2659 std::stringstream SS;
2660 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
2661 // TODO: If the attribute's kind appears in the list of duplicates, that is
2662 // because it is a target-specific attribute that appears multiple times.
2663 // It would be beneficial to test whether the duplicates are "similar
2664 // enough" to each other to not cause problems. For instance, check that
2665 // the spellings are identical, and custom parsing rules match, etc.
2667 // We need to generate struct instances based off ParsedAttrInfo from
2668 // AttributeList.cpp.
2670 emitArgInfo(*I->second, SS);
2671 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
2672 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
2673 SS << ", " << I->second->isSubClassOf("TypeAttr");
2674 SS << ", " << IsKnownToGCC(*I->second);
2675 SS << ", " << GenerateAppertainsTo(*I->second, OS);
2676 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
2677 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
2678 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
2684 SS << " // AT_" << I->first << "\n";
2687 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n";
2692 // Emits the kind list of parsed attributes
2693 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
2694 emitSourceFileHeader("Attribute name matcher", OS);
2696 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2697 std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma;
2698 std::set<std::string> Seen;
2699 for (const auto *A : Attrs) {
2700 const Record &Attr = *A;
2702 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
2703 bool Ignored = Attr.getValueAsBit("Ignored");
2704 if (SemaHandler || Ignored) {
2705 // Attribute spellings can be shared between target-specific attributes,
2706 // and can be shared between syntaxes for the same attribute. For
2707 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
2708 // specific attribute, or MSP430-specific attribute. Additionally, an
2709 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
2710 // for the same semantic attribute. Ultimately, we need to map each of
2711 // these to a single AttributeList::Kind value, but the StringMatcher
2712 // class cannot handle duplicate match strings. So we generate a list of
2713 // string to match based on the syntax, and emit multiple string matchers
2714 // depending on the syntax used.
2715 std::string AttrName;
2716 if (Attr.isSubClassOf("TargetSpecificAttr") &&
2717 !Attr.isValueUnset("ParseKind")) {
2718 AttrName = Attr.getValueAsString("ParseKind");
2719 if (Seen.find(AttrName) != Seen.end())
2721 Seen.insert(AttrName);
2723 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
2725 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2726 for (const auto &S : Spellings) {
2727 std::string RawSpelling = S.name();
2728 std::vector<StringMatcher::StringPair> *Matches = nullptr;
2729 std::string Spelling, Variety = S.variety();
2730 if (Variety == "CXX11") {
2732 Spelling += S.nameSpace();
2734 } else if (Variety == "GNU")
2736 else if (Variety == "Declspec")
2737 Matches = &Declspec;
2738 else if (Variety == "Keyword")
2739 Matches = &Keywords;
2740 else if (Variety == "Pragma")
2743 assert(Matches && "Unsupported spelling variety found");
2745 Spelling += NormalizeAttrSpelling(RawSpelling);
2747 Matches->push_back(StringMatcher::StringPair(Spelling,
2748 "return AttributeList::AT_" + AttrName + ";"));
2750 Matches->push_back(StringMatcher::StringPair(Spelling,
2751 "return AttributeList::IgnoredAttribute;"));
2756 OS << "static AttributeList::Kind getAttrKind(StringRef Name, ";
2757 OS << "AttributeList::Syntax Syntax) {\n";
2758 OS << " if (AttributeList::AS_GNU == Syntax) {\n";
2759 StringMatcher("Name", GNU, OS).Emit();
2760 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n";
2761 StringMatcher("Name", Declspec, OS).Emit();
2762 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n";
2763 StringMatcher("Name", CXX11, OS).Emit();
2764 OS << " } else if (AttributeList::AS_Keyword == Syntax || ";
2765 OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n";
2766 StringMatcher("Name", Keywords, OS).Emit();
2767 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n";
2768 StringMatcher("Name", Pragma, OS).Emit();
2770 OS << " return AttributeList::UnknownAttribute;\n"
2774 // Emits the code to dump an attribute.
2775 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) {
2776 emitSourceFileHeader("Attribute dumper", OS);
2779 " switch (A->getKind()) {\n"
2781 " llvm_unreachable(\"Unknown attribute kind!\");\n"
2783 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2784 for (const auto *Attr : Attrs) {
2785 const Record &R = *Attr;
2786 if (!R.getValueAsBit("ASTNode"))
2788 OS << " case attr::" << R.getName() << ": {\n";
2790 // If the attribute has a semantically-meaningful name (which is determined
2791 // by whether there is a Spelling enumeration for it), then write out the
2792 // spelling used for the attribute.
2793 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2794 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
2795 OS << " OS << \" \" << A->getSpelling();\n";
2797 Args = R.getValueAsListOfDefs("Args");
2798 if (!Args.empty()) {
2799 OS << " const auto *SA = cast<" << R.getName()
2801 for (const auto *Arg : Args)
2802 createArgument(*Arg, R.getName())->writeDump(OS);
2804 for (const auto *AI : Args)
2805 createArgument(*AI, R.getName())->writeDumpChildren(OS);
2814 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
2816 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
2817 emitClangAttrArgContextList(Records, OS);
2818 emitClangAttrIdentifierArgList(Records, OS);
2819 emitClangAttrTypeArgList(Records, OS);
2820 emitClangAttrLateParsedList(Records, OS);
2823 class DocumentationData {
2825 const Record *Documentation;
2826 const Record *Attribute;
2828 DocumentationData(const Record &Documentation, const Record &Attribute)
2829 : Documentation(&Documentation), Attribute(&Attribute) {}
2832 static void WriteCategoryHeader(const Record *DocCategory,
2834 const std::string &Name = DocCategory->getValueAsString("Name");
2835 OS << Name << "\n" << std::string(Name.length(), '=') << "\n";
2837 // If there is content, print that as well.
2838 std::string ContentStr = DocCategory->getValueAsString("Content");
2839 // Trim leading and trailing newlines and spaces.
2840 OS << StringRef(ContentStr).trim();
2853 static void WriteDocumentation(const DocumentationData &Doc,
2855 // FIXME: there is no way to have a per-spelling category for the attribute
2856 // documentation. This may not be a limiting factor since the spellings
2857 // should generally be consistently applied across the category.
2859 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute);
2861 // Determine the heading to be used for this attribute.
2862 std::string Heading = Doc.Documentation->getValueAsString("Heading");
2863 bool CustomHeading = !Heading.empty();
2864 if (Heading.empty()) {
2865 // If there's only one spelling, we can simply use that.
2866 if (Spellings.size() == 1)
2867 Heading = Spellings.begin()->name();
2869 std::set<std::string> Uniques;
2870 for (auto I = Spellings.begin(), E = Spellings.end();
2871 I != E && Uniques.size() <= 1; ++I) {
2872 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
2873 Uniques.insert(Spelling);
2875 // If the semantic map has only one spelling, that is sufficient for our
2877 if (Uniques.size() == 1)
2878 Heading = *Uniques.begin();
2882 // If the heading is still empty, it is an error.
2883 if (Heading.empty())
2884 PrintFatalError(Doc.Attribute->getLoc(),
2885 "This attribute requires a heading to be specified");
2887 // Gather a list of unique spellings; this is not the same as the semantic
2888 // spelling for the attribute. Variations in underscores and other non-
2889 // semantic characters are still acceptable.
2890 std::vector<std::string> Names;
2892 unsigned SupportedSpellings = 0;
2893 for (const auto &I : Spellings) {
2894 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety())
2896 .Case("CXX11", CXX11)
2897 .Case("Declspec", Declspec)
2898 .Case("Keyword", Keyword)
2899 .Case("Pragma", Pragma);
2901 // Mask in the supported spelling.
2902 SupportedSpellings |= Kind;
2905 if (Kind == CXX11 && !I.nameSpace().empty())
2906 Name = I.nameSpace() + "::";
2909 // If this name is the same as the heading, do not add it.
2910 if (Name != Heading)
2911 Names.push_back(Name);
2914 // Print out the heading for the attribute. If there are alternate spellings,
2915 // then display those after the heading.
2916 if (!CustomHeading && !Names.empty()) {
2918 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) {
2919 if (I != Names.begin())
2925 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n";
2927 if (!SupportedSpellings)
2928 PrintFatalError(Doc.Attribute->getLoc(),
2929 "Attribute has no supported spellings; cannot be "
2932 // List what spelling syntaxes the attribute supports.
2933 OS << ".. csv-table:: Supported Syntaxes\n";
2934 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\",";
2935 OS << " \"Pragma\"\n\n";
2937 if (SupportedSpellings & GNU) OS << "X";
2939 if (SupportedSpellings & CXX11) OS << "X";
2941 if (SupportedSpellings & Declspec) OS << "X";
2943 if (SupportedSpellings & Keyword) OS << "X";
2945 if (SupportedSpellings & Pragma) OS << "X";
2948 // If the attribute is deprecated, print a message about it, and possibly
2949 // provide a replacement attribute.
2950 if (!Doc.Documentation->isValueUnset("Deprecated")) {
2951 OS << "This attribute has been deprecated, and may be removed in a future "
2952 << "version of Clang.";
2953 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
2954 std::string Replacement = Deprecated.getValueAsString("Replacement");
2955 if (!Replacement.empty())
2956 OS << " This attribute has been superseded by ``"
2957 << Replacement << "``.";
2961 std::string ContentStr = Doc.Documentation->getValueAsString("Content");
2962 // Trim leading and trailing newlines and spaces.
2963 OS << StringRef(ContentStr).trim();
2968 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
2969 // Get the documentation introduction paragraph.
2970 const Record *Documentation = Records.getDef("GlobalDocumentation");
2971 if (!Documentation) {
2972 PrintFatalError("The Documentation top-level definition is missing, "
2973 "no documentation will be generated.");
2977 OS << Documentation->getValueAsString("Intro") << "\n";
2979 // Gather the Documentation lists from each of the attributes, based on the
2980 // category provided.
2981 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2982 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
2983 for (const auto *A : Attrs) {
2984 const Record &Attr = *A;
2985 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
2986 for (const auto *D : Docs) {
2987 const Record &Doc = *D;
2988 const Record *Category = Doc.getValueAsDef("Category");
2989 // If the category is "undocumented", then there cannot be any other
2990 // documentation categories (otherwise, the attribute would become
2992 std::string Cat = Category->getValueAsString("Name");
2993 bool Undocumented = Cat == "Undocumented";
2994 if (Undocumented && Docs.size() > 1)
2995 PrintFatalError(Doc.getLoc(),
2996 "Attribute is \"Undocumented\", but has multiple "
2997 "documentation categories");
3000 SplitDocs[Category].push_back(DocumentationData(Doc, Attr));
3004 // Having split the attributes out based on what documentation goes where,
3005 // we can begin to generate sections of documentation.
3006 for (const auto &I : SplitDocs) {
3007 WriteCategoryHeader(I.first, OS);
3009 // Walk over each of the attributes in the category and write out their
3011 for (const auto &Doc : I.second)
3012 WriteDocumentation(Doc, OS);
3016 } // end namespace clang