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/ArrayRef.h"
15 #include "llvm/ADT/DenseMap.h"
16 #include "llvm/ADT/DenseSet.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallString.h"
19 #include "llvm/ADT/StringExtras.h"
20 #include "llvm/ADT/StringRef.h"
21 #include "llvm/ADT/StringSet.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/ADT/iterator_range.h"
24 #include "llvm/Support/ErrorHandling.h"
25 #include "llvm/Support/raw_ostream.h"
26 #include "llvm/TableGen/Error.h"
27 #include "llvm/TableGen/Record.h"
28 #include "llvm/TableGen/StringMatcher.h"
29 #include "llvm/TableGen/TableGenBackend.h"
47 class FlattenedSpelling {
52 FlattenedSpelling(const std::string &Variety, const std::string &Name,
53 const std::string &Namespace, bool KnownToGCC) :
54 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {}
55 explicit FlattenedSpelling(const Record &Spelling) :
56 V(Spelling.getValueAsString("Variety")),
57 N(Spelling.getValueAsString("Name")) {
59 assert(V != "GCC" && V != "Clang" &&
60 "Given a GCC spelling, which means this hasn't been flattened!");
61 if (V == "CXX11" || V == "C2x" || V == "Pragma")
62 NS = Spelling.getValueAsString("Namespace");
64 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset);
67 const std::string &variety() const { return V; }
68 const std::string &name() const { return N; }
69 const std::string &nameSpace() const { return NS; }
70 bool knownToGCC() const { return K; }
73 } // end anonymous namespace
75 static std::vector<FlattenedSpelling>
76 GetFlattenedSpellings(const Record &Attr) {
77 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings");
78 std::vector<FlattenedSpelling> Ret;
80 for (const auto &Spelling : Spellings) {
81 StringRef Variety = Spelling->getValueAsString("Variety");
82 StringRef Name = Spelling->getValueAsString("Name");
83 if (Variety == "GCC") {
84 // Gin up two new spelling objects to add into the list.
85 Ret.emplace_back("GNU", Name, "", true);
86 Ret.emplace_back("CXX11", Name, "gnu", true);
87 } else if (Variety == "Clang") {
88 Ret.emplace_back("GNU", Name, "", false);
89 Ret.emplace_back("CXX11", Name, "clang", false);
90 if (Spelling->getValueAsBit("AllowInC"))
91 Ret.emplace_back("C2x", Name, "clang", false);
93 Ret.push_back(FlattenedSpelling(*Spelling));
99 static std::string ReadPCHRecord(StringRef type) {
100 return StringSwitch<std::string>(type)
101 .EndsWith("Decl *", "Record.GetLocalDeclAs<"
102 + std::string(type, 0, type.size()-1) + ">(Record.readInt())")
103 .Case("TypeSourceInfo *", "Record.getTypeSourceInfo()")
104 .Case("Expr *", "Record.readExpr()")
105 .Case("IdentifierInfo *", "Record.getIdentifierInfo()")
106 .Case("StringRef", "Record.readString()")
107 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
108 .Default("Record.readInt()");
111 // Get a type that is suitable for storing an object of the specified type.
112 static StringRef getStorageType(StringRef type) {
113 return StringSwitch<StringRef>(type)
114 .Case("StringRef", "std::string")
118 // Assumes that the way to get the value is SA->getname()
119 static std::string WritePCHRecord(StringRef type, StringRef name) {
120 return "Record." + StringSwitch<std::string>(type)
121 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + ");\n")
122 .Case("TypeSourceInfo *", "AddTypeSourceInfo(" + std::string(name) + ");\n")
123 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n")
124 .Case("IdentifierInfo *", "AddIdentifierRef(" + std::string(name) + ");\n")
125 .Case("StringRef", "AddString(" + std::string(name) + ");\n")
126 .Case("ParamIdx", "push_back(" + std::string(name) + ".serialize());\n")
127 .Default("push_back(" + std::string(name) + ");\n");
130 // Normalize attribute name by removing leading and trailing
131 // underscores. For example, __foo, foo__, __foo__ would
133 static StringRef NormalizeAttrName(StringRef AttrName) {
134 AttrName.consume_front("__");
135 AttrName.consume_back("__");
139 // Normalize the name by removing any and all leading and trailing underscores.
140 // This is different from NormalizeAttrName in that it also handles names like
141 // _pascal and __pascal.
142 static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
143 return Name.trim("_");
146 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
147 // removing "__" if it appears at the beginning and end of the attribute's name.
148 static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
149 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) {
150 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4);
156 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
158 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
159 ParsedAttrMap *Dupes = nullptr) {
160 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
161 std::set<std::string> Seen;
163 for (const auto *Attr : Attrs) {
164 if (Attr->getValueAsBit("SemaHandler")) {
166 if (Attr->isSubClassOf("TargetSpecificAttr") &&
167 !Attr->isValueUnset("ParseKind")) {
168 AN = Attr->getValueAsString("ParseKind");
170 // If this attribute has already been handled, it does not need to be
172 if (Seen.find(AN) != Seen.end()) {
174 Dupes->push_back(std::make_pair(AN, Attr));
179 AN = NormalizeAttrName(Attr->getName()).str();
181 R.push_back(std::make_pair(AN, Attr));
190 std::string lowerName, upperName;
196 Argument(const Record &Arg, StringRef Attr)
197 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName),
198 attrName(Attr), isOpt(false), Fake(false) {
199 if (!lowerName.empty()) {
200 lowerName[0] = std::tolower(lowerName[0]);
201 upperName[0] = std::toupper(upperName[0]);
203 // Work around MinGW's macro definition of 'interface' to 'struct'. We
204 // have an attribute argument called 'Interface', so only the lower case
205 // name conflicts with the macro definition.
206 if (lowerName == "interface")
207 lowerName = "interface_";
209 virtual ~Argument() = default;
211 StringRef getLowerName() const { return lowerName; }
212 StringRef getUpperName() const { return upperName; }
213 StringRef getAttrName() const { return attrName; }
215 bool isOptional() const { return isOpt; }
216 void setOptional(bool set) { isOpt = set; }
218 bool isFake() const { return Fake; }
219 void setFake(bool fake) { Fake = fake; }
221 // These functions print the argument contents formatted in different ways.
222 virtual void writeAccessors(raw_ostream &OS) const = 0;
223 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
224 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
225 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
226 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
227 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
228 virtual void writeCtorBody(raw_ostream &OS) const {}
229 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
230 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
231 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
232 virtual void writeDeclarations(raw_ostream &OS) const = 0;
233 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
234 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
235 virtual void writePCHWrite(raw_ostream &OS) const = 0;
236 virtual std::string getIsOmitted() const { return "false"; }
237 virtual void writeValue(raw_ostream &OS) const = 0;
238 virtual void writeDump(raw_ostream &OS) const = 0;
239 virtual void writeDumpChildren(raw_ostream &OS) const {}
240 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
242 virtual bool isEnumArg() const { return false; }
243 virtual bool isVariadicEnumArg() const { return false; }
244 virtual bool isVariadic() const { return false; }
246 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
247 OS << getUpperName();
251 class SimpleArgument : public Argument {
255 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
256 : Argument(Arg, Attr), type(std::move(T)) {}
258 std::string getType() const { return type; }
260 void writeAccessors(raw_ostream &OS) const override {
261 OS << " " << type << " get" << getUpperName() << "() const {\n";
262 OS << " return " << getLowerName() << ";\n";
266 void writeCloneArgs(raw_ostream &OS) const override {
267 OS << getLowerName();
270 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
271 OS << "A->get" << getUpperName() << "()";
274 void writeCtorInitializers(raw_ostream &OS) const override {
275 OS << getLowerName() << "(" << getUpperName() << ")";
278 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
279 OS << getLowerName() << "()";
282 void writeCtorParameters(raw_ostream &OS) const override {
283 OS << type << " " << getUpperName();
286 void writeDeclarations(raw_ostream &OS) const override {
287 OS << type << " " << getLowerName() << ";";
290 void writePCHReadDecls(raw_ostream &OS) const override {
291 std::string read = ReadPCHRecord(type);
292 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
295 void writePCHReadArgs(raw_ostream &OS) const override {
296 OS << getLowerName();
299 void writePCHWrite(raw_ostream &OS) const override {
300 OS << " " << WritePCHRecord(type, "SA->get" +
301 std::string(getUpperName()) + "()");
304 std::string getIsOmitted() const override {
305 if (type == "IdentifierInfo *")
306 return "!get" + getUpperName().str() + "()";
307 if (type == "ParamIdx")
308 return "!get" + getUpperName().str() + "().isValid()";
312 void writeValue(raw_ostream &OS) const override {
313 if (type == "FunctionDecl *")
314 OS << "\" << get" << getUpperName()
315 << "()->getNameInfo().getAsString() << \"";
316 else if (type == "IdentifierInfo *")
317 // Some non-optional (comma required) identifier arguments can be the
318 // empty string but are then recorded as a nullptr.
319 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
320 << "()->getName() : \"\") << \"";
321 else if (type == "TypeSourceInfo *")
322 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
323 else if (type == "ParamIdx")
324 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
326 OS << "\" << get" << getUpperName() << "() << \"";
329 void writeDump(raw_ostream &OS) const override {
330 if (type == "FunctionDecl *" || type == "NamedDecl *") {
331 OS << " OS << \" \";\n";
332 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
333 } else if (type == "IdentifierInfo *") {
334 // Some non-optional (comma required) identifier arguments can be the
335 // empty string but are then recorded as a nullptr.
336 OS << " if (SA->get" << getUpperName() << "())\n"
337 << " OS << \" \" << SA->get" << getUpperName()
338 << "()->getName();\n";
339 } else if (type == "TypeSourceInfo *") {
340 OS << " OS << \" \" << SA->get" << getUpperName()
341 << "().getAsString();\n";
342 } else if (type == "bool") {
343 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
344 << getUpperName() << "\";\n";
345 } else if (type == "int" || type == "unsigned") {
346 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
347 } else if (type == "ParamIdx") {
349 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
350 OS << " OS << \" \" << SA->get" << getUpperName()
351 << "().getSourceIndex();\n";
353 llvm_unreachable("Unknown SimpleArgument type!");
358 class DefaultSimpleArgument : public SimpleArgument {
362 DefaultSimpleArgument(const Record &Arg, StringRef Attr,
363 std::string T, int64_t Default)
364 : SimpleArgument(Arg, Attr, T), Default(Default) {}
366 void writeAccessors(raw_ostream &OS) const override {
367 SimpleArgument::writeAccessors(OS);
369 OS << "\n\n static const " << getType() << " Default" << getUpperName()
371 if (getType() == "bool")
372 OS << (Default != 0 ? "true" : "false");
379 class StringArgument : public Argument {
381 StringArgument(const Record &Arg, StringRef Attr)
382 : Argument(Arg, Attr)
385 void writeAccessors(raw_ostream &OS) const override {
386 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
387 OS << " return llvm::StringRef(" << getLowerName() << ", "
388 << getLowerName() << "Length);\n";
390 OS << " unsigned get" << getUpperName() << "Length() const {\n";
391 OS << " return " << getLowerName() << "Length;\n";
393 OS << " void set" << getUpperName()
394 << "(ASTContext &C, llvm::StringRef S) {\n";
395 OS << " " << getLowerName() << "Length = S.size();\n";
396 OS << " this->" << getLowerName() << " = new (C, 1) char ["
397 << getLowerName() << "Length];\n";
398 OS << " if (!S.empty())\n";
399 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
400 << getLowerName() << "Length);\n";
404 void writeCloneArgs(raw_ostream &OS) const override {
405 OS << "get" << getUpperName() << "()";
408 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
409 OS << "A->get" << getUpperName() << "()";
412 void writeCtorBody(raw_ostream &OS) const override {
413 OS << " if (!" << getUpperName() << ".empty())\n";
414 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
415 << ".data(), " << getLowerName() << "Length);\n";
418 void writeCtorInitializers(raw_ostream &OS) const override {
419 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
420 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
424 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
425 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
428 void writeCtorParameters(raw_ostream &OS) const override {
429 OS << "llvm::StringRef " << getUpperName();
432 void writeDeclarations(raw_ostream &OS) const override {
433 OS << "unsigned " << getLowerName() << "Length;\n";
434 OS << "char *" << getLowerName() << ";";
437 void writePCHReadDecls(raw_ostream &OS) const override {
438 OS << " std::string " << getLowerName()
439 << "= Record.readString();\n";
442 void writePCHReadArgs(raw_ostream &OS) const override {
443 OS << getLowerName();
446 void writePCHWrite(raw_ostream &OS) const override {
447 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
450 void writeValue(raw_ostream &OS) const override {
451 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
454 void writeDump(raw_ostream &OS) const override {
455 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
456 << "() << \"\\\"\";\n";
460 class AlignedArgument : public Argument {
462 AlignedArgument(const Record &Arg, StringRef Attr)
463 : Argument(Arg, Attr)
466 void writeAccessors(raw_ostream &OS) const override {
467 OS << " bool is" << getUpperName() << "Dependent() const;\n";
469 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
471 OS << " bool is" << getUpperName() << "Expr() const {\n";
472 OS << " return is" << getLowerName() << "Expr;\n";
475 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
476 OS << " assert(is" << getLowerName() << "Expr);\n";
477 OS << " return " << getLowerName() << "Expr;\n";
480 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
481 OS << " assert(!is" << getLowerName() << "Expr);\n";
482 OS << " return " << getLowerName() << "Type;\n";
486 void writeAccessorDefinitions(raw_ostream &OS) const override {
487 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
488 << "Dependent() const {\n";
489 OS << " if (is" << getLowerName() << "Expr)\n";
490 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
491 << "Expr->isValueDependent() || " << getLowerName()
492 << "Expr->isTypeDependent());\n";
494 OS << " return " << getLowerName()
495 << "Type->getType()->isDependentType();\n";
498 // FIXME: Do not do the calculation here
499 // FIXME: Handle types correctly
500 // A null pointer means maximum alignment
501 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName()
502 << "(ASTContext &Ctx) const {\n";
503 OS << " assert(!is" << getUpperName() << "Dependent());\n";
504 OS << " if (is" << getLowerName() << "Expr)\n";
505 OS << " return " << getLowerName() << "Expr ? " << getLowerName()
506 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()"
507 << " * Ctx.getCharWidth() : "
508 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n";
510 OS << " return 0; // FIXME\n";
514 void writeASTVisitorTraversal(raw_ostream &OS) const override {
515 StringRef Name = getUpperName();
516 OS << " if (A->is" << Name << "Expr()) {\n"
517 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
518 << " return false;\n"
519 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
520 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
521 << " return false;\n"
525 void writeCloneArgs(raw_ostream &OS) const override {
526 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
527 << "Expr ? static_cast<void*>(" << getLowerName()
528 << "Expr) : " << getLowerName()
532 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
533 // FIXME: move the definition in Sema::InstantiateAttrs to here.
534 // In the meantime, aligned attributes are cloned.
537 void writeCtorBody(raw_ostream &OS) const override {
538 OS << " if (is" << getLowerName() << "Expr)\n";
539 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
540 << getUpperName() << ");\n";
542 OS << " " << getLowerName()
543 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
547 void writeCtorInitializers(raw_ostream &OS) const override {
548 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
551 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
552 OS << "is" << getLowerName() << "Expr(false)";
555 void writeCtorParameters(raw_ostream &OS) const override {
556 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
559 void writeImplicitCtorArgs(raw_ostream &OS) const override {
560 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
563 void writeDeclarations(raw_ostream &OS) const override {
564 OS << "bool is" << getLowerName() << "Expr;\n";
566 OS << "Expr *" << getLowerName() << "Expr;\n";
567 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
571 void writePCHReadArgs(raw_ostream &OS) const override {
572 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
575 void writePCHReadDecls(raw_ostream &OS) const override {
576 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
577 OS << " void *" << getLowerName() << "Ptr;\n";
578 OS << " if (is" << getLowerName() << "Expr)\n";
579 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
581 OS << " " << getLowerName()
582 << "Ptr = Record.getTypeSourceInfo();\n";
585 void writePCHWrite(raw_ostream &OS) const override {
586 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
587 OS << " if (SA->is" << getUpperName() << "Expr())\n";
588 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
590 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
594 std::string getIsOmitted() const override {
595 return "!is" + getLowerName().str() + "Expr || !" + getLowerName().str()
599 void writeValue(raw_ostream &OS) const override {
601 OS << " " << getLowerName()
602 << "Expr->printPretty(OS, nullptr, Policy);\n";
606 void writeDump(raw_ostream &OS) const override {
607 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
608 OS << " dumpType(SA->get" << getUpperName()
609 << "Type()->getType());\n";
612 void writeDumpChildren(raw_ostream &OS) const override {
613 OS << " if (SA->is" << getUpperName() << "Expr())\n";
614 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n";
617 void writeHasChildren(raw_ostream &OS) const override {
618 OS << "SA->is" << getUpperName() << "Expr()";
622 class VariadicArgument : public Argument {
623 std::string Type, ArgName, ArgSizeName, RangeName;
626 // Assumed to receive a parameter: raw_ostream OS.
627 virtual void writeValueImpl(raw_ostream &OS) const {
628 OS << " OS << Val;\n";
630 // Assumed to receive a parameter: raw_ostream OS.
631 virtual void writeDumpImpl(raw_ostream &OS) const {
632 OS << " OS << \" \" << Val;\n";
636 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
637 : Argument(Arg, Attr), Type(std::move(T)),
638 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
639 RangeName(getLowerName()) {}
641 const std::string &getType() const { return Type; }
642 const std::string &getArgName() const { return ArgName; }
643 const std::string &getArgSizeName() const { return ArgSizeName; }
644 bool isVariadic() const override { return true; }
646 void writeAccessors(raw_ostream &OS) const override {
647 std::string IteratorType = getLowerName().str() + "_iterator";
648 std::string BeginFn = getLowerName().str() + "_begin()";
649 std::string EndFn = getLowerName().str() + "_end()";
651 OS << " typedef " << Type << "* " << IteratorType << ";\n";
652 OS << " " << IteratorType << " " << BeginFn << " const {"
653 << " return " << ArgName << "; }\n";
654 OS << " " << IteratorType << " " << EndFn << " const {"
655 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
656 OS << " unsigned " << getLowerName() << "_size() const {"
657 << " return " << ArgSizeName << "; }\n";
658 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
659 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
663 void writeCloneArgs(raw_ostream &OS) const override {
664 OS << ArgName << ", " << ArgSizeName;
667 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
668 // This isn't elegant, but we have to go through public methods...
669 OS << "A->" << getLowerName() << "_begin(), "
670 << "A->" << getLowerName() << "_size()";
673 void writeASTVisitorTraversal(raw_ostream &OS) const override {
674 // FIXME: Traverse the elements.
677 void writeCtorBody(raw_ostream &OS) const override {
678 OS << " std::copy(" << getUpperName() << ", " << getUpperName()
679 << " + " << ArgSizeName << ", " << ArgName << ");\n";
682 void writeCtorInitializers(raw_ostream &OS) const override {
683 OS << ArgSizeName << "(" << getUpperName() << "Size), "
684 << ArgName << "(new (Ctx, 16) " << getType() << "["
685 << ArgSizeName << "])";
688 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
689 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
692 void writeCtorParameters(raw_ostream &OS) const override {
693 OS << getType() << " *" << getUpperName() << ", unsigned "
694 << getUpperName() << "Size";
697 void writeImplicitCtorArgs(raw_ostream &OS) const override {
698 OS << getUpperName() << ", " << getUpperName() << "Size";
701 void writeDeclarations(raw_ostream &OS) const override {
702 OS << " unsigned " << ArgSizeName << ";\n";
703 OS << " " << getType() << " *" << ArgName << ";";
706 void writePCHReadDecls(raw_ostream &OS) const override {
707 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
708 OS << " SmallVector<" << getType() << ", 4> "
709 << getLowerName() << ";\n";
710 OS << " " << getLowerName() << ".reserve(" << getLowerName()
713 // If we can't store the values in the current type (if it's something
714 // like StringRef), store them in a different type and convert the
715 // container afterwards.
716 std::string StorageType = getStorageType(getType());
717 std::string StorageName = getLowerName();
718 if (StorageType != getType()) {
719 StorageName += "Storage";
720 OS << " SmallVector<" << StorageType << ", 4> "
721 << StorageName << ";\n";
722 OS << " " << StorageName << ".reserve(" << getLowerName()
726 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
727 std::string read = ReadPCHRecord(Type);
728 OS << " " << StorageName << ".push_back(" << read << ");\n";
730 if (StorageType != getType()) {
731 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
732 OS << " " << getLowerName() << ".push_back("
733 << StorageName << "[i]);\n";
737 void writePCHReadArgs(raw_ostream &OS) const override {
738 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
741 void writePCHWrite(raw_ostream &OS) const override {
742 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
743 OS << " for (auto &Val : SA->" << RangeName << "())\n";
744 OS << " " << WritePCHRecord(Type, "Val");
747 void writeValue(raw_ostream &OS) const override {
749 OS << " bool isFirst = true;\n"
750 << " for (const auto &Val : " << RangeName << "()) {\n"
751 << " if (isFirst) isFirst = false;\n"
752 << " else OS << \", \";\n";
758 void writeDump(raw_ostream &OS) const override {
759 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
764 class VariadicParamIdxArgument : public VariadicArgument {
766 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
767 : VariadicArgument(Arg, Attr, "ParamIdx") {}
770 void writeValueImpl(raw_ostream &OS) const override {
771 OS << " OS << Val.getSourceIndex();\n";
774 void writeDumpImpl(raw_ostream &OS) const override {
775 OS << " OS << \" \" << Val.getSourceIndex();\n";
779 // Unique the enums, but maintain the original declaration ordering.
780 std::vector<StringRef>
781 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
782 std::vector<StringRef> uniques;
783 SmallDenseSet<StringRef, 8> unique_set;
784 for (const auto &i : enums) {
785 if (unique_set.insert(i).second)
786 uniques.push_back(i);
791 class EnumArgument : public Argument {
793 std::vector<StringRef> values, enums, uniques;
796 EnumArgument(const Record &Arg, StringRef Attr)
797 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")),
798 values(Arg.getValueAsListOfStrings("Values")),
799 enums(Arg.getValueAsListOfStrings("Enums")),
800 uniques(uniqueEnumsInOrder(enums))
802 // FIXME: Emit a proper error
803 assert(!uniques.empty());
806 bool isEnumArg() const override { return true; }
808 void writeAccessors(raw_ostream &OS) const override {
809 OS << " " << type << " get" << getUpperName() << "() const {\n";
810 OS << " return " << getLowerName() << ";\n";
814 void writeCloneArgs(raw_ostream &OS) const override {
815 OS << getLowerName();
818 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
819 OS << "A->get" << getUpperName() << "()";
821 void writeCtorInitializers(raw_ostream &OS) const override {
822 OS << getLowerName() << "(" << getUpperName() << ")";
824 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
825 OS << getLowerName() << "(" << type << "(0))";
827 void writeCtorParameters(raw_ostream &OS) const override {
828 OS << type << " " << getUpperName();
830 void writeDeclarations(raw_ostream &OS) const override {
831 auto i = uniques.cbegin(), e = uniques.cend();
832 // The last one needs to not have a comma.
836 OS << " enum " << type << " {\n";
838 OS << " " << *i << ",\n";
839 OS << " " << *e << "\n";
842 OS << " " << type << " " << getLowerName() << ";";
845 void writePCHReadDecls(raw_ostream &OS) const override {
846 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName()
847 << "(static_cast<" << getAttrName() << "Attr::" << type
848 << ">(Record.readInt()));\n";
851 void writePCHReadArgs(raw_ostream &OS) const override {
852 OS << getLowerName();
855 void writePCHWrite(raw_ostream &OS) const override {
856 OS << "Record.push_back(SA->get" << getUpperName() << "());\n";
859 void writeValue(raw_ostream &OS) const override {
860 // FIXME: this isn't 100% correct -- some enum arguments require printing
861 // as a string literal, while others require printing as an identifier.
862 // Tablegen currently does not distinguish between the two forms.
863 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get"
864 << getUpperName() << "()) << \"\\\"";
867 void writeDump(raw_ostream &OS) const override {
868 OS << " switch(SA->get" << getUpperName() << "()) {\n";
869 for (const auto &I : uniques) {
870 OS << " case " << getAttrName() << "Attr::" << I << ":\n";
871 OS << " OS << \" " << I << "\";\n";
877 void writeConversion(raw_ostream &OS) const {
878 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
879 OS << type << " &Out) {\n";
880 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
881 OS << type << ">>(Val)\n";
882 for (size_t I = 0; I < enums.size(); ++I) {
883 OS << " .Case(\"" << values[I] << "\", ";
884 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
886 OS << " .Default(Optional<" << type << ">());\n";
888 OS << " Out = *R;\n return true;\n }\n";
889 OS << " return false;\n";
892 // Mapping from enumeration values back to enumeration strings isn't
893 // trivial because some enumeration values have multiple named
894 // enumerators, such as type_visibility(internal) and
895 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
896 OS << " static const char *Convert" << type << "ToStr("
897 << type << " Val) {\n"
898 << " switch(Val) {\n";
899 SmallDenseSet<StringRef, 8> Uniques;
900 for (size_t I = 0; I < enums.size(); ++I) {
901 if (Uniques.insert(enums[I]).second)
902 OS << " case " << getAttrName() << "Attr::" << enums[I]
903 << ": return \"" << values[I] << "\";\n";
906 << " llvm_unreachable(\"No enumerator with that value\");\n"
911 class VariadicEnumArgument: public VariadicArgument {
912 std::string type, QualifiedTypeName;
913 std::vector<StringRef> values, enums, uniques;
916 void writeValueImpl(raw_ostream &OS) const override {
917 // FIXME: this isn't 100% correct -- some enum arguments require printing
918 // as a string literal, while others require printing as an identifier.
919 // Tablegen currently does not distinguish between the two forms.
920 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type
921 << "ToStr(Val)" << "<< \"\\\"\";\n";
925 VariadicEnumArgument(const Record &Arg, StringRef Attr)
926 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")),
927 type(Arg.getValueAsString("Type")),
928 values(Arg.getValueAsListOfStrings("Values")),
929 enums(Arg.getValueAsListOfStrings("Enums")),
930 uniques(uniqueEnumsInOrder(enums))
932 QualifiedTypeName = getAttrName().str() + "Attr::" + type;
934 // FIXME: Emit a proper error
935 assert(!uniques.empty());
938 bool isVariadicEnumArg() const override { return true; }
940 void writeDeclarations(raw_ostream &OS) const override {
941 auto i = uniques.cbegin(), e = uniques.cend();
942 // The last one needs to not have a comma.
946 OS << " enum " << type << " {\n";
948 OS << " " << *i << ",\n";
949 OS << " " << *e << "\n";
953 VariadicArgument::writeDeclarations(OS);
956 void writeDump(raw_ostream &OS) const override {
957 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
958 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
959 << getLowerName() << "_end(); I != E; ++I) {\n";
960 OS << " switch(*I) {\n";
961 for (const auto &UI : uniques) {
962 OS << " case " << getAttrName() << "Attr::" << UI << ":\n";
963 OS << " OS << \" " << UI << "\";\n";
970 void writePCHReadDecls(raw_ostream &OS) const override {
971 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
972 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName()
974 OS << " " << getLowerName() << ".reserve(" << getLowerName()
976 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
977 OS << " " << getLowerName() << ".push_back(" << "static_cast<"
978 << QualifiedTypeName << ">(Record.readInt()));\n";
981 void writePCHWrite(raw_ostream &OS) const override {
982 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
983 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
984 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
985 << getLowerName() << "_end(); i != e; ++i)\n";
986 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)");
989 void writeConversion(raw_ostream &OS) const {
990 OS << " static bool ConvertStrTo" << type << "(StringRef Val, ";
991 OS << type << " &Out) {\n";
992 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<";
993 OS << type << ">>(Val)\n";
994 for (size_t I = 0; I < enums.size(); ++I) {
995 OS << " .Case(\"" << values[I] << "\", ";
996 OS << getAttrName() << "Attr::" << enums[I] << ")\n";
998 OS << " .Default(Optional<" << type << ">());\n";
1000 OS << " Out = *R;\n return true;\n }\n";
1001 OS << " return false;\n";
1004 OS << " static const char *Convert" << type << "ToStr("
1005 << type << " Val) {\n"
1006 << " switch(Val) {\n";
1007 SmallDenseSet<StringRef, 8> Uniques;
1008 for (size_t I = 0; I < enums.size(); ++I) {
1009 if (Uniques.insert(enums[I]).second)
1010 OS << " case " << getAttrName() << "Attr::" << enums[I]
1011 << ": return \"" << values[I] << "\";\n";
1014 << " llvm_unreachable(\"No enumerator with that value\");\n"
1019 class VersionArgument : public Argument {
1021 VersionArgument(const Record &Arg, StringRef Attr)
1022 : Argument(Arg, Attr)
1025 void writeAccessors(raw_ostream &OS) const override {
1026 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1027 OS << " return " << getLowerName() << ";\n";
1029 OS << " void set" << getUpperName()
1030 << "(ASTContext &C, VersionTuple V) {\n";
1031 OS << " " << getLowerName() << " = V;\n";
1035 void writeCloneArgs(raw_ostream &OS) const override {
1036 OS << "get" << getUpperName() << "()";
1039 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1040 OS << "A->get" << getUpperName() << "()";
1043 void writeCtorInitializers(raw_ostream &OS) const override {
1044 OS << getLowerName() << "(" << getUpperName() << ")";
1047 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1048 OS << getLowerName() << "()";
1051 void writeCtorParameters(raw_ostream &OS) const override {
1052 OS << "VersionTuple " << getUpperName();
1055 void writeDeclarations(raw_ostream &OS) const override {
1056 OS << "VersionTuple " << getLowerName() << ";\n";
1059 void writePCHReadDecls(raw_ostream &OS) const override {
1060 OS << " VersionTuple " << getLowerName()
1061 << "= Record.readVersionTuple();\n";
1064 void writePCHReadArgs(raw_ostream &OS) const override {
1065 OS << getLowerName();
1068 void writePCHWrite(raw_ostream &OS) const override {
1069 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1072 void writeValue(raw_ostream &OS) const override {
1073 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1076 void writeDump(raw_ostream &OS) const override {
1077 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1081 class ExprArgument : public SimpleArgument {
1083 ExprArgument(const Record &Arg, StringRef Attr)
1084 : SimpleArgument(Arg, Attr, "Expr *")
1087 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1089 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1090 OS << " return false;\n";
1093 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1094 OS << "tempInst" << getUpperName();
1097 void writeTemplateInstantiation(raw_ostream &OS) const override {
1098 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1100 OS << " EnterExpressionEvaluationContext "
1101 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1102 OS << " ExprResult " << "Result = S.SubstExpr("
1103 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1104 OS << " tempInst" << getUpperName() << " = "
1105 << "Result.getAs<Expr>();\n";
1109 void writeDump(raw_ostream &OS) const override {}
1111 void writeDumpChildren(raw_ostream &OS) const override {
1112 OS << " dumpStmt(SA->get" << getUpperName() << "());\n";
1115 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1118 class VariadicExprArgument : public VariadicArgument {
1120 VariadicExprArgument(const Record &Arg, StringRef Attr)
1121 : VariadicArgument(Arg, Attr, "Expr *")
1124 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1126 OS << " " << getType() << " *I = A->" << getLowerName()
1128 OS << " " << getType() << " *E = A->" << getLowerName()
1130 OS << " for (; I != E; ++I) {\n";
1131 OS << " if (!getDerived().TraverseStmt(*I))\n";
1132 OS << " return false;\n";
1137 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1138 OS << "tempInst" << getUpperName() << ", "
1139 << "A->" << getLowerName() << "_size()";
1142 void writeTemplateInstantiation(raw_ostream &OS) const override {
1143 OS << " auto *tempInst" << getUpperName()
1144 << " = new (C, 16) " << getType()
1145 << "[A->" << getLowerName() << "_size()];\n";
1147 OS << " EnterExpressionEvaluationContext "
1148 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1149 OS << " " << getType() << " *TI = tempInst" << getUpperName()
1151 OS << " " << getType() << " *I = A->" << getLowerName()
1153 OS << " " << getType() << " *E = A->" << getLowerName()
1155 OS << " for (; I != E; ++I, ++TI) {\n";
1156 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1157 OS << " *TI = Result.getAs<Expr>();\n";
1162 void writeDump(raw_ostream &OS) const override {}
1164 void writeDumpChildren(raw_ostream &OS) const override {
1165 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1166 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1167 << getLowerName() << "_end(); I != E; ++I)\n";
1168 OS << " dumpStmt(*I);\n";
1171 void writeHasChildren(raw_ostream &OS) const override {
1172 OS << "SA->" << getLowerName() << "_begin() != "
1173 << "SA->" << getLowerName() << "_end()";
1177 class VariadicIdentifierArgument : public VariadicArgument {
1179 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1180 : VariadicArgument(Arg, Attr, "IdentifierInfo *")
1184 class VariadicStringArgument : public VariadicArgument {
1186 VariadicStringArgument(const Record &Arg, StringRef Attr)
1187 : VariadicArgument(Arg, Attr, "StringRef")
1190 void writeCtorBody(raw_ostream &OS) const override {
1191 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1193 " StringRef Ref = " << getUpperName() << "[I];\n"
1194 " if (!Ref.empty()) {\n"
1195 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1196 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1197 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1202 void writeValueImpl(raw_ostream &OS) const override {
1203 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1207 class TypeArgument : public SimpleArgument {
1209 TypeArgument(const Record &Arg, StringRef Attr)
1210 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1213 void writeAccessors(raw_ostream &OS) const override {
1214 OS << " QualType get" << getUpperName() << "() const {\n";
1215 OS << " return " << getLowerName() << "->getType();\n";
1217 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1218 OS << " return " << getLowerName() << ";\n";
1222 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1223 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1224 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1225 OS << " return false;\n";
1228 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1229 OS << "A->get" << getUpperName() << "Loc()";
1232 void writePCHWrite(raw_ostream &OS) const override {
1233 OS << " " << WritePCHRecord(
1234 getType(), "SA->get" + std::string(getUpperName()) + "Loc()");
1238 } // end anonymous namespace
1240 static std::unique_ptr<Argument>
1241 createArgument(const Record &Arg, StringRef Attr,
1242 const Record *Search = nullptr) {
1246 std::unique_ptr<Argument> Ptr;
1247 llvm::StringRef ArgName = Search->getName();
1249 if (ArgName == "AlignedArgument")
1250 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr);
1251 else if (ArgName == "EnumArgument")
1252 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr);
1253 else if (ArgName == "ExprArgument")
1254 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr);
1255 else if (ArgName == "FunctionArgument")
1256 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *");
1257 else if (ArgName == "NamedArgument")
1258 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "NamedDecl *");
1259 else if (ArgName == "IdentifierArgument")
1260 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *");
1261 else if (ArgName == "DefaultBoolArgument")
1262 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1263 Arg, Attr, "bool", Arg.getValueAsBit("Default"));
1264 else if (ArgName == "BoolArgument")
1265 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool");
1266 else if (ArgName == "DefaultIntArgument")
1267 Ptr = llvm::make_unique<DefaultSimpleArgument>(
1268 Arg, Attr, "int", Arg.getValueAsInt("Default"));
1269 else if (ArgName == "IntArgument")
1270 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int");
1271 else if (ArgName == "StringArgument")
1272 Ptr = llvm::make_unique<StringArgument>(Arg, Attr);
1273 else if (ArgName == "TypeArgument")
1274 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr);
1275 else if (ArgName == "UnsignedArgument")
1276 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned");
1277 else if (ArgName == "VariadicUnsignedArgument")
1278 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned");
1279 else if (ArgName == "VariadicStringArgument")
1280 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr);
1281 else if (ArgName == "VariadicEnumArgument")
1282 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr);
1283 else if (ArgName == "VariadicExprArgument")
1284 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr);
1285 else if (ArgName == "VariadicParamIdxArgument")
1286 Ptr = llvm::make_unique<VariadicParamIdxArgument>(Arg, Attr);
1287 else if (ArgName == "ParamIdxArgument")
1288 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "ParamIdx");
1289 else if (ArgName == "VariadicIdentifierArgument")
1290 Ptr = llvm::make_unique<VariadicIdentifierArgument>(Arg, Attr);
1291 else if (ArgName == "VersionArgument")
1292 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr);
1295 // Search in reverse order so that the most-derived type is handled first.
1296 ArrayRef<std::pair<Record*, SMRange>> Bases = Search->getSuperClasses();
1297 for (const auto &Base : llvm::reverse(Bases)) {
1298 if ((Ptr = createArgument(Arg, Attr, Base.first)))
1303 if (Ptr && Arg.getValueAsBit("Optional"))
1304 Ptr->setOptional(true);
1306 if (Ptr && Arg.getValueAsBit("Fake"))
1312 static void writeAvailabilityValue(raw_ostream &OS) {
1313 OS << "\" << getPlatform()->getName();\n"
1314 << " if (getStrict()) OS << \", strict\";\n"
1315 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1316 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1317 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1318 << " if (getUnavailable()) OS << \", unavailable\";\n"
1322 static void writeDeprecatedAttrValue(raw_ostream &OS, std::string &Variety) {
1323 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1324 // Only GNU deprecated has an optional fixit argument at the second position.
1325 if (Variety == "GNU")
1326 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1327 " << getReplacement() << \"\\\"\";\n";
1331 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) {
1332 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1334 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1335 if (Spellings.empty()) {
1336 OS << " return \"(No spelling)\";\n}\n\n";
1340 OS << " switch (SpellingListIndex) {\n"
1342 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1343 " return \"(No spelling)\";\n";
1345 for (unsigned I = 0; I < Spellings.size(); ++I)
1346 OS << " case " << I << ":\n"
1347 " return \"" << Spellings[I].name() << "\";\n";
1348 // End of the switch statement.
1350 // End of the getSpelling function.
1355 writePrettyPrintFunction(Record &R,
1356 const std::vector<std::unique_ptr<Argument>> &Args,
1358 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
1360 OS << "void " << R.getName() << "Attr::printPretty("
1361 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1363 if (Spellings.empty()) {
1369 " switch (SpellingListIndex) {\n"
1371 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1374 for (unsigned I = 0; I < Spellings.size(); ++ I) {
1375 llvm::SmallString<16> Prefix;
1376 llvm::SmallString<8> Suffix;
1377 // The actual spelling of the name and namespace (if applicable)
1378 // of an attribute without considering prefix and suffix.
1379 llvm::SmallString<64> Spelling;
1380 std::string Name = Spellings[I].name();
1381 std::string Variety = Spellings[I].variety();
1383 if (Variety == "GNU") {
1384 Prefix = " __attribute__((";
1386 } else if (Variety == "CXX11" || Variety == "C2x") {
1389 std::string Namespace = Spellings[I].nameSpace();
1390 if (!Namespace.empty()) {
1391 Spelling += Namespace;
1394 } else if (Variety == "Declspec") {
1395 Prefix = " __declspec(";
1397 } else if (Variety == "Microsoft") {
1400 } else if (Variety == "Keyword") {
1403 } else if (Variety == "Pragma") {
1404 Prefix = "#pragma ";
1406 std::string Namespace = Spellings[I].nameSpace();
1407 if (!Namespace.empty()) {
1408 Spelling += Namespace;
1412 llvm_unreachable("Unknown attribute syntax variety!");
1418 " case " << I << " : {\n"
1419 " OS << \"" << Prefix << Spelling;
1421 if (Variety == "Pragma") {
1423 OS << " printPrettyPragma(OS, Policy);\n";
1424 OS << " OS << \"\\n\";";
1430 if (Spelling == "availability") {
1432 writeAvailabilityValue(OS);
1434 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1436 writeDeprecatedAttrValue(OS, Variety);
1439 // To avoid printing parentheses around an empty argument list or
1440 // printing spurious commas at the end of an argument list, we need to
1441 // determine where the last provided non-fake argument is.
1442 unsigned NonFakeArgs = 0;
1443 unsigned TrailingOptArgs = 0;
1444 bool FoundNonOptArg = false;
1445 for (const auto &arg : llvm::reverse(Args)) {
1451 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1452 // any way to detect whether the argument was omitted.
1453 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1454 FoundNonOptArg = true;
1457 if (!TrailingOptArgs++)
1459 << " unsigned TrailingOmittedArgs = 0;\n";
1460 OS << " if (" << arg->getIsOmitted() << ")\n"
1461 << " ++TrailingOmittedArgs;\n";
1463 if (TrailingOptArgs)
1465 if (TrailingOptArgs < NonFakeArgs)
1467 else if (TrailingOptArgs)
1469 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1470 << " OS << \"(\";\n"
1472 unsigned ArgIndex = 0;
1473 for (const auto &arg : Args) {
1477 if (ArgIndex >= NonFakeArgs - TrailingOptArgs)
1479 << " if (" << ArgIndex << " < " << NonFakeArgs
1480 << " - TrailingOmittedArgs)\n"
1481 << " OS << \", \";\n"
1486 std::string IsOmitted = arg->getIsOmitted();
1487 if (arg->isOptional() && IsOmitted != "false")
1489 << " if (!(" << IsOmitted << ")) {\n"
1491 arg->writeValue(OS);
1492 if (arg->isOptional() && IsOmitted != "false")
1498 if (TrailingOptArgs < NonFakeArgs)
1500 else if (TrailingOptArgs)
1502 << " if (TrailingOmittedArgs < " << NonFakeArgs << ")\n"
1503 << " OS << \")\";\n"
1507 OS << Suffix + "\";\n";
1514 // End of the switch statement.
1516 // End of the print function.
1520 /// Return the index of a spelling in a spelling list.
1522 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList,
1523 const FlattenedSpelling &Spelling) {
1524 assert(!SpellingList.empty() && "Spelling list is empty!");
1526 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) {
1527 const FlattenedSpelling &S = SpellingList[Index];
1528 if (S.variety() != Spelling.variety())
1530 if (S.nameSpace() != Spelling.nameSpace())
1532 if (S.name() != Spelling.name())
1538 llvm_unreachable("Unknown spelling!");
1541 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1542 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors");
1543 if (Accessors.empty())
1546 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R);
1547 assert(!SpellingList.empty() &&
1548 "Attribute with empty spelling list can't have accessors!");
1549 for (const auto *Accessor : Accessors) {
1550 const StringRef Name = Accessor->getValueAsString("Name");
1551 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Accessor);
1553 OS << " bool " << Name << "() const { return SpellingListIndex == ";
1554 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1555 OS << getSpellingListIndex(SpellingList, Spellings[Index]);
1556 if (Index != Spellings.size() - 1)
1557 OS << " ||\n SpellingListIndex == ";
1565 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1566 assert(!Spellings.empty() && "An empty list of spellings was provided");
1567 std::string FirstName = NormalizeNameForSpellingComparison(
1568 Spellings.front().name());
1569 for (const auto &Spelling :
1570 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) {
1571 std::string Name = NormalizeNameForSpellingComparison(Spelling.name());
1572 if (Name != FirstName)
1578 typedef std::map<unsigned, std::string> SemanticSpellingMap;
1580 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1581 SemanticSpellingMap &Map) {
1582 // The enumerants are automatically generated based on the variety,
1583 // namespace (if present) and name for each attribute spelling. However,
1584 // care is taken to avoid trampling on the reserved namespace due to
1586 std::string Ret(" enum Spelling {\n");
1587 std::set<std::string> Uniques;
1589 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1590 const FlattenedSpelling &S = *I;
1591 const std::string &Variety = S.variety();
1592 const std::string &Spelling = S.name();
1593 const std::string &Namespace = S.nameSpace();
1594 std::string EnumName;
1596 EnumName += (Variety + "_");
1597 if (!Namespace.empty())
1598 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() +
1600 EnumName += NormalizeNameForSpellingComparison(Spelling);
1602 // Even if the name is not unique, this spelling index corresponds to a
1603 // particular enumerant name that we've calculated.
1604 Map[Idx] = EnumName;
1606 // Since we have been stripping underscores to avoid trampling on the
1607 // reserved namespace, we may have inadvertently created duplicate
1608 // enumerant names. These duplicates are not considered part of the
1609 // semantic spelling, and can be elided.
1610 if (Uniques.find(EnumName) != Uniques.end())
1613 Uniques.insert(EnumName);
1614 if (I != Spellings.begin())
1616 // Duplicate spellings are not considered part of the semantic spelling
1617 // enumeration, but the spelling index and semantic spelling values are
1618 // meant to be equivalent, so we must specify a concrete value for each
1620 Ret += " " + EnumName + " = " + llvm::utostr(Idx);
1626 void WriteSemanticSpellingSwitch(const std::string &VarName,
1627 const SemanticSpellingMap &Map,
1629 OS << " switch (" << VarName << ") {\n default: "
1630 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1631 for (const auto &I : Map)
1632 OS << " case " << I.first << ": return " << I.second << ";\n";
1636 // Emits the LateParsed property for attributes.
1637 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) {
1638 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1639 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
1641 for (const auto *Attr : Attrs) {
1642 bool LateParsed = Attr->getValueAsBit("LateParsed");
1645 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
1647 // FIXME: Handle non-GNU attributes
1648 for (const auto &I : Spellings) {
1649 if (I.variety() != "GNU")
1651 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n";
1655 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1658 static bool hasGNUorCXX11Spelling(const Record &Attribute) {
1659 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
1660 for (const auto &I : Spellings) {
1661 if (I.variety() == "GNU" || I.variety() == "CXX11")
1669 struct AttributeSubjectMatchRule {
1670 const Record *MetaSubject;
1671 const Record *Constraint;
1673 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
1674 : MetaSubject(MetaSubject), Constraint(Constraint) {
1675 assert(MetaSubject && "Missing subject");
1678 bool isSubRule() const { return Constraint != nullptr; }
1680 std::vector<Record *> getSubjects() const {
1681 return (Constraint ? Constraint : MetaSubject)
1682 ->getValueAsListOfDefs("Subjects");
1685 std::vector<Record *> getLangOpts() const {
1687 // Lookup the options in the sub-rule first, in case the sub-rule
1688 // overrides the rules options.
1689 std::vector<Record *> Opts = Constraint->getValueAsListOfDefs("LangOpts");
1693 return MetaSubject->getValueAsListOfDefs("LangOpts");
1696 // Abstract rules are used only for sub-rules
1697 bool isAbstractRule() const { return getSubjects().empty(); }
1699 StringRef getName() const {
1700 return (Constraint ? Constraint : MetaSubject)->getValueAsString("Name");
1703 bool isNegatedSubRule() const {
1704 assert(isSubRule() && "Not a sub-rule");
1705 return Constraint->getValueAsBit("Negated");
1708 std::string getSpelling() const {
1709 std::string Result = MetaSubject->getValueAsString("Name");
1712 if (isNegatedSubRule())
1713 Result += "unless(";
1714 Result += getName();
1715 if (isNegatedSubRule())
1722 std::string getEnumValueName() const {
1723 SmallString<128> Result;
1724 Result += "SubjectMatchRule_";
1725 Result += MetaSubject->getValueAsString("Name");
1728 if (isNegatedSubRule())
1730 Result += Constraint->getValueAsString("Name");
1732 if (isAbstractRule())
1733 Result += "_abstract";
1734 return Result.str();
1737 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
1739 static const char *EnumName;
1742 const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
1744 struct PragmaClangAttributeSupport {
1745 std::vector<AttributeSubjectMatchRule> Rules;
1747 class RuleOrAggregateRuleSet {
1748 std::vector<AttributeSubjectMatchRule> Rules;
1750 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
1752 : Rules(Rules), IsRule(IsRule) {}
1755 bool isRule() const { return IsRule; }
1757 const AttributeSubjectMatchRule &getRule() const {
1758 assert(IsRule && "not a rule!");
1762 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
1766 static RuleOrAggregateRuleSet
1767 getRule(const AttributeSubjectMatchRule &Rule) {
1768 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
1770 static RuleOrAggregateRuleSet
1771 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
1772 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
1775 llvm::DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
1777 PragmaClangAttributeSupport(RecordKeeper &Records);
1779 bool isAttributedSupported(const Record &Attribute);
1781 void emitMatchRuleList(raw_ostream &OS);
1783 std::string generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
1785 void generateParsingHelpers(raw_ostream &OS);
1788 } // end anonymous namespace
1790 static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
1791 const Record *CurrentBase = D->getValueAsDef("Base");
1794 if (CurrentBase == Base)
1796 return doesDeclDeriveFrom(CurrentBase, Base);
1799 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
1800 RecordKeeper &Records) {
1801 std::vector<Record *> MetaSubjects =
1802 Records.getAllDerivedDefinitions("AttrSubjectMatcherRule");
1803 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
1804 const Record *MetaSubject,
1805 const Record *Constraint) {
1806 Rules.emplace_back(MetaSubject, Constraint);
1807 std::vector<Record *> ApplicableSubjects =
1808 SubjectContainer->getValueAsListOfDefs("Subjects");
1809 for (const auto *Subject : ApplicableSubjects) {
1812 .try_emplace(Subject, RuleOrAggregateRuleSet::getRule(
1813 AttributeSubjectMatchRule(MetaSubject,
1817 PrintFatalError("Attribute subject match rules should not represent"
1818 "same attribute subjects.");
1822 for (const auto *MetaSubject : MetaSubjects) {
1823 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
1824 std::vector<Record *> Constraints =
1825 MetaSubject->getValueAsListOfDefs("Constraints");
1826 for (const auto *Constraint : Constraints)
1827 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
1830 std::vector<Record *> Aggregates =
1831 Records.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule");
1832 std::vector<Record *> DeclNodes = Records.getAllDerivedDefinitions("DDecl");
1833 for (const auto *Aggregate : Aggregates) {
1834 Record *SubjectDecl = Aggregate->getValueAsDef("Subject");
1836 // Gather sub-classes of the aggregate subject that act as attribute
1838 std::vector<AttributeSubjectMatchRule> Rules;
1839 for (const auto *D : DeclNodes) {
1840 if (doesDeclDeriveFrom(D, SubjectDecl)) {
1841 auto It = SubjectsToRules.find(D);
1842 if (It == SubjectsToRules.end())
1844 if (!It->second.isRule() || It->second.getRule().isSubRule())
1845 continue; // Assume that the rule will be included as well.
1846 Rules.push_back(It->second.getRule());
1852 .try_emplace(SubjectDecl,
1853 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
1856 PrintFatalError("Attribute subject match rules should not represent"
1857 "same attribute subjects.");
1862 static PragmaClangAttributeSupport &
1863 getPragmaAttributeSupport(RecordKeeper &Records) {
1864 static PragmaClangAttributeSupport Instance(Records);
1868 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
1869 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
1870 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
1872 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
1874 for (const auto &Rule : Rules) {
1875 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
1876 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
1877 << Rule.isAbstractRule();
1878 if (Rule.isSubRule())
1880 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
1881 << ", " << Rule.isNegatedSubRule();
1884 OS << "#undef ATTR_MATCH_SUB_RULE\n";
1887 bool PragmaClangAttributeSupport::isAttributedSupported(
1888 const Record &Attribute) {
1889 // If the attribute explicitly specified whether to support #pragma clang
1890 // attribute, use that setting.
1892 bool SpecifiedResult =
1893 Attribute.getValueAsBitOrUnset("PragmaAttributeSupport", Unset);
1895 return SpecifiedResult;
1898 // An attribute requires delayed parsing (LateParsed is on)
1899 if (Attribute.getValueAsBit("LateParsed"))
1901 // An attribute has no GNU/CXX11 spelling
1902 if (!hasGNUorCXX11Spelling(Attribute))
1904 // An attribute subject list has a subject that isn't covered by one of the
1905 // subject match rules or has no subjects at all.
1906 if (Attribute.isValueUnset("Subjects"))
1908 const Record *SubjectObj = Attribute.getValueAsDef("Subjects");
1909 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1910 if (Subjects.empty())
1912 for (const auto *Subject : Subjects) {
1913 if (SubjectsToRules.find(Subject) == SubjectsToRules.end())
1920 PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
1922 if (!isAttributedSupported(Attr))
1924 // Generate a function that constructs a set of matching rules that describe
1925 // to which declarations the attribute should apply to.
1926 std::string FnName = "matchRulesFor" + Attr.getName().str();
1927 OS << "static void " << FnName << "(llvm::SmallVectorImpl<std::pair<"
1928 << AttributeSubjectMatchRule::EnumName
1929 << ", bool>> &MatchRules, const LangOptions &LangOpts) {\n";
1930 if (Attr.isValueUnset("Subjects")) {
1934 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
1935 std::vector<Record *> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
1936 for (const auto *Subject : Subjects) {
1937 auto It = SubjectsToRules.find(Subject);
1938 assert(It != SubjectsToRules.end() &&
1939 "This attribute is unsupported by #pragma clang attribute");
1940 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
1941 // The rule might be language specific, so only subtract it from the given
1942 // rules if the specific language options are specified.
1943 std::vector<Record *> LangOpts = Rule.getLangOpts();
1944 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
1945 << ", /*IsSupported=*/";
1946 if (!LangOpts.empty()) {
1947 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
1948 const StringRef Part = (*I)->getValueAsString("Name");
1949 if ((*I)->getValueAsBit("Negated"))
1951 OS << "LangOpts." << Part;
1964 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
1965 // Generate routines that check the names of sub-rules.
1966 OS << "Optional<attr::SubjectMatchRule> "
1967 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
1968 OS << " return None;\n";
1971 std::map<const Record *, std::vector<AttributeSubjectMatchRule>>
1973 for (const auto &Rule : Rules) {
1974 if (!Rule.isSubRule())
1976 SubMatchRules[Rule.MetaSubject].push_back(Rule);
1979 for (const auto &SubMatchRule : SubMatchRules) {
1980 OS << "Optional<attr::SubjectMatchRule> isAttributeSubjectMatchSubRuleFor_"
1981 << SubMatchRule.first->getValueAsString("Name")
1982 << "(StringRef Name, bool IsUnless) {\n";
1983 OS << " if (IsUnless)\n";
1985 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1986 for (const auto &Rule : SubMatchRule.second) {
1987 if (Rule.isNegatedSubRule())
1988 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1991 OS << " Default(None);\n";
1993 "llvm::StringSwitch<Optional<attr::SubjectMatchRule>>(Name).\n";
1994 for (const auto &Rule : SubMatchRule.second) {
1995 if (!Rule.isNegatedSubRule())
1996 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
1999 OS << " Default(None);\n";
2003 // Generate the function that checks for the top-level rules.
2004 OS << "std::pair<Optional<attr::SubjectMatchRule>, "
2005 "Optional<attr::SubjectMatchRule> (*)(StringRef, "
2006 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2008 "llvm::StringSwitch<std::pair<Optional<attr::SubjectMatchRule>, "
2009 "Optional<attr::SubjectMatchRule> (*) (StringRef, "
2011 for (const auto &Rule : Rules) {
2012 if (Rule.isSubRule())
2014 std::string SubRuleFunction;
2015 if (SubMatchRules.count(Rule.MetaSubject))
2017 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2019 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2020 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2021 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2023 OS << " Default(std::make_pair(None, "
2024 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2027 // Generate the function that checks for the submatch rules.
2028 OS << "const char *validAttributeSubjectMatchSubRules("
2029 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2030 OS << " switch (Rule) {\n";
2031 for (const auto &SubMatchRule : SubMatchRules) {
2033 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2035 OS << " return \"'";
2036 bool IsFirst = true;
2037 for (const auto &Rule : SubMatchRule.second) {
2041 if (Rule.isNegatedSubRule())
2043 OS << Rule.getName();
2044 if (Rule.isNegatedSubRule())
2050 OS << " default: return nullptr;\n";
2055 template <typename Fn>
2056 static void forEachUniqueSpelling(const Record &Attr, Fn &&F) {
2057 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
2058 SmallDenseSet<StringRef, 8> Seen;
2059 for (const FlattenedSpelling &S : Spellings) {
2060 if (Seen.insert(S.name()).second)
2065 /// Emits the first-argument-is-type property for attributes.
2066 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) {
2067 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2068 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2070 for (const auto *Attr : Attrs) {
2071 // Determine whether the first argument is a type.
2072 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2076 if (Args[0]->getSuperClasses().back().first->getName() != "TypeArgument")
2079 // All these spellings take a single type argument.
2080 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2081 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2084 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2087 /// Emits the parse-arguments-in-unevaluated-context property for
2089 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) {
2090 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2091 ParsedAttrMap Attrs = getParsedAttrList(Records);
2092 for (const auto &I : Attrs) {
2093 const Record &Attr = *I.second;
2095 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated"))
2098 // All these spellings take are parsed unevaluated.
2099 forEachUniqueSpelling(Attr, [&](const FlattenedSpelling &S) {
2100 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2103 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2106 static bool isIdentifierArgument(Record *Arg) {
2107 return !Arg->getSuperClasses().empty() &&
2108 llvm::StringSwitch<bool>(Arg->getSuperClasses().back().first->getName())
2109 .Case("IdentifierArgument", true)
2110 .Case("EnumArgument", true)
2111 .Case("VariadicEnumArgument", true)
2115 static bool isVariadicIdentifierArgument(Record *Arg) {
2116 return !Arg->getSuperClasses().empty() &&
2117 llvm::StringSwitch<bool>(
2118 Arg->getSuperClasses().back().first->getName())
2119 .Case("VariadicIdentifierArgument", true)
2123 static void emitClangAttrVariadicIdentifierArgList(RecordKeeper &Records,
2125 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2126 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2127 for (const auto *A : Attrs) {
2128 // Determine whether the first argument is a variadic identifier.
2129 std::vector<Record *> Args = A->getValueAsListOfDefs("Args");
2130 if (Args.empty() || !isVariadicIdentifierArgument(Args[0]))
2133 // All these spellings take an identifier argument.
2134 forEachUniqueSpelling(*A, [&](const FlattenedSpelling &S) {
2135 OS << ".Case(\"" << S.name() << "\", "
2140 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2143 // Emits the first-argument-is-identifier property for attributes.
2144 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) {
2145 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2146 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2148 for (const auto *Attr : Attrs) {
2149 // Determine whether the first argument is an identifier.
2150 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args");
2151 if (Args.empty() || !isIdentifierArgument(Args[0]))
2154 // All these spellings take an identifier argument.
2155 forEachUniqueSpelling(*Attr, [&](const FlattenedSpelling &S) {
2156 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n";
2159 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2164 // Emits the class definitions for attributes.
2165 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) {
2166 emitSourceFileHeader("Attribute classes' definitions", OS);
2168 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
2169 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n";
2171 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2173 for (const auto *Attr : Attrs) {
2174 const Record &R = *Attr;
2176 // FIXME: Currently, documentation is generated as-needed due to the fact
2177 // that there is no way to allow a generated project "reach into" the docs
2178 // directory (for instance, it may be an out-of-tree build). However, we want
2179 // to ensure that every attribute has a Documentation field, and produce an
2180 // error if it has been neglected. Otherwise, the on-demand generation which
2181 // happens server-side will fail. This code is ensuring that functionality,
2182 // even though this Emitter doesn't technically need the documentation.
2183 // When attribute documentation can be generated as part of the build
2184 // itself, this code can be removed.
2185 (void)R.getValueAsListOfDefs("Documentation");
2187 if (!R.getValueAsBit("ASTNode"))
2190 ArrayRef<std::pair<Record *, SMRange>> Supers = R.getSuperClasses();
2191 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2192 std::string SuperName;
2193 bool Inheritable = false;
2194 for (const auto &Super : llvm::reverse(Supers)) {
2195 const Record *R = Super.first;
2196 if (R->getName() != "TargetSpecificAttr" &&
2197 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2198 SuperName = R->getName();
2199 if (R->getName() == "InheritableAttr")
2203 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n";
2205 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2206 std::vector<std::unique_ptr<Argument>> Args;
2207 Args.reserve(ArgRecords.size());
2209 bool HasOptArg = false;
2210 bool HasFakeArg = false;
2211 for (const auto *ArgRecord : ArgRecords) {
2212 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
2213 Args.back()->writeDeclarations(OS);
2216 // For these purposes, fake takes priority over optional.
2217 if (Args.back()->isFake()) {
2219 } else if (Args.back()->isOptional()) {
2226 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2228 // If there are zero or one spellings, all spelling-related functionality
2229 // can be elided. If all of the spellings share the same name, the spelling
2230 // functionality can also be elided.
2231 bool ElideSpelling = (Spellings.size() <= 1) ||
2232 SpellingNamesAreCommon(Spellings);
2234 // This maps spelling index values to semantic Spelling enumerants.
2235 SemanticSpellingMap SemanticToSyntacticMap;
2238 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
2240 // Emit CreateImplicit factory methods.
2241 auto emitCreateImplicit = [&](bool emitFake) {
2242 OS << " static " << R.getName() << "Attr *CreateImplicit(";
2243 OS << "ASTContext &Ctx";
2245 OS << ", Spelling S";
2246 for (auto const &ai : Args) {
2247 if (ai->isFake() && !emitFake) continue;
2249 ai->writeCtorParameters(OS);
2251 OS << ", SourceRange Loc = SourceRange()";
2253 OS << " auto *A = new (Ctx) " << R.getName();
2254 OS << "Attr(Loc, Ctx, ";
2255 for (auto const &ai : Args) {
2256 if (ai->isFake() && !emitFake) continue;
2257 ai->writeImplicitCtorArgs(OS);
2260 OS << (ElideSpelling ? "0" : "S") << ");\n";
2261 OS << " A->setImplicit(true);\n";
2262 OS << " return A;\n }\n\n";
2265 // Emit a CreateImplicit that takes all the arguments.
2266 emitCreateImplicit(true);
2268 // Emit a CreateImplicit that takes all the non-fake arguments.
2270 emitCreateImplicit(false);
2273 // Emit constructors.
2274 auto emitCtor = [&](bool emitOpt, bool emitFake) {
2275 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
2276 if (arg->isFake()) return emitFake;
2277 if (arg->isOptional()) return emitOpt;
2281 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n";
2282 for (auto const &ai : Args) {
2283 if (!shouldEmitArg(ai)) continue;
2285 ai->writeCtorParameters(OS);
2290 OS << "unsigned SI\n";
2293 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, "
2294 << ( R.getValueAsBit("LateParsed") ? "true" : "false" );
2297 << (R.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
2302 for (auto const &ai : Args) {
2304 if (!shouldEmitArg(ai)) {
2305 ai->writeCtorDefaultInitializers(OS);
2307 ai->writeCtorInitializers(OS);
2314 for (auto const &ai : Args) {
2315 if (!shouldEmitArg(ai)) continue;
2316 ai->writeCtorBody(OS);
2321 // Emit a constructor that includes all the arguments.
2322 // This is necessary for cloning.
2323 emitCtor(true, true);
2325 // Emit a constructor that takes all the non-fake arguments.
2327 emitCtor(true, false);
2330 // Emit a constructor that takes all the non-fake, non-optional arguments.
2332 emitCtor(false, false);
2335 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
2336 OS << " void printPretty(raw_ostream &OS,\n"
2337 << " const PrintingPolicy &Policy) const;\n";
2338 OS << " const char *getSpelling() const;\n";
2340 if (!ElideSpelling) {
2341 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
2342 OS << " Spelling getSemanticSpelling() const {\n";
2343 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap,
2348 writeAttrAccessorDefinition(R, OS);
2350 for (auto const &ai : Args) {
2351 ai->writeAccessors(OS);
2354 // Don't write conversion routines for fake arguments.
2355 if (ai->isFake()) continue;
2357 if (ai->isEnumArg())
2358 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS);
2359 else if (ai->isVariadicEnumArg())
2360 static_cast<const VariadicEnumArgument *>(ai.get())
2361 ->writeConversion(OS);
2364 OS << R.getValueAsString("AdditionalMembers");
2367 OS << " static bool classof(const Attr *A) { return A->getKind() == "
2368 << "attr::" << R.getName() << "; }\n";
2373 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
2376 // Emits the class method definitions for attributes.
2377 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2378 emitSourceFileHeader("Attribute classes' member function definitions", OS);
2380 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2382 for (auto *Attr : Attrs) {
2385 if (!R.getValueAsBit("ASTNode"))
2388 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
2389 std::vector<std::unique_ptr<Argument>> Args;
2390 for (const auto *Arg : ArgRecords)
2391 Args.emplace_back(createArgument(*Arg, R.getName()));
2393 for (auto const &ai : Args)
2394 ai->writeAccessorDefinitions(OS);
2396 OS << R.getName() << "Attr *" << R.getName()
2397 << "Attr::clone(ASTContext &C) const {\n";
2398 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C";
2399 for (auto const &ai : Args) {
2401 ai->writeCloneArgs(OS);
2403 OS << ", getSpellingListIndex());\n";
2404 OS << " A->Inherited = Inherited;\n";
2405 OS << " A->IsPackExpansion = IsPackExpansion;\n";
2406 OS << " A->Implicit = Implicit;\n";
2407 OS << " return A;\n}\n\n";
2409 writePrettyPrintFunction(R, Args, OS);
2410 writeGetSpellingFunction(R, OS);
2413 // Instead of relying on virtual dispatch we just create a huge dispatch
2414 // switch. This is both smaller and faster than virtual functions.
2415 auto EmitFunc = [&](const char *Method) {
2416 OS << " switch (getKind()) {\n";
2417 for (const auto *Attr : Attrs) {
2418 const Record &R = *Attr;
2419 if (!R.getValueAsBit("ASTNode"))
2422 OS << " case attr::" << R.getName() << ":\n";
2423 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
2427 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
2431 OS << "const char *Attr::getSpelling() const {\n";
2432 EmitFunc("getSpelling()");
2434 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
2435 EmitFunc("clone(C)");
2437 OS << "void Attr::printPretty(raw_ostream &OS, "
2438 "const PrintingPolicy &Policy) const {\n";
2439 EmitFunc("printPretty(OS, Policy)");
2442 } // end namespace clang
2444 static void emitAttrList(raw_ostream &OS, StringRef Class,
2445 const std::vector<Record*> &AttrList) {
2446 for (auto Cur : AttrList) {
2447 OS << Class << "(" << Cur->getName() << ")\n";
2451 // Determines if an attribute has a Pragma spelling.
2452 static bool AttrHasPragmaSpelling(const Record *R) {
2453 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2454 return llvm::find_if(Spellings, [](const FlattenedSpelling &S) {
2455 return S.variety() == "Pragma";
2456 }) != Spellings.end();
2461 struct AttrClassDescriptor {
2462 const char * const MacroName;
2463 const char * const TableGenName;
2466 } // end anonymous namespace
2468 static const AttrClassDescriptor AttrClassDescriptors[] = {
2470 { "TYPE_ATTR", "TypeAttr" },
2471 { "STMT_ATTR", "StmtAttr" },
2472 { "INHERITABLE_ATTR", "InheritableAttr" },
2473 { "DECL_OR_TYPE_ATTR", "DeclOrTypeAttr" },
2474 { "INHERITABLE_PARAM_ATTR", "InheritableParamAttr" },
2475 { "PARAMETER_ABI_ATTR", "ParameterABIAttr" }
2478 static void emitDefaultDefine(raw_ostream &OS, StringRef name,
2479 const char *superName) {
2480 OS << "#ifndef " << name << "\n";
2481 OS << "#define " << name << "(NAME) ";
2482 if (superName) OS << superName << "(NAME)";
2483 OS << "\n#endif\n\n";
2488 /// A class of attributes.
2490 const AttrClassDescriptor &Descriptor;
2492 AttrClass *SuperClass = nullptr;
2493 std::vector<AttrClass*> SubClasses;
2494 std::vector<Record*> Attrs;
2496 AttrClass(const AttrClassDescriptor &Descriptor, Record *R)
2497 : Descriptor(Descriptor), TheRecord(R) {}
2499 void emitDefaultDefines(raw_ostream &OS) const {
2500 // Default the macro unless this is a root class (i.e. Attr).
2502 emitDefaultDefine(OS, Descriptor.MacroName,
2503 SuperClass->Descriptor.MacroName);
2507 void emitUndefs(raw_ostream &OS) const {
2508 OS << "#undef " << Descriptor.MacroName << "\n";
2511 void emitAttrList(raw_ostream &OS) const {
2512 for (auto SubClass : SubClasses) {
2513 SubClass->emitAttrList(OS);
2516 ::emitAttrList(OS, Descriptor.MacroName, Attrs);
2519 void classifyAttrOnRoot(Record *Attr) {
2520 bool result = classifyAttr(Attr);
2521 assert(result && "failed to classify on root"); (void) result;
2524 void emitAttrRange(raw_ostream &OS) const {
2525 OS << "ATTR_RANGE(" << Descriptor.TableGenName
2526 << ", " << getFirstAttr()->getName()
2527 << ", " << getLastAttr()->getName() << ")\n";
2531 bool classifyAttr(Record *Attr) {
2532 // Check all the subclasses.
2533 for (auto SubClass : SubClasses) {
2534 if (SubClass->classifyAttr(Attr))
2538 // It's not more specific than this class, but it might still belong here.
2539 if (Attr->isSubClassOf(TheRecord)) {
2540 Attrs.push_back(Attr);
2547 Record *getFirstAttr() const {
2548 if (!SubClasses.empty())
2549 return SubClasses.front()->getFirstAttr();
2550 return Attrs.front();
2553 Record *getLastAttr() const {
2555 return Attrs.back();
2556 return SubClasses.back()->getLastAttr();
2560 /// The entire hierarchy of attribute classes.
2561 class AttrClassHierarchy {
2562 std::vector<std::unique_ptr<AttrClass>> Classes;
2565 AttrClassHierarchy(RecordKeeper &Records) {
2566 // Find records for all the classes.
2567 for (auto &Descriptor : AttrClassDescriptors) {
2568 Record *ClassRecord = Records.getClass(Descriptor.TableGenName);
2569 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
2570 Classes.emplace_back(Class);
2573 // Link up the hierarchy.
2574 for (auto &Class : Classes) {
2575 if (AttrClass *SuperClass = findSuperClass(Class->TheRecord)) {
2576 Class->SuperClass = SuperClass;
2577 SuperClass->SubClasses.push_back(Class.get());
2582 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
2583 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
2584 "only the first class should be a root class!");
2589 void emitDefaultDefines(raw_ostream &OS) const {
2590 for (auto &Class : Classes) {
2591 Class->emitDefaultDefines(OS);
2595 void emitUndefs(raw_ostream &OS) const {
2596 for (auto &Class : Classes) {
2597 Class->emitUndefs(OS);
2601 void emitAttrLists(raw_ostream &OS) const {
2602 // Just start from the root class.
2603 Classes[0]->emitAttrList(OS);
2606 void emitAttrRanges(raw_ostream &OS) const {
2607 for (auto &Class : Classes)
2608 Class->emitAttrRange(OS);
2611 void classifyAttr(Record *Attr) {
2612 // Add the attribute to the root class.
2613 Classes[0]->classifyAttrOnRoot(Attr);
2617 AttrClass *findClassByRecord(Record *R) const {
2618 for (auto &Class : Classes) {
2619 if (Class->TheRecord == R)
2625 AttrClass *findSuperClass(Record *R) const {
2626 // TableGen flattens the superclass list, so we just need to walk it
2628 auto SuperClasses = R->getSuperClasses();
2629 for (signed i = 0, e = SuperClasses.size(); i != e; ++i) {
2630 auto SuperClass = findClassByRecord(SuperClasses[e - i - 1].first);
2631 if (SuperClass) return SuperClass;
2637 } // end anonymous namespace
2641 // Emits the enumeration list for attributes.
2642 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) {
2643 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
2645 AttrClassHierarchy Hierarchy(Records);
2647 // Add defaulting macro definitions.
2648 Hierarchy.emitDefaultDefines(OS);
2649 emitDefaultDefine(OS, "PRAGMA_SPELLING_ATTR", nullptr);
2651 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2652 std::vector<Record *> PragmaAttrs;
2653 for (auto *Attr : Attrs) {
2654 if (!Attr->getValueAsBit("ASTNode"))
2657 // Add the attribute to the ad-hoc groups.
2658 if (AttrHasPragmaSpelling(Attr))
2659 PragmaAttrs.push_back(Attr);
2661 // Place it in the hierarchy.
2662 Hierarchy.classifyAttr(Attr);
2665 // Emit the main attribute list.
2666 Hierarchy.emitAttrLists(OS);
2668 // Emit the ad hoc groups.
2669 emitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs);
2671 // Emit the attribute ranges.
2672 OS << "#ifdef ATTR_RANGE\n";
2673 Hierarchy.emitAttrRanges(OS);
2674 OS << "#undef ATTR_RANGE\n";
2677 Hierarchy.emitUndefs(OS);
2678 OS << "#undef PRAGMA_SPELLING_ATTR\n";
2681 // Emits the enumeration list for attributes.
2682 void EmitClangAttrSubjectMatchRuleList(RecordKeeper &Records, raw_ostream &OS) {
2683 emitSourceFileHeader(
2684 "List of all attribute subject matching rules that Clang recognizes", OS);
2685 PragmaClangAttributeSupport &PragmaAttributeSupport =
2686 getPragmaAttributeSupport(Records);
2687 emitDefaultDefine(OS, "ATTR_MATCH_RULE", nullptr);
2688 PragmaAttributeSupport.emitMatchRuleList(OS);
2689 OS << "#undef ATTR_MATCH_RULE\n";
2692 // Emits the code to read an attribute from a precompiled header.
2693 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) {
2694 emitSourceFileHeader("Attribute deserialization code", OS);
2696 Record *InhClass = Records.getClass("InheritableAttr");
2697 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"),
2699 std::vector<std::unique_ptr<Argument>> Args;
2701 OS << " switch (Kind) {\n";
2702 for (const auto *Attr : Attrs) {
2703 const Record &R = *Attr;
2704 if (!R.getValueAsBit("ASTNode"))
2707 OS << " case attr::" << R.getName() << ": {\n";
2708 if (R.isSubClassOf(InhClass))
2709 OS << " bool isInherited = Record.readInt();\n";
2710 OS << " bool isImplicit = Record.readInt();\n";
2711 OS << " unsigned Spelling = Record.readInt();\n";
2712 ArgRecords = R.getValueAsListOfDefs("Args");
2714 for (const auto *Arg : ArgRecords) {
2715 Args.emplace_back(createArgument(*Arg, R.getName()));
2716 Args.back()->writePCHReadDecls(OS);
2718 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context";
2719 for (auto const &ri : Args) {
2721 ri->writePCHReadArgs(OS);
2723 OS << ", Spelling);\n";
2724 if (R.isSubClassOf(InhClass))
2725 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
2726 OS << " New->setImplicit(isImplicit);\n";
2733 // Emits the code to write an attribute to a precompiled header.
2734 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) {
2735 emitSourceFileHeader("Attribute serialization code", OS);
2737 Record *InhClass = Records.getClass("InheritableAttr");
2738 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
2740 OS << " switch (A->getKind()) {\n";
2741 for (const auto *Attr : Attrs) {
2742 const Record &R = *Attr;
2743 if (!R.getValueAsBit("ASTNode"))
2745 OS << " case attr::" << R.getName() << ": {\n";
2746 Args = R.getValueAsListOfDefs("Args");
2747 if (R.isSubClassOf(InhClass) || !Args.empty())
2748 OS << " const auto *SA = cast<" << R.getName()
2750 if (R.isSubClassOf(InhClass))
2751 OS << " Record.push_back(SA->isInherited());\n";
2752 OS << " Record.push_back(A->isImplicit());\n";
2753 OS << " Record.push_back(A->getSpellingListIndex());\n";
2755 for (const auto *Arg : Args)
2756 createArgument(*Arg, R.getName())->writePCHWrite(OS);
2763 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
2764 // parameter with only a single check type, if applicable.
2765 static void GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
2766 std::string *FnName,
2768 StringRef CheckAgainst,
2770 if (!R->isValueUnset(ListName)) {
2772 std::vector<StringRef> Items = R->getValueAsListOfStrings(ListName);
2773 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
2774 StringRef Part = *I;
2775 Test += CheckAgainst;
2788 // Generate a conditional expression to check if the current target satisfies
2789 // the conditions for a TargetSpecificAttr record, and append the code for
2790 // those checks to the Test string. If the FnName string pointer is non-null,
2791 // append a unique suffix to distinguish this set of target checks from other
2792 // TargetSpecificAttr records.
2793 static void GenerateTargetSpecificAttrChecks(const Record *R,
2794 std::vector<StringRef> &Arches,
2796 std::string *FnName) {
2797 // It is assumed that there will be an llvm::Triple object
2798 // named "T" and a TargetInfo object named "Target" within
2799 // scope that can be used to determine whether the attribute exists in
2802 // If one or more architectures is specified, check those. Arches are handled
2803 // differently because GenerateTargetRequirements needs to combine the list
2805 if (!Arches.empty()) {
2807 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
2808 StringRef Part = *I;
2809 Test += "T.getArch() == llvm::Triple::";
2819 // If the attribute is specific to particular OSes, check those.
2820 GenerateTargetSpecificAttrCheck(R, Test, FnName, "OSes", "T.getOS()",
2823 // If one or more CXX ABIs are specified, check those as well.
2824 GenerateTargetSpecificAttrCheck(R, Test, FnName, "CXXABIs",
2825 "Target.getCXXABI().getKind()",
2827 // If one or more object formats is specified, check those.
2828 GenerateTargetSpecificAttrCheck(R, Test, FnName, "ObjectFormats",
2829 "T.getObjectFormat()", "llvm::Triple::");
2832 static void GenerateHasAttrSpellingStringSwitch(
2833 const std::vector<Record *> &Attrs, raw_ostream &OS,
2834 const std::string &Variety = "", const std::string &Scope = "") {
2835 for (const auto *Attr : Attrs) {
2836 // C++11-style attributes have specific version information associated with
2837 // them. If the attribute has no scope, the version information must not
2838 // have the default value (1), as that's incorrect. Instead, the unscoped
2839 // attribute version information should be taken from the SD-6 standing
2840 // document, which can be found at:
2841 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
2844 if (Variety == "CXX11") {
2845 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings");
2846 for (const auto &Spelling : Spellings) {
2847 if (Spelling->getValueAsString("Variety") == "CXX11") {
2848 Version = static_cast<int>(Spelling->getValueAsInt("Version"));
2849 if (Scope.empty() && Version == 1)
2850 PrintError(Spelling->getLoc(), "C++ standard attributes must "
2851 "have valid version information.");
2858 if (Attr->isSubClassOf("TargetSpecificAttr")) {
2859 const Record *R = Attr->getValueAsDef("Target");
2860 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
2861 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr);
2863 // If this is the C++11 variety, also add in the LangOpts test.
2864 if (Variety == "CXX11")
2865 Test += " && LangOpts.CPlusPlus11";
2866 else if (Variety == "C2x")
2867 Test += " && LangOpts.DoubleSquareBracketAttributes";
2868 } else if (Variety == "CXX11")
2869 // C++11 mode should be checked against LangOpts, which is presumed to be
2870 // present in the caller.
2871 Test = "LangOpts.CPlusPlus11";
2872 else if (Variety == "C2x")
2873 Test = "LangOpts.DoubleSquareBracketAttributes";
2875 std::string TestStr =
2876 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1";
2877 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr);
2878 for (const auto &S : Spellings)
2879 if (Variety.empty() || (Variety == S.variety() &&
2880 (Scope.empty() || Scope == S.nameSpace())))
2881 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n";
2883 OS << " .Default(0);\n";
2886 // Emits the list of spellings for attributes.
2887 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
2888 emitSourceFileHeader("Code to implement the __has_attribute logic", OS);
2890 // Separate all of the attributes out into four group: generic, C++11, GNU,
2891 // and declspecs. Then generate a big switch statement for each of them.
2892 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
2893 std::vector<Record *> Declspec, Microsoft, GNU, Pragma;
2894 std::map<std::string, std::vector<Record *>> CXX, C2x;
2896 // Walk over the list of all attributes, and split them out based on the
2897 // spelling variety.
2898 for (auto *R : Attrs) {
2899 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R);
2900 for (const auto &SI : Spellings) {
2901 const std::string &Variety = SI.variety();
2902 if (Variety == "GNU")
2904 else if (Variety == "Declspec")
2905 Declspec.push_back(R);
2906 else if (Variety == "Microsoft")
2907 Microsoft.push_back(R);
2908 else if (Variety == "CXX11")
2909 CXX[SI.nameSpace()].push_back(R);
2910 else if (Variety == "C2x")
2911 C2x[SI.nameSpace()].push_back(R);
2912 else if (Variety == "Pragma")
2913 Pragma.push_back(R);
2917 OS << "const llvm::Triple &T = Target.getTriple();\n";
2918 OS << "switch (Syntax) {\n";
2919 OS << "case AttrSyntax::GNU:\n";
2920 OS << " return llvm::StringSwitch<int>(Name)\n";
2921 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU");
2922 OS << "case AttrSyntax::Declspec:\n";
2923 OS << " return llvm::StringSwitch<int>(Name)\n";
2924 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec");
2925 OS << "case AttrSyntax::Microsoft:\n";
2926 OS << " return llvm::StringSwitch<int>(Name)\n";
2927 GenerateHasAttrSpellingStringSwitch(Microsoft, OS, "Microsoft");
2928 OS << "case AttrSyntax::Pragma:\n";
2929 OS << " return llvm::StringSwitch<int>(Name)\n";
2930 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma");
2931 auto fn = [&OS](const char *Spelling, const char *Variety,
2932 const std::map<std::string, std::vector<Record *>> &List) {
2933 OS << "case AttrSyntax::" << Variety << ": {\n";
2934 // C++11-style attributes are further split out based on the Scope.
2935 for (auto I = List.cbegin(), E = List.cend(); I != E; ++I) {
2936 if (I != List.cbegin())
2938 if (I->first.empty())
2939 OS << "if (ScopeName == \"\") {\n";
2941 OS << "if (ScopeName == \"" << I->first << "\") {\n";
2942 OS << " return llvm::StringSwitch<int>(Name)\n";
2943 GenerateHasAttrSpellingStringSwitch(I->second, OS, Spelling, I->first);
2946 OS << "\n} break;\n";
2948 fn("CXX11", "CXX", CXX);
2949 fn("C2x", "C", C2x);
2953 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) {
2954 emitSourceFileHeader("Code to translate different attribute spellings "
2955 "into internal identifiers", OS);
2957 OS << " switch (AttrKind) {\n";
2959 ParsedAttrMap Attrs = getParsedAttrList(Records);
2960 for (const auto &I : Attrs) {
2961 const Record &R = *I.second;
2962 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
2963 OS << " case AT_" << I.first << ": {\n";
2964 for (unsigned I = 0; I < Spellings.size(); ++ I) {
2965 OS << " if (Name == \"" << Spellings[I].name() << "\" && "
2967 << StringSwitch<unsigned>(Spellings[I].variety())
2971 .Case("Declspec", 3)
2972 .Case("Microsoft", 4)
2976 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n"
2977 << " return " << I << ";\n";
2985 OS << " return 0;\n";
2988 // Emits code used by RecursiveASTVisitor to visit attributes
2989 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) {
2990 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS);
2992 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
2994 // Write method declarations for Traverse* methods.
2995 // We emit this here because we only generate methods for attributes that
2996 // are declared as ASTNodes.
2997 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
2998 for (const auto *Attr : Attrs) {
2999 const Record &R = *Attr;
3000 if (!R.getValueAsBit("ASTNode"))
3002 OS << " bool Traverse"
3003 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
3005 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3006 << " return true; \n"
3009 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3011 // Write individual Traverse* methods for each attribute class.
3012 for (const auto *Attr : Attrs) {
3013 const Record &R = *Attr;
3014 if (!R.getValueAsBit("ASTNode"))
3017 OS << "template <typename Derived>\n"
3018 << "bool VISITORCLASS<Derived>::Traverse"
3019 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
3020 << " if (!getDerived().VisitAttr(A))\n"
3021 << " return false;\n"
3022 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
3023 << " return false;\n";
3025 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3026 for (const auto *Arg : ArgRecords)
3027 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS);
3029 OS << " return true;\n";
3033 // Write generic Traverse routine
3034 OS << "template <typename Derived>\n"
3035 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3037 << " return true;\n"
3039 << " switch (A->getKind()) {\n";
3041 for (const auto *Attr : Attrs) {
3042 const Record &R = *Attr;
3043 if (!R.getValueAsBit("ASTNode"))
3046 OS << " case attr::" << R.getName() << ":\n"
3047 << " return getDerived().Traverse" << R.getName() << "Attr("
3048 << "cast<" << R.getName() << "Attr>(A));\n";
3050 OS << " }\n"; // end switch
3051 OS << " llvm_unreachable(\"bad attribute kind\");\n";
3052 OS << "}\n"; // end function
3053 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3056 void EmitClangAttrTemplateInstantiateHelper(const std::vector<Record *> &Attrs,
3058 bool AppliesToDecl) {
3060 OS << " switch (At->getKind()) {\n";
3061 for (const auto *Attr : Attrs) {
3062 const Record &R = *Attr;
3063 if (!R.getValueAsBit("ASTNode"))
3065 OS << " case attr::" << R.getName() << ": {\n";
3066 bool ShouldClone = R.getValueAsBit("Clone") &&
3068 R.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3071 OS << " return nullptr;\n";
3076 OS << " const auto *A = cast<"
3077 << R.getName() << "Attr>(At);\n";
3078 bool TDependent = R.getValueAsBit("TemplateDependent");
3081 OS << " return A->clone(C);\n";
3086 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args");
3087 std::vector<std::unique_ptr<Argument>> Args;
3088 Args.reserve(ArgRecords.size());
3090 for (const auto *ArgRecord : ArgRecords)
3091 Args.emplace_back(createArgument(*ArgRecord, R.getName()));
3093 for (auto const &ai : Args)
3094 ai->writeTemplateInstantiation(OS);
3096 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C";
3097 for (auto const &ai : Args) {
3099 ai->writeTemplateInstantiationArgs(OS);
3101 OS << ", A->getSpellingListIndex());\n }\n";
3103 OS << " } // end switch\n"
3104 << " llvm_unreachable(\"Unknown attribute!\");\n"
3105 << " return nullptr;\n";
3108 // Emits code to instantiate dependent attributes on templates.
3109 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) {
3110 emitSourceFileHeader("Template instantiation code for attributes", OS);
3112 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr");
3114 OS << "namespace clang {\n"
3115 << "namespace sema {\n\n"
3116 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
3118 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3119 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
3121 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
3122 << " ASTContext &C, Sema &S,\n"
3123 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
3124 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
3126 << "} // end namespace sema\n"
3127 << "} // end namespace clang\n";
3130 // Emits the list of parsed attributes.
3131 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) {
3132 emitSourceFileHeader("List of all attributes that Clang recognizes", OS);
3134 OS << "#ifndef PARSED_ATTR\n";
3135 OS << "#define PARSED_ATTR(NAME) NAME\n";
3138 ParsedAttrMap Names = getParsedAttrList(Records);
3139 for (const auto &I : Names) {
3140 OS << "PARSED_ATTR(" << I.first << ")\n";
3144 static bool isArgVariadic(const Record &R, StringRef AttrName) {
3145 return createArgument(R, AttrName)->isVariadic();
3148 static void emitArgInfo(const Record &R, raw_ostream &OS) {
3149 // This function will count the number of arguments specified for the
3150 // attribute and emit the number of required arguments followed by the
3151 // number of optional arguments.
3152 std::vector<Record *> Args = R.getValueAsListOfDefs("Args");
3153 unsigned ArgCount = 0, OptCount = 0;
3154 bool HasVariadic = false;
3155 for (const auto *Arg : Args) {
3156 // If the arg is fake, it's the user's job to supply it: general parsing
3157 // logic shouldn't need to know anything about it.
3158 if (Arg->getValueAsBit("Fake"))
3160 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount;
3161 if (!HasVariadic && isArgVariadic(*Arg, R.getName()))
3165 // If there is a variadic argument, we will set the optional argument count
3166 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
3167 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount);
3170 static void GenerateDefaultAppertainsTo(raw_ostream &OS) {
3171 OS << "static bool defaultAppertainsTo(Sema &, const ParsedAttr &,";
3172 OS << "const Decl *) {\n";
3173 OS << " return true;\n";
3177 static std::string GetDiagnosticSpelling(const Record &R) {
3178 std::string Ret = R.getValueAsString("DiagSpelling");
3182 // If we couldn't find the DiagSpelling in this object, we can check to see
3183 // if the object is one that has a base, and if it is, loop up to the Base
3184 // member recursively.
3185 std::string Super = R.getSuperClasses().back().first->getName();
3186 if (Super == "DDecl" || Super == "DStmt")
3187 return GetDiagnosticSpelling(*R.getValueAsDef("Base"));
3192 static std::string CalculateDiagnostic(const Record &S) {
3193 // If the SubjectList object has a custom diagnostic associated with it,
3194 // return that directly.
3195 const StringRef CustomDiag = S.getValueAsString("CustomDiag");
3196 if (!CustomDiag.empty())
3197 return ("\"" + Twine(CustomDiag) + "\"").str();
3199 std::vector<std::string> DiagList;
3200 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects");
3201 for (const auto *Subject : Subjects) {
3202 const Record &R = *Subject;
3203 // Get the diagnostic text from the Decl or Stmt node given.
3204 std::string V = GetDiagnosticSpelling(R);
3206 PrintError(R.getLoc(),
3207 "Could not determine diagnostic spelling for the node: " +
3208 R.getName() + "; please add one to DeclNodes.td");
3210 // The node may contain a list of elements itself, so split the elements
3211 // by a comma, and trim any whitespace.
3212 SmallVector<StringRef, 2> Frags;
3213 llvm::SplitString(V, Frags, ",");
3214 for (auto Str : Frags) {
3215 DiagList.push_back(Str.trim());
3220 if (DiagList.empty()) {
3221 PrintFatalError(S.getLoc(),
3222 "Could not deduce diagnostic argument for Attr subjects");
3226 // FIXME: this is not particularly good for localization purposes and ideally
3227 // should be part of the diagnostics engine itself with some sort of list
3230 // A single member of the list can be returned directly.
3231 if (DiagList.size() == 1)
3232 return '"' + DiagList.front() + '"';
3234 if (DiagList.size() == 2)
3235 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
3237 // If there are more than two in the list, we serialize the first N - 1
3238 // elements with a comma. This leaves the string in the state: foo, bar,
3239 // baz (but misses quux). We can then add ", and " for the last element
3241 std::string Diag = llvm::join(DiagList.begin(), DiagList.end() - 1, ", ");
3242 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
3245 static std::string GetSubjectWithSuffix(const Record *R) {
3246 const std::string &B = R->getName();
3247 if (B == "DeclBase")
3252 static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
3253 return "is" + Subject.getName().str();
3256 static std::string GenerateCustomAppertainsTo(const Record &Subject,
3258 std::string FnName = functionNameForCustomAppertainsTo(Subject);
3260 // If this code has already been generated, simply return the previous
3262 static std::set<std::string> CustomSubjectSet;
3263 auto I = CustomSubjectSet.find(FnName);
3264 if (I != CustomSubjectSet.end())
3267 Record *Base = Subject.getValueAsDef("Base");
3269 // Not currently support custom subjects within custom subjects.
3270 if (Base->isSubClassOf("SubsetSubject")) {
3271 PrintFatalError(Subject.getLoc(),
3272 "SubsetSubjects within SubsetSubjects is not supported");
3276 OS << "static bool " << FnName << "(const Decl *D) {\n";
3277 OS << " if (const auto *S = dyn_cast<";
3278 OS << GetSubjectWithSuffix(Base);
3280 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n";
3281 OS << " return false;\n";
3284 CustomSubjectSet.insert(FnName);
3288 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
3289 // If the attribute does not contain a Subjects definition, then use the
3290 // default appertainsTo logic.
3291 if (Attr.isValueUnset("Subjects"))
3292 return "defaultAppertainsTo";
3294 const Record *SubjectObj = Attr.getValueAsDef("Subjects");
3295 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects");
3297 // If the list of subjects is empty, it is assumed that the attribute
3298 // appertains to everything.
3299 if (Subjects.empty())
3300 return "defaultAppertainsTo";
3302 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn");
3304 // Otherwise, generate an appertainsTo check specific to this attribute which
3305 // checks all of the given subjects against the Decl passed in. Return the
3306 // name of that check to the caller.
3308 // If D is null, that means the attribute was not applied to a declaration
3309 // at all (for instance because it was applied to a type), or that the caller
3310 // has determined that the check should fail (perhaps prior to the creation
3311 // of the declaration).
3312 std::string FnName = "check" + Attr.getName().str() + "AppertainsTo";
3313 std::stringstream SS;
3314 SS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr, ";
3315 SS << "const Decl *D) {\n";
3316 SS << " if (!D || (";
3317 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3318 // If the subject has custom code associated with it, generate a function
3319 // for it. The function cannot be inlined into this check (yet) because it
3320 // requires the subject to be of a specific type, and were that information
3321 // inlined here, it would not support an attribute with multiple custom
3323 if ((*I)->isSubClassOf("SubsetSubject")) {
3324 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)";
3326 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3333 SS << " S.Diag(Attr.getLoc(), diag::";
3334 SS << (Warn ? "warn_attribute_wrong_decl_type_str" :
3335 "err_attribute_wrong_decl_type_str");
3337 SS << " << Attr << ";
3338 SS << CalculateDiagnostic(*SubjectObj) << ";\n";
3339 SS << " return false;\n";
3341 SS << " return true;\n";
3349 emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
3351 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
3352 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
3353 OS << " switch (rule) {\n";
3354 for (const auto &Rule : PragmaAttributeSupport.Rules) {
3355 if (Rule.isAbstractRule()) {
3356 OS << " case " << Rule.getEnumValue() << ":\n";
3357 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
3358 OS << " return false;\n";
3361 std::vector<Record *> Subjects = Rule.getSubjects();
3362 assert(!Subjects.empty() && "Missing subjects");
3363 OS << " case " << Rule.getEnumValue() << ":\n";
3365 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
3366 // If the subject has custom code associated with it, use the function
3367 // that was generated for GenerateAppertainsTo to check if the declaration
3369 if ((*I)->isSubClassOf("SubsetSubject"))
3370 OS << functionNameForCustomAppertainsTo(**I) << "(D)";
3372 OS << "isa<" << GetSubjectWithSuffix(*I) << ">(D)";
3380 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
3384 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) {
3385 OS << "static bool defaultDiagnoseLangOpts(Sema &, ";
3386 OS << "const ParsedAttr &) {\n";
3387 OS << " return true;\n";
3391 static std::string GenerateLangOptRequirements(const Record &R,
3393 // If the attribute has an empty or unset list of language requirements,
3394 // return the default handler.
3395 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts");
3396 if (LangOpts.empty())
3397 return "defaultDiagnoseLangOpts";
3399 // Generate the test condition, as well as a unique function name for the
3400 // diagnostic test. The list of options should usually be short (one or two
3401 // options), and the uniqueness isn't strictly necessary (it is just for
3402 // codegen efficiency).
3403 std::string FnName = "check", Test;
3404 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) {
3405 const StringRef Part = (*I)->getValueAsString("Name");
3406 if ((*I)->getValueAsBit("Negated")) {
3410 Test += "S.LangOpts.";
3416 FnName += "LangOpts";
3418 // If this code has already been generated, simply return the previous
3420 static std::set<std::string> CustomLangOptsSet;
3421 auto I = CustomLangOptsSet.find(FnName);
3422 if (I != CustomLangOptsSet.end())
3425 OS << "static bool " << FnName << "(Sema &S, const ParsedAttr &Attr) {\n";
3426 OS << " if (" << Test << ")\n";
3427 OS << " return true;\n\n";
3428 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) ";
3429 OS << "<< Attr.getName();\n";
3430 OS << " return false;\n";
3433 CustomLangOptsSet.insert(FnName);
3437 static void GenerateDefaultTargetRequirements(raw_ostream &OS) {
3438 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n";
3439 OS << " return true;\n";
3443 static std::string GenerateTargetRequirements(const Record &Attr,
3444 const ParsedAttrMap &Dupes,
3446 // If the attribute is not a target specific attribute, return the default
3448 if (!Attr.isSubClassOf("TargetSpecificAttr"))
3449 return "defaultTargetRequirements";
3451 // Get the list of architectures to be tested for.
3452 const Record *R = Attr.getValueAsDef("Target");
3453 std::vector<StringRef> Arches = R->getValueAsListOfStrings("Arches");
3455 // If there are other attributes which share the same parsed attribute kind,
3456 // such as target-specific attributes with a shared spelling, collapse the
3457 // duplicate architectures. This is required because a shared target-specific
3458 // attribute has only one ParsedAttr::Kind enumeration value, but it
3459 // applies to multiple target architectures. In order for the attribute to be
3460 // considered valid, all of its architectures need to be included.
3461 if (!Attr.isValueUnset("ParseKind")) {
3462 const StringRef APK = Attr.getValueAsString("ParseKind");
3463 for (const auto &I : Dupes) {
3464 if (I.first == APK) {
3465 std::vector<StringRef> DA =
3466 I.second->getValueAsDef("Target")->getValueAsListOfStrings(
3468 Arches.insert(Arches.end(), DA.begin(), DA.end());
3473 std::string FnName = "isTarget";
3475 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName);
3477 // If this code has already been generated, simply return the previous
3479 static std::set<std::string> CustomTargetSet;
3480 auto I = CustomTargetSet.find(FnName);
3481 if (I != CustomTargetSet.end())
3484 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n";
3485 OS << " const llvm::Triple &T = Target.getTriple();\n";
3486 OS << " return " << Test << ";\n";
3489 CustomTargetSet.insert(FnName);
3493 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) {
3494 OS << "static unsigned defaultSpellingIndexToSemanticSpelling("
3495 << "const ParsedAttr &Attr) {\n";
3496 OS << " return UINT_MAX;\n";
3500 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
3502 // If the attribute does not have a semantic form, we can bail out early.
3503 if (!Attr.getValueAsBit("ASTNode"))
3504 return "defaultSpellingIndexToSemanticSpelling";
3506 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3508 // If there are zero or one spellings, or all of the spellings share the same
3509 // name, we can also bail out early.
3510 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
3511 return "defaultSpellingIndexToSemanticSpelling";
3513 // Generate the enumeration we will use for the mapping.
3514 SemanticSpellingMap SemanticToSyntacticMap;
3515 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap);
3516 std::string Name = Attr.getName().str() + "AttrSpellingMap";
3518 OS << "static unsigned " << Name << "(const ParsedAttr &Attr) {\n";
3520 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
3521 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS);
3527 static bool IsKnownToGCC(const Record &Attr) {
3528 // Look at the spellings for this subject; if there are any spellings which
3529 // claim to be known to GCC, the attribute is known to GCC.
3530 return llvm::any_of(
3531 GetFlattenedSpellings(Attr),
3532 [](const FlattenedSpelling &S) { return S.knownToGCC(); });
3535 /// Emits the parsed attribute helpers
3536 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) {
3537 emitSourceFileHeader("Parsed attribute helpers", OS);
3539 PragmaClangAttributeSupport &PragmaAttributeSupport =
3540 getPragmaAttributeSupport(Records);
3542 // Get the list of parsed attributes, and accept the optional list of
3543 // duplicates due to the ParseKind.
3544 ParsedAttrMap Dupes;
3545 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes);
3547 // Generate the default appertainsTo, target and language option diagnostic,
3548 // and spelling list index mapping methods.
3549 GenerateDefaultAppertainsTo(OS);
3550 GenerateDefaultLangOptRequirements(OS);
3551 GenerateDefaultTargetRequirements(OS);
3552 GenerateDefaultSpellingIndexToSemanticSpelling(OS);
3554 // Generate the appertainsTo diagnostic methods and write their names into
3555 // another mapping. At the same time, generate the AttrInfoMap object
3556 // contents. Due to the reliance on generated code, use separate streams so
3557 // that code will not be interleaved.
3559 raw_string_ostream SS {Buffer};
3560 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
3561 // TODO: If the attribute's kind appears in the list of duplicates, that is
3562 // because it is a target-specific attribute that appears multiple times.
3563 // It would be beneficial to test whether the duplicates are "similar
3564 // enough" to each other to not cause problems. For instance, check that
3565 // the spellings are identical, and custom parsing rules match, etc.
3567 // We need to generate struct instances based off ParsedAttrInfo from
3570 emitArgInfo(*I->second, SS);
3571 SS << ", " << I->second->getValueAsBit("HasCustomParsing");
3572 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr");
3574 << (I->second->isSubClassOf("TypeAttr") ||
3575 I->second->isSubClassOf("DeclOrTypeAttr"));
3576 SS << ", " << I->second->isSubClassOf("StmtAttr");
3577 SS << ", " << IsKnownToGCC(*I->second);
3578 SS << ", " << PragmaAttributeSupport.isAttributedSupported(*I->second);
3579 SS << ", " << GenerateAppertainsTo(*I->second, OS);
3580 SS << ", " << GenerateLangOptRequirements(*I->second, OS);
3581 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS);
3582 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS);
3584 << PragmaAttributeSupport.generateStrictConformsTo(*I->second, OS);
3590 SS << " // AT_" << I->first << "\n";
3593 OS << "static const ParsedAttrInfo AttrInfoMap[ParsedAttr::UnknownAttribute "
3598 // Generate the attribute match rules.
3599 emitAttributeMatchRules(PragmaAttributeSupport, OS);
3602 // Emits the kind list of parsed attributes
3603 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) {
3604 emitSourceFileHeader("Attribute name matcher", OS);
3606 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3607 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
3608 Keywords, Pragma, C2x;
3609 std::set<std::string> Seen;
3610 for (const auto *A : Attrs) {
3611 const Record &Attr = *A;
3613 bool SemaHandler = Attr.getValueAsBit("SemaHandler");
3614 bool Ignored = Attr.getValueAsBit("Ignored");
3615 if (SemaHandler || Ignored) {
3616 // Attribute spellings can be shared between target-specific attributes,
3617 // and can be shared between syntaxes for the same attribute. For
3618 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
3619 // specific attribute, or MSP430-specific attribute. Additionally, an
3620 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
3621 // for the same semantic attribute. Ultimately, we need to map each of
3622 // these to a single ParsedAttr::Kind value, but the StringMatcher
3623 // class cannot handle duplicate match strings. So we generate a list of
3624 // string to match based on the syntax, and emit multiple string matchers
3625 // depending on the syntax used.
3626 std::string AttrName;
3627 if (Attr.isSubClassOf("TargetSpecificAttr") &&
3628 !Attr.isValueUnset("ParseKind")) {
3629 AttrName = Attr.getValueAsString("ParseKind");
3630 if (Seen.find(AttrName) != Seen.end())
3632 Seen.insert(AttrName);
3634 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str();
3636 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
3637 for (const auto &S : Spellings) {
3638 const std::string &RawSpelling = S.name();
3639 std::vector<StringMatcher::StringPair> *Matches = nullptr;
3640 std::string Spelling;
3641 const std::string &Variety = S.variety();
3642 if (Variety == "CXX11") {
3644 Spelling += S.nameSpace();
3646 } else if (Variety == "C2x") {
3648 Spelling += S.nameSpace();
3650 } else if (Variety == "GNU")
3652 else if (Variety == "Declspec")
3653 Matches = &Declspec;
3654 else if (Variety == "Microsoft")
3655 Matches = &Microsoft;
3656 else if (Variety == "Keyword")
3657 Matches = &Keywords;
3658 else if (Variety == "Pragma")
3661 assert(Matches && "Unsupported spelling variety found");
3663 if (Variety == "GNU")
3664 Spelling += NormalizeGNUAttrSpelling(RawSpelling);
3666 Spelling += RawSpelling;
3669 Matches->push_back(StringMatcher::StringPair(
3670 Spelling, "return ParsedAttr::AT_" + AttrName + ";"));
3672 Matches->push_back(StringMatcher::StringPair(
3673 Spelling, "return ParsedAttr::IgnoredAttribute;"));
3678 OS << "static ParsedAttr::Kind getAttrKind(StringRef Name, ";
3679 OS << "ParsedAttr::Syntax Syntax) {\n";
3680 OS << " if (ParsedAttr::AS_GNU == Syntax) {\n";
3681 StringMatcher("Name", GNU, OS).Emit();
3682 OS << " } else if (ParsedAttr::AS_Declspec == Syntax) {\n";
3683 StringMatcher("Name", Declspec, OS).Emit();
3684 OS << " } else if (ParsedAttr::AS_Microsoft == Syntax) {\n";
3685 StringMatcher("Name", Microsoft, OS).Emit();
3686 OS << " } else if (ParsedAttr::AS_CXX11 == Syntax) {\n";
3687 StringMatcher("Name", CXX11, OS).Emit();
3688 OS << " } else if (ParsedAttr::AS_C2x == Syntax) {\n";
3689 StringMatcher("Name", C2x, OS).Emit();
3690 OS << " } else if (ParsedAttr::AS_Keyword == Syntax || ";
3691 OS << "ParsedAttr::AS_ContextSensitiveKeyword == Syntax) {\n";
3692 StringMatcher("Name", Keywords, OS).Emit();
3693 OS << " } else if (ParsedAttr::AS_Pragma == Syntax) {\n";
3694 StringMatcher("Name", Pragma, OS).Emit();
3696 OS << " return ParsedAttr::UnknownAttribute;\n"
3700 // Emits the code to dump an attribute.
3701 void EmitClangAttrTextNodeDump(RecordKeeper &Records, raw_ostream &OS) {
3702 emitSourceFileHeader("Attribute text node dumper", OS);
3704 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3705 for (const auto *Attr : Attrs) {
3706 const Record &R = *Attr;
3707 if (!R.getValueAsBit("ASTNode"))
3710 // If the attribute has a semantically-meaningful name (which is determined
3711 // by whether there is a Spelling enumeration for it), then write out the
3712 // spelling used for the attribute.
3714 std::string FunctionContent;
3715 llvm::raw_string_ostream SS(FunctionContent);
3717 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R);
3718 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
3719 SS << " OS << \" \" << A->getSpelling();\n";
3721 Args = R.getValueAsListOfDefs("Args");
3722 for (const auto *Arg : Args)
3723 createArgument(*Arg, R.getName())->writeDump(SS);
3726 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3729 OS << " const auto *SA = cast<" << R.getName()
3730 << "Attr>(A); (void)SA;\n";
3737 void EmitClangAttrNodeTraverse(RecordKeeper &Records, raw_ostream &OS) {
3738 emitSourceFileHeader("Attribute text node traverser", OS);
3740 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), Args;
3741 for (const auto *Attr : Attrs) {
3742 const Record &R = *Attr;
3743 if (!R.getValueAsBit("ASTNode"))
3746 std::string FunctionContent;
3747 llvm::raw_string_ostream SS(FunctionContent);
3749 Args = R.getValueAsListOfDefs("Args");
3750 for (const auto *Arg : Args)
3751 createArgument(*Arg, R.getName())->writeDumpChildren(SS);
3753 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
3756 OS << " const auto *SA = cast<" << R.getName()
3757 << "Attr>(A); (void)SA;\n";
3764 void EmitClangAttrParserStringSwitches(RecordKeeper &Records,
3766 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS);
3767 emitClangAttrArgContextList(Records, OS);
3768 emitClangAttrIdentifierArgList(Records, OS);
3769 emitClangAttrVariadicIdentifierArgList(Records, OS);
3770 emitClangAttrTypeArgList(Records, OS);
3771 emitClangAttrLateParsedList(Records, OS);
3774 void EmitClangAttrSubjectMatchRulesParserStringSwitches(RecordKeeper &Records,
3776 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
3779 enum class SpellingKind {
3788 static const size_t NumSpellingKinds = (size_t)SpellingKind::Pragma + 1;
3790 class SpellingList {
3791 std::vector<std::string> Spellings[NumSpellingKinds];
3794 ArrayRef<std::string> operator[](SpellingKind K) const {
3795 return Spellings[(size_t)K];
3798 void add(const Record &Attr, FlattenedSpelling Spelling) {
3799 SpellingKind Kind = StringSwitch<SpellingKind>(Spelling.variety())
3800 .Case("GNU", SpellingKind::GNU)
3801 .Case("CXX11", SpellingKind::CXX11)
3802 .Case("C2x", SpellingKind::C2x)
3803 .Case("Declspec", SpellingKind::Declspec)
3804 .Case("Microsoft", SpellingKind::Microsoft)
3805 .Case("Keyword", SpellingKind::Keyword)
3806 .Case("Pragma", SpellingKind::Pragma);
3808 if (!Spelling.nameSpace().empty()) {
3810 case SpellingKind::CXX11:
3811 case SpellingKind::C2x:
3812 Name = Spelling.nameSpace() + "::";
3814 case SpellingKind::Pragma:
3815 Name = Spelling.nameSpace() + " ";
3818 PrintFatalError(Attr.getLoc(), "Unexpected namespace in spelling");
3821 Name += Spelling.name();
3823 Spellings[(size_t)Kind].push_back(Name);
3827 class DocumentationData {
3829 const Record *Documentation;
3830 const Record *Attribute;
3831 std::string Heading;
3832 SpellingList SupportedSpellings;
3834 DocumentationData(const Record &Documentation, const Record &Attribute,
3835 std::pair<std::string, SpellingList> HeadingAndSpellings)
3836 : Documentation(&Documentation), Attribute(&Attribute),
3837 Heading(std::move(HeadingAndSpellings.first)),
3838 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
3841 static void WriteCategoryHeader(const Record *DocCategory,
3843 const StringRef Name = DocCategory->getValueAsString("Name");
3844 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
3846 // If there is content, print that as well.
3847 const StringRef ContentStr = DocCategory->getValueAsString("Content");
3848 // Trim leading and trailing newlines and spaces.
3849 OS << ContentStr.trim();
3854 static std::pair<std::string, SpellingList>
3855 GetAttributeHeadingAndSpellings(const Record &Documentation,
3856 const Record &Attribute) {
3857 // FIXME: there is no way to have a per-spelling category for the attribute
3858 // documentation. This may not be a limiting factor since the spellings
3859 // should generally be consistently applied across the category.
3861 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attribute);
3862 if (Spellings.empty())
3863 PrintFatalError(Attribute.getLoc(),
3864 "Attribute has no supported spellings; cannot be "
3867 // Determine the heading to be used for this attribute.
3868 std::string Heading = Documentation.getValueAsString("Heading");
3869 if (Heading.empty()) {
3870 // If there's only one spelling, we can simply use that.
3871 if (Spellings.size() == 1)
3872 Heading = Spellings.begin()->name();
3874 std::set<std::string> Uniques;
3875 for (auto I = Spellings.begin(), E = Spellings.end();
3876 I != E && Uniques.size() <= 1; ++I) {
3877 std::string Spelling = NormalizeNameForSpellingComparison(I->name());
3878 Uniques.insert(Spelling);
3880 // If the semantic map has only one spelling, that is sufficient for our
3882 if (Uniques.size() == 1)
3883 Heading = *Uniques.begin();
3887 // If the heading is still empty, it is an error.
3888 if (Heading.empty())
3889 PrintFatalError(Attribute.getLoc(),
3890 "This attribute requires a heading to be specified");
3892 SpellingList SupportedSpellings;
3893 for (const auto &I : Spellings)
3894 SupportedSpellings.add(Attribute, I);
3896 return std::make_pair(std::move(Heading), std::move(SupportedSpellings));
3899 static void WriteDocumentation(RecordKeeper &Records,
3900 const DocumentationData &Doc, raw_ostream &OS) {
3901 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
3903 // List what spelling syntaxes the attribute supports.
3904 OS << ".. csv-table:: Supported Syntaxes\n";
3905 OS << " :header: \"GNU\", \"C++11\", \"C2x\", \"``__declspec``\",";
3906 OS << " \"Keyword\", \"``#pragma``\", \"``#pragma clang attribute``\"\n\n";
3908 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
3909 SpellingKind K = (SpellingKind)Kind;
3910 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
3912 if (K == SpellingKind::Microsoft)
3915 bool PrintedAny = false;
3916 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
3919 OS << "``" << Spelling << "``";
3926 if (getPragmaAttributeSupport(Records).isAttributedSupported(
3931 // If the attribute is deprecated, print a message about it, and possibly
3932 // provide a replacement attribute.
3933 if (!Doc.Documentation->isValueUnset("Deprecated")) {
3934 OS << "This attribute has been deprecated, and may be removed in a future "
3935 << "version of Clang.";
3936 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated");
3937 const StringRef Replacement = Deprecated.getValueAsString("Replacement");
3938 if (!Replacement.empty())
3939 OS << " This attribute has been superseded by ``" << Replacement
3944 const StringRef ContentStr = Doc.Documentation->getValueAsString("Content");
3945 // Trim leading and trailing newlines and spaces.
3946 OS << ContentStr.trim();
3951 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) {
3952 // Get the documentation introduction paragraph.
3953 const Record *Documentation = Records.getDef("GlobalDocumentation");
3954 if (!Documentation) {
3955 PrintFatalError("The Documentation top-level definition is missing, "
3956 "no documentation will be generated.");
3960 OS << Documentation->getValueAsString("Intro") << "\n";
3962 // Gather the Documentation lists from each of the attributes, based on the
3963 // category provided.
3964 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr");
3965 std::map<const Record *, std::vector<DocumentationData>> SplitDocs;
3966 for (const auto *A : Attrs) {
3967 const Record &Attr = *A;
3968 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation");
3969 for (const auto *D : Docs) {
3970 const Record &Doc = *D;
3971 const Record *Category = Doc.getValueAsDef("Category");
3972 // If the category is "undocumented", then there cannot be any other
3973 // documentation categories (otherwise, the attribute would become
3975 const StringRef Cat = Category->getValueAsString("Name");
3976 bool Undocumented = Cat == "Undocumented";
3977 if (Undocumented && Docs.size() > 1)
3978 PrintFatalError(Doc.getLoc(),
3979 "Attribute is \"Undocumented\", but has multiple "
3980 "documentation categories");
3983 SplitDocs[Category].push_back(DocumentationData(
3984 Doc, Attr, GetAttributeHeadingAndSpellings(Doc, Attr)));
3988 // Having split the attributes out based on what documentation goes where,
3989 // we can begin to generate sections of documentation.
3990 for (auto &I : SplitDocs) {
3991 WriteCategoryHeader(I.first, OS);
3993 llvm::sort(I.second,
3994 [](const DocumentationData &D1, const DocumentationData &D2) {
3995 return D1.Heading < D2.Heading;
3998 // Walk over each of the attributes in the category and write out their
4000 for (const auto &Doc : I.second)
4001 WriteDocumentation(Records, Doc, OS);
4005 void EmitTestPragmaAttributeSupportedAttributes(RecordKeeper &Records,
4007 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
4008 ParsedAttrMap Attrs = getParsedAttrList(Records);
4009 OS << "#pragma clang attribute supports the following attributes:\n";
4010 for (const auto &I : Attrs) {
4011 if (!Support.isAttributedSupported(*I.second))
4014 if (I.second->isValueUnset("Subjects")) {
4018 const Record *SubjectObj = I.second->getValueAsDef("Subjects");
4019 std::vector<Record *> Subjects =
4020 SubjectObj->getValueAsListOfDefs("Subjects");
4022 for (const auto &Subject : llvm::enumerate(Subjects)) {
4023 if (Subject.index())
4025 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
4026 Support.SubjectsToRules.find(Subject.value())->getSecond();
4027 if (RuleSet.isRule()) {
4028 OS << RuleSet.getRule().getEnumValueName();
4032 for (const auto &Rule : llvm::enumerate(RuleSet.getAggregateRuleSet())) {
4035 OS << Rule.value().getEnumValueName();
4041 OS << "End of supported attributes.\n";
4044 } // end namespace clang