1 //===-- ClangAttrEmitter.cpp - Generate Clang attribute handling ----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // These tablegen backends emit Clang attribute processing code
11 //===----------------------------------------------------------------------===//
13 #include "TableGenBackends.h"
14 #include "ASTTableGen.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/ADT/DenseMap.h"
18 #include "llvm/ADT/DenseSet.h"
19 #include "llvm/ADT/MapVector.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/SmallString.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringRef.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/ErrorHandling.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/TableGen/Error.h"
28 #include "llvm/TableGen/Record.h"
29 #include "llvm/TableGen/StringMatcher.h"
30 #include "llvm/TableGen/TableGenBackend.h"
47 class FlattenedSpelling
{
50 const Record
&OriginalSpelling
;
53 FlattenedSpelling(StringRef Variety
, StringRef Name
, StringRef Namespace
,
54 bool KnownToGCC
, const Record
&OriginalSpelling
)
55 : V(Variety
), N(Name
), NS(Namespace
), K(KnownToGCC
),
56 OriginalSpelling(OriginalSpelling
) {}
57 explicit FlattenedSpelling(const Record
&Spelling
)
58 : V(Spelling
.getValueAsString("Variety")),
59 N(Spelling
.getValueAsString("Name")), OriginalSpelling(Spelling
) {
60 assert(V
!= "GCC" && V
!= "Clang" &&
61 "Given a GCC spelling, which means this hasn't been flattened!");
62 if (V
== "CXX11" || V
== "C23" || V
== "Pragma")
63 NS
= Spelling
.getValueAsString("Namespace");
66 StringRef
variety() const { return V
; }
67 StringRef
name() const { return N
; }
68 StringRef
nameSpace() const { return NS
; }
69 bool knownToGCC() const { return K
; }
70 const Record
&getSpellingRecord() const { return OriginalSpelling
; }
73 struct FlattenedSpellingInfo
{
74 FlattenedSpellingInfo(StringRef Syntax
, StringRef Scope
,
75 const std::string
&TargetTest
, uint32_t ArgMask
)
76 : Syntax(Syntax
), Scope(Scope
), TargetTest(TargetTest
), ArgMask(ArgMask
) {
80 std::string TargetTest
;
83 using FSIVecTy
= std::vector
<FlattenedSpellingInfo
>;
85 } // end anonymous namespace
87 static bool GenerateTargetSpecificAttrChecks(const Record
*R
,
88 std::vector
<StringRef
> &Arches
,
91 static bool isStringLiteralArgument(const Record
*Arg
);
92 static bool isVariadicStringLiteralArgument(const Record
*Arg
);
94 static std::vector
<FlattenedSpelling
>
95 GetFlattenedSpellings(const Record
&Attr
) {
96 std::vector
<FlattenedSpelling
> Ret
;
98 for (const auto &Spelling
: Attr
.getValueAsListOfDefs("Spellings")) {
99 StringRef Variety
= Spelling
->getValueAsString("Variety");
100 StringRef Name
= Spelling
->getValueAsString("Name");
101 if (Variety
== "GCC") {
102 Ret
.emplace_back("GNU", Name
, "", true, *Spelling
);
103 Ret
.emplace_back("CXX11", Name
, "gnu", true, *Spelling
);
104 if (Spelling
->getValueAsBit("AllowInC"))
105 Ret
.emplace_back("C23", Name
, "gnu", true, *Spelling
);
106 } else if (Variety
== "Clang") {
107 Ret
.emplace_back("GNU", Name
, "", false, *Spelling
);
108 Ret
.emplace_back("CXX11", Name
, "clang", false, *Spelling
);
109 if (Spelling
->getValueAsBit("AllowInC"))
110 Ret
.emplace_back("C23", Name
, "clang", false, *Spelling
);
112 Ret
.push_back(FlattenedSpelling(*Spelling
));
119 static std::string
ReadPCHRecord(StringRef type
) {
120 return StringSwitch
<std::string
>(type
)
121 .EndsWith("Decl *", "Record.readDeclAs<" + type
.drop_back().str() + ">()")
122 .Case("TypeSourceInfo *", "Record.readTypeSourceInfo()")
123 .Case("Expr *", "Record.readExpr()")
124 .Case("IdentifierInfo *", "Record.readIdentifier()")
125 .Case("StringRef", "Record.readString()")
126 .Case("ParamIdx", "ParamIdx::deserialize(Record.readInt())")
127 .Case("OMPTraitInfo *", "Record.readOMPTraitInfo()")
128 .Default("Record.readInt()");
131 // Get a type that is suitable for storing an object of the specified type.
132 static StringRef
getStorageType(StringRef type
) {
133 return StringSwitch
<StringRef
>(type
)
134 .Case("StringRef", "std::string")
138 // Assumes that the way to get the value is SA->getname()
139 static std::string
WritePCHRecord(StringRef type
, StringRef name
) {
141 StringSwitch
<std::string
>(type
)
142 .EndsWith("Decl *", "AddDeclRef(" + name
.str() + ");\n")
143 .Case("TypeSourceInfo *",
144 "AddTypeSourceInfo(" + name
.str() + ");\n")
145 .Case("Expr *", "AddStmt(" + name
.str() + ");\n")
146 .Case("IdentifierInfo *",
147 "AddIdentifierRef(" + name
.str() + ");\n")
148 .Case("StringRef", "AddString(" + name
.str() + ");\n")
149 .Case("ParamIdx", "push_back(" + name
.str() + ".serialize());\n")
150 .Case("OMPTraitInfo *", "writeOMPTraitInfo(" + name
.str() + ");\n")
151 .Default("push_back(" + name
.str() + ");\n");
154 // Normalize attribute name by removing leading and trailing
155 // underscores. For example, __foo, foo__, __foo__ would
157 static StringRef
NormalizeAttrName(StringRef AttrName
) {
158 AttrName
.consume_front("__");
159 AttrName
.consume_back("__");
163 // Normalize the name by removing any and all leading and trailing underscores.
164 // This is different from NormalizeAttrName in that it also handles names like
165 // _pascal and __pascal.
166 static StringRef
NormalizeNameForSpellingComparison(StringRef Name
) {
167 return Name
.trim("_");
170 // Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
171 // removing "__" if it appears at the beginning and end of the attribute's name.
172 static StringRef
NormalizeGNUAttrSpelling(StringRef AttrSpelling
) {
173 if (AttrSpelling
.starts_with("__") && AttrSpelling
.ends_with("__")) {
174 AttrSpelling
= AttrSpelling
.substr(2, AttrSpelling
.size() - 4);
180 typedef std::vector
<std::pair
<std::string
, const Record
*>> ParsedAttrMap
;
182 static ParsedAttrMap
getParsedAttrList(const RecordKeeper
&Records
,
183 ParsedAttrMap
*Dupes
= nullptr,
184 bool SemaOnly
= true) {
185 std::set
<std::string
> Seen
;
187 for (const Record
*Attr
: Records
.getAllDerivedDefinitions("Attr")) {
188 if (!SemaOnly
|| Attr
->getValueAsBit("SemaHandler")) {
190 if (Attr
->isSubClassOf("TargetSpecificAttr") &&
191 !Attr
->isValueUnset("ParseKind")) {
192 AN
= Attr
->getValueAsString("ParseKind").str();
194 // If this attribute has already been handled, it does not need to be
196 if (!Seen
.insert(AN
).second
) {
198 Dupes
->push_back(std::make_pair(AN
, Attr
));
202 AN
= NormalizeAttrName(Attr
->getName()).str();
204 R
.push_back(std::make_pair(AN
, Attr
));
213 std::string lowerName
, upperName
;
219 Argument(StringRef Arg
, StringRef Attr
)
220 : lowerName(Arg
.str()), upperName(lowerName
), attrName(Attr
),
221 isOpt(false), Fake(false) {
222 if (!lowerName
.empty()) {
223 lowerName
[0] = std::tolower(lowerName
[0]);
224 upperName
[0] = std::toupper(upperName
[0]);
226 // Work around MinGW's macro definition of 'interface' to 'struct'. We
227 // have an attribute argument called 'Interface', so only the lower case
228 // name conflicts with the macro definition.
229 if (lowerName
== "interface")
230 lowerName
= "interface_";
232 Argument(const Record
&Arg
, StringRef Attr
)
233 : Argument(Arg
.getValueAsString("Name"), Attr
) {}
234 virtual ~Argument() = default;
236 StringRef
getLowerName() const { return lowerName
; }
237 StringRef
getUpperName() const { return upperName
; }
238 StringRef
getAttrName() const { return attrName
; }
240 bool isOptional() const { return isOpt
; }
241 void setOptional(bool set
) { isOpt
= set
; }
243 bool isFake() const { return Fake
; }
244 void setFake(bool fake
) { Fake
= fake
; }
246 // These functions print the argument contents formatted in different ways.
247 virtual void writeAccessors(raw_ostream
&OS
) const = 0;
248 virtual void writeAccessorDefinitions(raw_ostream
&OS
) const {}
249 virtual void writeASTVisitorTraversal(raw_ostream
&OS
) const {}
250 virtual void writeCloneArgs(raw_ostream
&OS
) const = 0;
251 virtual void writeTemplateInstantiationArgs(raw_ostream
&OS
) const = 0;
252 virtual void writeTemplateInstantiation(raw_ostream
&OS
) const {}
253 virtual void writeCtorBody(raw_ostream
&OS
) const {}
254 virtual void writeCtorInitializers(raw_ostream
&OS
) const = 0;
255 virtual void writeCtorDefaultInitializers(raw_ostream
&OS
) const = 0;
256 virtual void writeCtorParameters(raw_ostream
&OS
) const = 0;
257 virtual void writeDeclarations(raw_ostream
&OS
) const = 0;
258 virtual void writePCHReadArgs(raw_ostream
&OS
) const = 0;
259 virtual void writePCHReadDecls(raw_ostream
&OS
) const = 0;
260 virtual void writePCHWrite(raw_ostream
&OS
) const = 0;
261 virtual std::string
getIsOmitted() const { return "false"; }
262 virtual void writeValue(raw_ostream
&OS
) const = 0;
263 virtual void writeDump(raw_ostream
&OS
) const = 0;
264 virtual void writeDumpChildren(raw_ostream
&OS
) const {}
265 virtual void writeHasChildren(raw_ostream
&OS
) const { OS
<< "false"; }
267 virtual bool isEnumArg() const { return false; }
268 virtual bool isVariadicEnumArg() const { return false; }
269 virtual bool isVariadic() const { return false; }
271 virtual void writeImplicitCtorArgs(raw_ostream
&OS
) const {
272 OS
<< getUpperName();
276 class SimpleArgument
: public Argument
{
280 SimpleArgument(const Record
&Arg
, StringRef Attr
, std::string T
)
281 : Argument(Arg
, Attr
), type(std::move(T
)) {}
283 std::string
getType() const { return type
; }
285 void writeAccessors(raw_ostream
&OS
) const override
{
286 OS
<< " " << type
<< " get" << getUpperName() << "() const {\n";
287 OS
<< " return " << getLowerName() << ";\n";
291 void writeCloneArgs(raw_ostream
&OS
) const override
{
292 OS
<< getLowerName();
295 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
296 OS
<< "A->get" << getUpperName() << "()";
299 void writeCtorInitializers(raw_ostream
&OS
) const override
{
300 OS
<< getLowerName() << "(" << getUpperName() << ")";
303 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
304 OS
<< getLowerName() << "()";
307 void writeCtorParameters(raw_ostream
&OS
) const override
{
308 OS
<< type
<< " " << getUpperName();
311 void writeDeclarations(raw_ostream
&OS
) const override
{
312 OS
<< type
<< " " << getLowerName() << ";";
315 void writePCHReadDecls(raw_ostream
&OS
) const override
{
316 std::string read
= ReadPCHRecord(type
);
317 OS
<< " " << type
<< " " << getLowerName() << " = " << read
<< ";\n";
320 void writePCHReadArgs(raw_ostream
&OS
) const override
{
321 OS
<< getLowerName();
324 void writePCHWrite(raw_ostream
&OS
) const override
{
326 << WritePCHRecord(type
, "SA->get" + getUpperName().str() + "()");
329 std::string
getIsOmitted() const override
{
330 auto IsOneOf
= [](StringRef subject
, auto... list
) {
331 return ((subject
== list
) || ...);
334 if (IsOneOf(type
, "IdentifierInfo *", "Expr *"))
335 return "!get" + getUpperName().str() + "()";
336 if (IsOneOf(type
, "TypeSourceInfo *"))
337 return "!get" + getUpperName().str() + "Loc()";
338 if (IsOneOf(type
, "ParamIdx"))
339 return "!get" + getUpperName().str() + "().isValid()";
341 assert(IsOneOf(type
, "unsigned", "int", "bool", "FunctionDecl *",
346 void writeValue(raw_ostream
&OS
) const override
{
347 if (type
== "FunctionDecl *")
348 OS
<< "\" << get" << getUpperName()
349 << "()->getNameInfo().getAsString() << \"";
350 else if (type
== "IdentifierInfo *")
351 // Some non-optional (comma required) identifier arguments can be the
352 // empty string but are then recorded as a nullptr.
353 OS
<< "\" << (get" << getUpperName() << "() ? get" << getUpperName()
354 << "()->getName() : \"\") << \"";
355 else if (type
== "VarDecl *")
356 OS
<< "\" << get" << getUpperName() << "()->getName() << \"";
357 else if (type
== "TypeSourceInfo *")
358 OS
<< "\" << get" << getUpperName() << "().getAsString() << \"";
359 else if (type
== "ParamIdx")
360 OS
<< "\" << get" << getUpperName() << "().getSourceIndex() << \"";
362 OS
<< "\" << get" << getUpperName() << "() << \"";
365 void writeDump(raw_ostream
&OS
) const override
{
366 if (StringRef(type
).ends_with("Decl *")) {
367 OS
<< " OS << \" \";\n";
368 OS
<< " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
369 } else if (type
== "IdentifierInfo *") {
370 // Some non-optional (comma required) identifier arguments can be the
371 // empty string but are then recorded as a nullptr.
372 OS
<< " if (SA->get" << getUpperName() << "())\n"
373 << " OS << \" \" << SA->get" << getUpperName()
374 << "()->getName();\n";
375 } else if (type
== "TypeSourceInfo *") {
377 OS
<< " if (SA->get" << getUpperName() << "Loc())";
378 OS
<< " OS << \" \" << SA->get" << getUpperName()
379 << "().getAsString();\n";
380 } else if (type
== "bool") {
381 OS
<< " if (SA->get" << getUpperName() << "()) OS << \" "
382 << getUpperName() << "\";\n";
383 } else if (type
== "int" || type
== "unsigned") {
384 OS
<< " OS << \" \" << SA->get" << getUpperName() << "();\n";
385 } else if (type
== "ParamIdx") {
387 OS
<< " if (SA->get" << getUpperName() << "().isValid())\n ";
388 OS
<< " OS << \" \" << SA->get" << getUpperName()
389 << "().getSourceIndex();\n";
390 } else if (type
== "OMPTraitInfo *") {
391 OS
<< " OS << \" \" << SA->get" << getUpperName() << "();\n";
393 llvm_unreachable("Unknown SimpleArgument type!");
398 class DefaultSimpleArgument
: public SimpleArgument
{
402 DefaultSimpleArgument(const Record
&Arg
, StringRef Attr
,
403 std::string T
, int64_t Default
)
404 : SimpleArgument(Arg
, Attr
, T
), Default(Default
) {}
406 void writeAccessors(raw_ostream
&OS
) const override
{
407 SimpleArgument::writeAccessors(OS
);
409 OS
<< "\n\n static const " << getType() << " Default" << getUpperName()
411 if (getType() == "bool")
412 OS
<< (Default
!= 0 ? "true" : "false");
419 class StringArgument
: public Argument
{
421 StringArgument(const Record
&Arg
, StringRef Attr
)
422 : Argument(Arg
, Attr
)
425 void writeAccessors(raw_ostream
&OS
) const override
{
426 OS
<< " llvm::StringRef get" << getUpperName() << "() const {\n";
427 OS
<< " return llvm::StringRef(" << getLowerName() << ", "
428 << getLowerName() << "Length);\n";
430 OS
<< " unsigned get" << getUpperName() << "Length() const {\n";
431 OS
<< " return " << getLowerName() << "Length;\n";
433 OS
<< " void set" << getUpperName()
434 << "(ASTContext &C, llvm::StringRef S) {\n";
435 OS
<< " " << getLowerName() << "Length = S.size();\n";
436 OS
<< " this->" << getLowerName() << " = new (C, 1) char ["
437 << getLowerName() << "Length];\n";
438 OS
<< " if (!S.empty())\n";
439 OS
<< " std::memcpy(this->" << getLowerName() << ", S.data(), "
440 << getLowerName() << "Length);\n";
444 void writeCloneArgs(raw_ostream
&OS
) const override
{
445 OS
<< "get" << getUpperName() << "()";
448 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
449 OS
<< "A->get" << getUpperName() << "()";
452 void writeCtorBody(raw_ostream
&OS
) const override
{
453 OS
<< " if (!" << getUpperName() << ".empty())\n";
454 OS
<< " std::memcpy(" << getLowerName() << ", " << getUpperName()
455 << ".data(), " << getLowerName() << "Length);\n";
458 void writeCtorInitializers(raw_ostream
&OS
) const override
{
459 OS
<< getLowerName() << "Length(" << getUpperName() << ".size()),"
460 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
464 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
465 OS
<< getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
468 void writeCtorParameters(raw_ostream
&OS
) const override
{
469 OS
<< "llvm::StringRef " << getUpperName();
472 void writeDeclarations(raw_ostream
&OS
) const override
{
473 OS
<< "unsigned " << getLowerName() << "Length;\n";
474 OS
<< "char *" << getLowerName() << ";";
477 void writePCHReadDecls(raw_ostream
&OS
) const override
{
478 OS
<< " std::string " << getLowerName()
479 << "= Record.readString();\n";
482 void writePCHReadArgs(raw_ostream
&OS
) const override
{
483 OS
<< getLowerName();
486 void writePCHWrite(raw_ostream
&OS
) const override
{
487 OS
<< " Record.AddString(SA->get" << getUpperName() << "());\n";
490 void writeValue(raw_ostream
&OS
) const override
{
491 OS
<< "\\\"\" << get" << getUpperName() << "() << \"\\\"";
494 void writeDump(raw_ostream
&OS
) const override
{
495 OS
<< " OS << \" \\\"\" << SA->get" << getUpperName()
496 << "() << \"\\\"\";\n";
500 class AlignedArgument
: public Argument
{
502 AlignedArgument(const Record
&Arg
, StringRef Attr
)
503 : Argument(Arg
, Attr
)
506 void writeAccessors(raw_ostream
&OS
) const override
{
507 OS
<< " bool is" << getUpperName() << "Dependent() const;\n";
508 OS
<< " bool is" << getUpperName() << "ErrorDependent() const;\n";
510 OS
<< " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
512 OS
<< " bool is" << getUpperName() << "Expr() const {\n";
513 OS
<< " return is" << getLowerName() << "Expr;\n";
516 OS
<< " Expr *get" << getUpperName() << "Expr() const {\n";
517 OS
<< " assert(is" << getLowerName() << "Expr);\n";
518 OS
<< " return " << getLowerName() << "Expr;\n";
521 OS
<< " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
522 OS
<< " assert(!is" << getLowerName() << "Expr);\n";
523 OS
<< " return " << getLowerName() << "Type;\n";
526 OS
<< " std::optional<unsigned> getCached" << getUpperName()
527 << "Value() const {\n";
528 OS
<< " return " << getLowerName() << "Cache;\n";
531 OS
<< " void setCached" << getUpperName()
532 << "Value(unsigned AlignVal) {\n";
533 OS
<< " " << getLowerName() << "Cache = AlignVal;\n";
537 void writeAccessorDefinitions(raw_ostream
&OS
) const override
{
538 OS
<< "bool " << getAttrName() << "Attr::is" << getUpperName()
539 << "Dependent() const {\n";
540 OS
<< " if (is" << getLowerName() << "Expr)\n";
541 OS
<< " return " << getLowerName() << "Expr && (" << getLowerName()
542 << "Expr->isValueDependent() || " << getLowerName()
543 << "Expr->isTypeDependent());\n";
545 OS
<< " return " << getLowerName()
546 << "Type->getType()->isDependentType();\n";
549 OS
<< "bool " << getAttrName() << "Attr::is" << getUpperName()
550 << "ErrorDependent() const {\n";
551 OS
<< " if (is" << getLowerName() << "Expr)\n";
552 OS
<< " return " << getLowerName() << "Expr && " << getLowerName()
553 << "Expr->containsErrors();\n";
554 OS
<< " return " << getLowerName()
555 << "Type->getType()->containsErrors();\n";
559 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
560 StringRef Name
= getUpperName();
561 OS
<< " if (A->is" << Name
<< "Expr()) {\n"
562 << " if (!getDerived().TraverseStmt(A->get" << Name
<< "Expr()))\n"
563 << " return false;\n"
564 << " } else if (auto *TSI = A->get" << Name
<< "Type()) {\n"
565 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
566 << " return false;\n"
570 void writeCloneArgs(raw_ostream
&OS
) const override
{
571 OS
<< "is" << getLowerName() << "Expr, is" << getLowerName()
572 << "Expr ? static_cast<void*>(" << getLowerName()
573 << "Expr) : " << getLowerName()
577 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
578 // FIXME: move the definition in Sema::InstantiateAttrs to here.
579 // In the meantime, aligned attributes are cloned.
582 void writeCtorBody(raw_ostream
&OS
) const override
{
583 OS
<< " if (is" << getLowerName() << "Expr)\n";
584 OS
<< " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
585 << getUpperName() << ");\n";
587 OS
<< " " << getLowerName()
588 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
592 void writeCtorInitializers(raw_ostream
&OS
) const override
{
593 OS
<< "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
596 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
597 OS
<< "is" << getLowerName() << "Expr(false)";
600 void writeCtorParameters(raw_ostream
&OS
) const override
{
601 OS
<< "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
604 void writeImplicitCtorArgs(raw_ostream
&OS
) const override
{
605 OS
<< "Is" << getUpperName() << "Expr, " << getUpperName();
608 void writeDeclarations(raw_ostream
&OS
) const override
{
609 OS
<< "bool is" << getLowerName() << "Expr;\n";
611 OS
<< "Expr *" << getLowerName() << "Expr;\n";
612 OS
<< "TypeSourceInfo *" << getLowerName() << "Type;\n";
614 OS
<< "std::optional<unsigned> " << getLowerName() << "Cache;\n";
617 void writePCHReadArgs(raw_ostream
&OS
) const override
{
618 OS
<< "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
621 void writePCHReadDecls(raw_ostream
&OS
) const override
{
622 OS
<< " bool is" << getLowerName() << "Expr = Record.readInt();\n";
623 OS
<< " void *" << getLowerName() << "Ptr;\n";
624 OS
<< " if (is" << getLowerName() << "Expr)\n";
625 OS
<< " " << getLowerName() << "Ptr = Record.readExpr();\n";
627 OS
<< " " << getLowerName()
628 << "Ptr = Record.readTypeSourceInfo();\n";
631 void writePCHWrite(raw_ostream
&OS
) const override
{
632 OS
<< " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
633 OS
<< " if (SA->is" << getUpperName() << "Expr())\n";
634 OS
<< " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
636 OS
<< " Record.AddTypeSourceInfo(SA->get" << getUpperName()
640 std::string
getIsOmitted() const override
{
641 return "!((is" + getLowerName().str() + "Expr && " +
642 getLowerName().str() + "Expr) || (!is" + getLowerName().str() +
643 "Expr && " + getLowerName().str() + "Type))";
646 void writeValue(raw_ostream
&OS
) const override
{
648 OS
<< " if (is" << getLowerName() << "Expr && " << getLowerName()
650 OS
<< " " << getLowerName()
651 << "Expr->printPretty(OS, nullptr, Policy);\n";
652 OS
<< " if (!is" << getLowerName() << "Expr && " << getLowerName()
654 OS
<< " " << getLowerName()
655 << "Type->getType().print(OS, Policy);\n";
659 void writeDump(raw_ostream
&OS
) const override
{
660 OS
<< " if (!SA->is" << getUpperName() << "Expr())\n";
661 OS
<< " dumpType(SA->get" << getUpperName()
662 << "Type()->getType());\n";
665 void writeDumpChildren(raw_ostream
&OS
) const override
{
666 OS
<< " if (SA->is" << getUpperName() << "Expr())\n";
667 OS
<< " Visit(SA->get" << getUpperName() << "Expr());\n";
670 void writeHasChildren(raw_ostream
&OS
) const override
{
671 OS
<< "SA->is" << getUpperName() << "Expr()";
675 class VariadicArgument
: public Argument
{
676 std::string Type
, ArgName
, ArgSizeName
, RangeName
;
679 // Assumed to receive a parameter: raw_ostream OS.
680 virtual void writeValueImpl(raw_ostream
&OS
) const {
681 OS
<< " OS << Val;\n";
683 // Assumed to receive a parameter: raw_ostream OS.
684 virtual void writeDumpImpl(raw_ostream
&OS
) const {
685 OS
<< " OS << \" \" << Val;\n";
689 VariadicArgument(const Record
&Arg
, StringRef Attr
, std::string T
)
690 : Argument(Arg
, Attr
), Type(std::move(T
)),
691 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName
+ "Size"),
692 RangeName(getLowerName().str()) {}
694 VariadicArgument(StringRef Arg
, StringRef Attr
, std::string T
)
695 : Argument(Arg
, Attr
), Type(std::move(T
)),
696 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName
+ "Size"),
697 RangeName(getLowerName().str()) {}
699 const std::string
&getType() const { return Type
; }
700 const std::string
&getArgName() const { return ArgName
; }
701 const std::string
&getArgSizeName() const { return ArgSizeName
; }
702 bool isVariadic() const override
{ return true; }
704 void writeAccessors(raw_ostream
&OS
) const override
{
705 std::string IteratorType
= getLowerName().str() + "_iterator";
706 std::string BeginFn
= getLowerName().str() + "_begin()";
707 std::string EndFn
= getLowerName().str() + "_end()";
709 OS
<< " typedef " << Type
<< "* " << IteratorType
<< ";\n";
710 OS
<< " " << IteratorType
<< " " << BeginFn
<< " const {"
711 << " return " << ArgName
<< "; }\n";
712 OS
<< " " << IteratorType
<< " " << EndFn
<< " const {"
713 << " return " << ArgName
<< " + " << ArgSizeName
<< "; }\n";
714 OS
<< " unsigned " << getLowerName() << "_size() const {"
715 << " return " << ArgSizeName
<< "; }\n";
716 OS
<< " llvm::iterator_range<" << IteratorType
<< "> " << RangeName
717 << "() const { return llvm::make_range(" << BeginFn
<< ", " << EndFn
721 void writeSetter(raw_ostream
&OS
) const {
722 OS
<< " void set" << getUpperName() << "(ASTContext &Ctx, ";
723 writeCtorParameters(OS
);
725 OS
<< " " << ArgSizeName
<< " = " << getUpperName() << "Size;\n";
726 OS
<< " " << ArgName
<< " = new (Ctx, 16) " << getType() << "["
727 << ArgSizeName
<< "];\n";
733 void writeCloneArgs(raw_ostream
&OS
) const override
{
734 OS
<< ArgName
<< ", " << ArgSizeName
;
737 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
738 // This isn't elegant, but we have to go through public methods...
739 OS
<< "A->" << getLowerName() << "_begin(), "
740 << "A->" << getLowerName() << "_size()";
743 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
744 // FIXME: Traverse the elements.
747 void writeCtorBody(raw_ostream
&OS
) const override
{
748 OS
<< " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
749 << ArgSizeName
<< ", " << ArgName
<< ");\n";
752 void writeCtorInitializers(raw_ostream
&OS
) const override
{
753 OS
<< ArgSizeName
<< "(" << getUpperName() << "Size), "
754 << ArgName
<< "(new (Ctx, 16) " << getType() << "["
755 << ArgSizeName
<< "])";
758 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
759 OS
<< ArgSizeName
<< "(0), " << ArgName
<< "(nullptr)";
762 void writeCtorParameters(raw_ostream
&OS
) const override
{
763 OS
<< getType() << " *" << getUpperName() << ", unsigned "
764 << getUpperName() << "Size";
767 void writeImplicitCtorArgs(raw_ostream
&OS
) const override
{
768 OS
<< getUpperName() << ", " << getUpperName() << "Size";
771 void writeDeclarations(raw_ostream
&OS
) const override
{
772 OS
<< " unsigned " << ArgSizeName
<< ";\n";
773 OS
<< " " << getType() << " *" << ArgName
<< ";";
776 void writePCHReadDecls(raw_ostream
&OS
) const override
{
777 OS
<< " unsigned " << getLowerName() << "Size = Record.readInt();\n";
778 OS
<< " SmallVector<" << getType() << ", 4> "
779 << getLowerName() << ";\n";
780 OS
<< " " << getLowerName() << ".reserve(" << getLowerName()
783 // If we can't store the values in the current type (if it's something
784 // like StringRef), store them in a different type and convert the
785 // container afterwards.
786 std::string StorageType
= getStorageType(getType()).str();
787 std::string StorageName
= getLowerName().str();
788 if (StorageType
!= getType()) {
789 StorageName
+= "Storage";
790 OS
<< " SmallVector<" << StorageType
<< ", 4> "
791 << StorageName
<< ";\n";
792 OS
<< " " << StorageName
<< ".reserve(" << getLowerName()
796 OS
<< " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
797 std::string read
= ReadPCHRecord(Type
);
798 OS
<< " " << StorageName
<< ".push_back(" << read
<< ");\n";
800 if (StorageType
!= getType()) {
801 OS
<< " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
802 OS
<< " " << getLowerName() << ".push_back("
803 << StorageName
<< "[i]);\n";
807 void writePCHReadArgs(raw_ostream
&OS
) const override
{
808 OS
<< getLowerName() << ".data(), " << getLowerName() << "Size";
811 void writePCHWrite(raw_ostream
&OS
) const override
{
812 OS
<< " Record.push_back(SA->" << getLowerName() << "_size());\n";
813 OS
<< " for (auto &Val : SA->" << RangeName
<< "())\n";
814 OS
<< " " << WritePCHRecord(Type
, "Val");
817 void writeValue(raw_ostream
&OS
) const override
{
819 OS
<< " for (const auto &Val : " << RangeName
<< "()) {\n"
820 << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
826 void writeDump(raw_ostream
&OS
) const override
{
827 OS
<< " for (const auto &Val : SA->" << RangeName
<< "())\n";
832 class VariadicOMPInteropInfoArgument
: public VariadicArgument
{
834 VariadicOMPInteropInfoArgument(const Record
&Arg
, StringRef Attr
)
835 : VariadicArgument(Arg
, Attr
, "OMPInteropInfo") {}
837 void writeDump(raw_ostream
&OS
) const override
{
838 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
839 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
840 << getLowerName() << "_end(); I != E; ++I) {\n";
841 OS
<< " if (I->IsTarget && I->IsTargetSync)\n";
842 OS
<< " OS << \" Target_TargetSync\";\n";
843 OS
<< " else if (I->IsTarget)\n";
844 OS
<< " OS << \" Target\";\n";
846 OS
<< " OS << \" TargetSync\";\n";
850 void writePCHReadDecls(raw_ostream
&OS
) const override
{
851 OS
<< " unsigned " << getLowerName() << "Size = Record.readInt();\n";
852 OS
<< " SmallVector<OMPInteropInfo, 4> " << getLowerName() << ";\n";
853 OS
<< " " << getLowerName() << ".reserve(" << getLowerName()
855 OS
<< " for (unsigned I = 0, E = " << getLowerName() << "Size; ";
856 OS
<< "I != E; ++I) {\n";
857 OS
<< " bool IsTarget = Record.readBool();\n";
858 OS
<< " bool IsTargetSync = Record.readBool();\n";
859 OS
<< " " << getLowerName()
860 << ".emplace_back(IsTarget, IsTargetSync);\n";
864 void writePCHWrite(raw_ostream
&OS
) const override
{
865 OS
<< " Record.push_back(SA->" << getLowerName() << "_size());\n";
866 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
867 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
868 << getLowerName() << "_end(); I != E; ++I) {\n";
869 OS
<< " Record.writeBool(I->IsTarget);\n";
870 OS
<< " Record.writeBool(I->IsTargetSync);\n";
875 class VariadicParamIdxArgument
: public VariadicArgument
{
877 VariadicParamIdxArgument(const Record
&Arg
, StringRef Attr
)
878 : VariadicArgument(Arg
, Attr
, "ParamIdx") {}
881 void writeValueImpl(raw_ostream
&OS
) const override
{
882 OS
<< " OS << Val.getSourceIndex();\n";
885 void writeDumpImpl(raw_ostream
&OS
) const override
{
886 OS
<< " OS << \" \" << Val.getSourceIndex();\n";
890 struct VariadicParamOrParamIdxArgument
: public VariadicArgument
{
891 VariadicParamOrParamIdxArgument(const Record
&Arg
, StringRef Attr
)
892 : VariadicArgument(Arg
, Attr
, "int") {}
895 // Unique the enums, but maintain the original declaration ordering.
896 std::vector
<StringRef
>
897 uniqueEnumsInOrder(const std::vector
<StringRef
> &enums
) {
898 std::vector
<StringRef
> uniques
;
899 SmallDenseSet
<StringRef
, 8> unique_set
;
900 for (const auto &i
: enums
) {
901 if (unique_set
.insert(i
).second
)
902 uniques
.push_back(i
);
907 class EnumArgument
: public Argument
{
908 std::string fullType
;
910 std::vector
<StringRef
> values
, enums
, uniques
;
915 EnumArgument(const Record
&Arg
, StringRef Attr
)
916 : Argument(Arg
, Attr
), values(Arg
.getValueAsListOfStrings("Values")),
917 enums(Arg
.getValueAsListOfStrings("Enums")),
918 uniques(uniqueEnumsInOrder(enums
)),
919 isExternal(Arg
.getValueAsBit("IsExternalType")),
920 isCovered(Arg
.getValueAsBit("IsCovered")) {
921 StringRef Type
= Arg
.getValueAsString("Type");
922 shortType
= isExternal
? Type
.rsplit("::").second
: Type
;
923 // If shortType didn't contain :: at all rsplit will give us an empty
925 if (shortType
.empty())
927 fullType
= isExternal
? Type
: (getAttrName() + "Attr::" + Type
).str();
929 // FIXME: Emit a proper error
930 assert(!uniques
.empty());
933 bool isEnumArg() const override
{ return true; }
935 void writeAccessors(raw_ostream
&OS
) const override
{
936 OS
<< " " << fullType
<< " get" << getUpperName() << "() const {\n";
937 OS
<< " return " << getLowerName() << ";\n";
941 void writeCloneArgs(raw_ostream
&OS
) const override
{
942 OS
<< getLowerName();
945 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
946 OS
<< "A->get" << getUpperName() << "()";
948 void writeCtorInitializers(raw_ostream
&OS
) const override
{
949 OS
<< getLowerName() << "(" << getUpperName() << ")";
951 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
952 OS
<< getLowerName() << "(" << fullType
<< "(0))";
954 void writeCtorParameters(raw_ostream
&OS
) const override
{
955 OS
<< fullType
<< " " << getUpperName();
957 void writeDeclarations(raw_ostream
&OS
) const override
{
959 auto i
= uniques
.cbegin(), e
= uniques
.cend();
960 // The last one needs to not have a comma.
964 OS
<< " enum " << shortType
<< " {\n";
966 OS
<< " " << *i
<< ",\n";
967 OS
<< " " << *e
<< "\n";
972 OS
<< " " << fullType
<< " " << getLowerName() << ";";
975 void writePCHReadDecls(raw_ostream
&OS
) const override
{
976 OS
<< " " << fullType
<< " " << getLowerName() << "(static_cast<"
977 << fullType
<< ">(Record.readInt()));\n";
980 void writePCHReadArgs(raw_ostream
&OS
) const override
{
981 OS
<< getLowerName();
984 void writePCHWrite(raw_ostream
&OS
) const override
{
985 OS
<< "Record.push_back(static_cast<uint64_t>(SA->get" << getUpperName()
989 void writeValue(raw_ostream
&OS
) const override
{
990 // FIXME: this isn't 100% correct -- some enum arguments require printing
991 // as a string literal, while others require printing as an identifier.
992 // Tablegen currently does not distinguish between the two forms.
993 OS
<< "\\\"\" << " << getAttrName() << "Attr::Convert" << shortType
994 << "ToStr(get" << getUpperName() << "()) << \"\\\"";
997 void writeDump(raw_ostream
&OS
) const override
{
998 OS
<< " switch(SA->get" << getUpperName() << "()) {\n";
999 for (const auto &I
: uniques
) {
1000 OS
<< " case " << fullType
<< "::" << I
<< ":\n";
1001 OS
<< " OS << \" " << I
<< "\";\n";
1005 OS
<< " default:\n";
1006 OS
<< " llvm_unreachable(\"Invalid attribute value\");\n";
1011 void writeConversion(raw_ostream
&OS
, bool Header
) const {
1013 OS
<< " static bool ConvertStrTo" << shortType
<< "(StringRef Val, "
1014 << fullType
<< " &Out);\n";
1015 OS
<< " static const char *Convert" << shortType
<< "ToStr("
1016 << fullType
<< " Val);\n";
1020 OS
<< "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1021 << "(StringRef Val, " << fullType
<< " &Out) {\n";
1022 OS
<< " std::optional<" << fullType
<< "> "
1023 << "R = llvm::StringSwitch<std::optional<" << fullType
<< ">>(Val)\n";
1024 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1025 OS
<< " .Case(\"" << values
[I
] << "\", ";
1026 OS
<< fullType
<< "::" << enums
[I
] << ")\n";
1028 OS
<< " .Default(std::optional<" << fullType
<< ">());\n";
1029 OS
<< " if (R) {\n";
1030 OS
<< " Out = *R;\n return true;\n }\n";
1031 OS
<< " return false;\n";
1034 // Mapping from enumeration values back to enumeration strings isn't
1035 // trivial because some enumeration values have multiple named
1036 // enumerators, such as type_visibility(internal) and
1037 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
1038 OS
<< "const char *" << getAttrName() << "Attr::Convert" << shortType
1039 << "ToStr(" << fullType
<< " Val) {\n"
1040 << " switch(Val) {\n";
1041 SmallDenseSet
<StringRef
, 8> Uniques
;
1042 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1043 if (Uniques
.insert(enums
[I
]).second
)
1044 OS
<< " case " << fullType
<< "::" << enums
[I
] << ": return \""
1045 << values
[I
] << "\";\n";
1048 OS
<< " default: llvm_unreachable(\"Invalid attribute value\");\n";
1051 << " llvm_unreachable(\"No enumerator with that value\");\n"
1056 class VariadicEnumArgument
: public VariadicArgument
{
1057 std::string fullType
;
1058 StringRef shortType
;
1059 std::vector
<StringRef
> values
, enums
, uniques
;
1064 void writeValueImpl(raw_ostream
&OS
) const override
{
1065 // FIXME: this isn't 100% correct -- some enum arguments require printing
1066 // as a string literal, while others require printing as an identifier.
1067 // Tablegen currently does not distinguish between the two forms.
1068 OS
<< " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert"
1069 << shortType
<< "ToStr(Val)"
1070 << "<< \"\\\"\";\n";
1074 VariadicEnumArgument(const Record
&Arg
, StringRef Attr
)
1075 : VariadicArgument(Arg
, Attr
, Arg
.getValueAsString("Type").str()),
1076 values(Arg
.getValueAsListOfStrings("Values")),
1077 enums(Arg
.getValueAsListOfStrings("Enums")),
1078 uniques(uniqueEnumsInOrder(enums
)),
1079 isExternal(Arg
.getValueAsBit("IsExternalType")),
1080 isCovered(Arg
.getValueAsBit("IsCovered")) {
1081 StringRef Type
= Arg
.getValueAsString("Type");
1082 shortType
= isExternal
? Type
.rsplit("::").second
: Type
;
1083 // If shortType didn't contain :: at all rsplit will give us an empty
1085 if (shortType
.empty())
1087 fullType
= isExternal
? Type
: (getAttrName() + "Attr::" + Type
).str();
1089 // FIXME: Emit a proper error
1090 assert(!uniques
.empty());
1093 bool isVariadicEnumArg() const override
{ return true; }
1095 void writeDeclarations(raw_ostream
&OS
) const override
{
1097 auto i
= uniques
.cbegin(), e
= uniques
.cend();
1098 // The last one needs to not have a comma.
1102 OS
<< " enum " << shortType
<< " {\n";
1104 OS
<< " " << *i
<< ",\n";
1105 OS
<< " " << *e
<< "\n";
1110 VariadicArgument::writeDeclarations(OS
);
1113 void writeDump(raw_ostream
&OS
) const override
{
1114 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
1115 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1116 << getLowerName() << "_end(); I != E; ++I) {\n";
1117 OS
<< " switch(*I) {\n";
1118 for (const auto &UI
: uniques
) {
1119 OS
<< " case " << fullType
<< "::" << UI
<< ":\n";
1120 OS
<< " OS << \" " << UI
<< "\";\n";
1124 OS
<< " default:\n";
1125 OS
<< " llvm_unreachable(\"Invalid attribute value\");\n";
1131 void writePCHReadDecls(raw_ostream
&OS
) const override
{
1132 OS
<< " unsigned " << getLowerName() << "Size = Record.readInt();\n";
1133 OS
<< " SmallVector<" << fullType
<< ", 4> " << getLowerName()
1135 OS
<< " " << getLowerName() << ".reserve(" << getLowerName()
1137 OS
<< " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1138 OS
<< " " << getLowerName() << ".push_back("
1139 << "static_cast<" << fullType
<< ">(Record.readInt()));\n";
1142 void writePCHWrite(raw_ostream
&OS
) const override
{
1143 OS
<< " Record.push_back(SA->" << getLowerName() << "_size());\n";
1144 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
1145 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1146 << getLowerName() << "_end(); i != e; ++i)\n";
1147 OS
<< " " << WritePCHRecord(fullType
, "(*i)");
1150 void writeConversion(raw_ostream
&OS
, bool Header
) const {
1152 OS
<< " static bool ConvertStrTo" << shortType
<< "(StringRef Val, "
1153 << fullType
<< " &Out);\n";
1154 OS
<< " static const char *Convert" << shortType
<< "ToStr("
1155 << fullType
<< " Val);\n";
1159 OS
<< "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1160 << "(StringRef Val, ";
1161 OS
<< fullType
<< " &Out) {\n";
1162 OS
<< " std::optional<" << fullType
1163 << "> R = llvm::StringSwitch<std::optional<";
1164 OS
<< fullType
<< ">>(Val)\n";
1165 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1166 OS
<< " .Case(\"" << values
[I
] << "\", ";
1167 OS
<< fullType
<< "::" << enums
[I
] << ")\n";
1169 OS
<< " .Default(std::optional<" << fullType
<< ">());\n";
1170 OS
<< " if (R) {\n";
1171 OS
<< " Out = *R;\n return true;\n }\n";
1172 OS
<< " return false;\n";
1175 OS
<< "const char *" << getAttrName() << "Attr::Convert" << shortType
1176 << "ToStr(" << fullType
<< " Val) {\n"
1177 << " switch(Val) {\n";
1178 SmallDenseSet
<StringRef
, 8> Uniques
;
1179 for (size_t I
= 0; I
< enums
.size(); ++I
) {
1180 if (Uniques
.insert(enums
[I
]).second
)
1181 OS
<< " case " << fullType
<< "::" << enums
[I
] << ": return \""
1182 << values
[I
] << "\";\n";
1185 OS
<< " default: llvm_unreachable(\"Invalid attribute value\");\n";
1188 << " llvm_unreachable(\"No enumerator with that value\");\n"
1193 class VersionArgument
: public Argument
{
1195 VersionArgument(const Record
&Arg
, StringRef Attr
)
1196 : Argument(Arg
, Attr
)
1199 void writeAccessors(raw_ostream
&OS
) const override
{
1200 OS
<< " VersionTuple get" << getUpperName() << "() const {\n";
1201 OS
<< " return " << getLowerName() << ";\n";
1203 OS
<< " void set" << getUpperName()
1204 << "(ASTContext &C, VersionTuple V) {\n";
1205 OS
<< " " << getLowerName() << " = V;\n";
1209 void writeCloneArgs(raw_ostream
&OS
) const override
{
1210 OS
<< "get" << getUpperName() << "()";
1213 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1214 OS
<< "A->get" << getUpperName() << "()";
1217 void writeCtorInitializers(raw_ostream
&OS
) const override
{
1218 OS
<< getLowerName() << "(" << getUpperName() << ")";
1221 void writeCtorDefaultInitializers(raw_ostream
&OS
) const override
{
1222 OS
<< getLowerName() << "()";
1225 void writeCtorParameters(raw_ostream
&OS
) const override
{
1226 OS
<< "VersionTuple " << getUpperName();
1229 void writeDeclarations(raw_ostream
&OS
) const override
{
1230 OS
<< "VersionTuple " << getLowerName() << ";\n";
1233 void writePCHReadDecls(raw_ostream
&OS
) const override
{
1234 OS
<< " VersionTuple " << getLowerName()
1235 << "= Record.readVersionTuple();\n";
1238 void writePCHReadArgs(raw_ostream
&OS
) const override
{
1239 OS
<< getLowerName();
1242 void writePCHWrite(raw_ostream
&OS
) const override
{
1243 OS
<< " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1246 void writeValue(raw_ostream
&OS
) const override
{
1247 OS
<< getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1250 void writeDump(raw_ostream
&OS
) const override
{
1251 OS
<< " OS << \" \" << SA->get" << getUpperName() << "();\n";
1255 class ExprArgument
: public SimpleArgument
{
1257 ExprArgument(const Record
&Arg
, StringRef Attr
)
1258 : SimpleArgument(Arg
, Attr
, "Expr *")
1261 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
1263 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1264 OS
<< " return false;\n";
1267 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1268 OS
<< "tempInst" << getUpperName();
1271 void writeTemplateInstantiation(raw_ostream
&OS
) const override
{
1272 OS
<< " " << getType() << " tempInst" << getUpperName() << ";\n";
1274 OS
<< " EnterExpressionEvaluationContext "
1275 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1276 OS
<< " ExprResult " << "Result = S.SubstExpr("
1277 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1278 OS
<< " if (Result.isInvalid())\n";
1279 OS
<< " return nullptr;\n";
1280 OS
<< " tempInst" << getUpperName() << " = Result.get();\n";
1284 void writeValue(raw_ostream
&OS
) const override
{
1286 OS
<< " get" << getUpperName()
1287 << "()->printPretty(OS, nullptr, Policy);\n";
1291 void writeDump(raw_ostream
&OS
) const override
{}
1293 void writeDumpChildren(raw_ostream
&OS
) const override
{
1294 OS
<< " Visit(SA->get" << getUpperName() << "());\n";
1297 void writeHasChildren(raw_ostream
&OS
) const override
{ OS
<< "true"; }
1300 class VariadicExprArgument
: public VariadicArgument
{
1302 VariadicExprArgument(const Record
&Arg
, StringRef Attr
)
1303 : VariadicArgument(Arg
, Attr
, "Expr *")
1306 VariadicExprArgument(StringRef ArgName
, StringRef Attr
)
1307 : VariadicArgument(ArgName
, Attr
, "Expr *") {}
1309 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
1311 OS
<< " " << getType() << " *I = A->" << getLowerName()
1313 OS
<< " " << getType() << " *E = A->" << getLowerName()
1315 OS
<< " for (; I != E; ++I) {\n";
1316 OS
<< " if (!getDerived().TraverseStmt(*I))\n";
1317 OS
<< " return false;\n";
1322 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1323 OS
<< "tempInst" << getUpperName() << ", "
1324 << "A->" << getLowerName() << "_size()";
1327 void writeTemplateInstantiation(raw_ostream
&OS
) const override
{
1328 OS
<< " auto *tempInst" << getUpperName()
1329 << " = new (C, 16) " << getType()
1330 << "[A->" << getLowerName() << "_size()];\n";
1332 OS
<< " EnterExpressionEvaluationContext "
1333 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1334 OS
<< " " << getType() << " *TI = tempInst" << getUpperName()
1336 OS
<< " " << getType() << " *I = A->" << getLowerName()
1338 OS
<< " " << getType() << " *E = A->" << getLowerName()
1340 OS
<< " for (; I != E; ++I, ++TI) {\n";
1341 OS
<< " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n";
1342 OS
<< " if (Result.isInvalid())\n";
1343 OS
<< " return nullptr;\n";
1344 OS
<< " *TI = Result.get();\n";
1349 void writeDump(raw_ostream
&OS
) const override
{}
1351 void writeDumpChildren(raw_ostream
&OS
) const override
{
1352 OS
<< " for (" << getAttrName() << "Attr::" << getLowerName()
1353 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1354 << getLowerName() << "_end(); I != E; ++I)\n";
1355 OS
<< " Visit(*I);\n";
1358 void writeHasChildren(raw_ostream
&OS
) const override
{
1359 OS
<< "SA->" << getLowerName() << "_begin() != "
1360 << "SA->" << getLowerName() << "_end()";
1364 class VariadicIdentifierArgument
: public VariadicArgument
{
1366 VariadicIdentifierArgument(const Record
&Arg
, StringRef Attr
)
1367 : VariadicArgument(Arg
, Attr
, "IdentifierInfo *")
1371 class VariadicStringArgument
: public VariadicArgument
{
1373 VariadicStringArgument(const Record
&Arg
, StringRef Attr
)
1374 : VariadicArgument(Arg
, Attr
, "StringRef")
1377 void writeCtorBody(raw_ostream
&OS
) const override
{
1378 OS
<< " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1380 " StringRef Ref = " << getUpperName() << "[I];\n"
1381 " if (!Ref.empty()) {\n"
1382 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1383 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1384 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1389 void writeValueImpl(raw_ostream
&OS
) const override
{
1390 OS
<< " OS << \"\\\"\" << Val << \"\\\"\";\n";
1394 class TypeArgument
: public SimpleArgument
{
1396 TypeArgument(const Record
&Arg
, StringRef Attr
)
1397 : SimpleArgument(Arg
, Attr
, "TypeSourceInfo *")
1400 void writeAccessors(raw_ostream
&OS
) const override
{
1401 OS
<< " QualType get" << getUpperName() << "() const {\n";
1402 OS
<< " return " << getLowerName() << "->getType();\n";
1404 OS
<< " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1405 OS
<< " return " << getLowerName() << ";\n";
1409 void writeASTVisitorTraversal(raw_ostream
&OS
) const override
{
1410 OS
<< " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1411 OS
<< " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1412 OS
<< " return false;\n";
1415 void writeTemplateInstantiation(raw_ostream
&OS
) const override
{
1416 OS
<< " " << getType() << " tempInst" << getUpperName() << " =\n";
1417 OS
<< " S.SubstType(A->get" << getUpperName() << "Loc(), "
1418 << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
1419 OS
<< " if (!tempInst" << getUpperName() << ")\n";
1420 OS
<< " return nullptr;\n";
1423 void writeTemplateInstantiationArgs(raw_ostream
&OS
) const override
{
1424 OS
<< "tempInst" << getUpperName();
1427 void writePCHWrite(raw_ostream
&OS
) const override
{
1429 << WritePCHRecord(getType(),
1430 "SA->get" + getUpperName().str() + "Loc()");
1434 class WrappedAttr
: public SimpleArgument
{
1436 WrappedAttr(const Record
&Arg
, StringRef Attr
)
1437 : SimpleArgument(Arg
, Attr
, "Attr *") {}
1439 void writePCHReadDecls(raw_ostream
&OS
) const override
{
1440 OS
<< " Attr *" << getLowerName() << " = Record.readAttr();";
1443 void writePCHWrite(raw_ostream
&OS
) const override
{
1444 OS
<< " AddAttr(SA->get" << getUpperName() << "());";
1447 void writeDump(raw_ostream
&OS
) const override
{}
1449 void writeDumpChildren(raw_ostream
&OS
) const override
{
1450 OS
<< " Visit(SA->get" << getUpperName() << "());\n";
1453 void writeHasChildren(raw_ostream
&OS
) const override
{ OS
<< "true"; }
1456 } // end anonymous namespace
1458 static std::unique_ptr
<Argument
>
1459 createArgument(const Record
&Arg
, StringRef Attr
,
1460 const Record
*Search
= nullptr) {
1464 std::unique_ptr
<Argument
> Ptr
;
1465 StringRef ArgName
= Search
->getName();
1467 if (ArgName
== "AlignedArgument")
1468 Ptr
= std::make_unique
<AlignedArgument
>(Arg
, Attr
);
1469 else if (ArgName
== "EnumArgument")
1470 Ptr
= std::make_unique
<EnumArgument
>(Arg
, Attr
);
1471 else if (ArgName
== "ExprArgument")
1472 Ptr
= std::make_unique
<ExprArgument
>(Arg
, Attr
);
1473 else if (ArgName
== "DeclArgument")
1474 Ptr
= std::make_unique
<SimpleArgument
>(
1475 Arg
, Attr
, (Arg
.getValueAsDef("Kind")->getName() + "Decl *").str());
1476 else if (ArgName
== "IdentifierArgument")
1477 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "IdentifierInfo *");
1478 else if (ArgName
== "DefaultBoolArgument")
1479 Ptr
= std::make_unique
<DefaultSimpleArgument
>(
1480 Arg
, Attr
, "bool", Arg
.getValueAsBit("Default"));
1481 else if (ArgName
== "BoolArgument")
1482 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "bool");
1483 else if (ArgName
== "DefaultIntArgument")
1484 Ptr
= std::make_unique
<DefaultSimpleArgument
>(
1485 Arg
, Attr
, "int", Arg
.getValueAsInt("Default"));
1486 else if (ArgName
== "IntArgument")
1487 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "int");
1488 else if (ArgName
== "StringArgument")
1489 Ptr
= std::make_unique
<StringArgument
>(Arg
, Attr
);
1490 else if (ArgName
== "TypeArgument")
1491 Ptr
= std::make_unique
<TypeArgument
>(Arg
, Attr
);
1492 else if (ArgName
== "UnsignedArgument")
1493 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "unsigned");
1494 else if (ArgName
== "VariadicUnsignedArgument")
1495 Ptr
= std::make_unique
<VariadicArgument
>(Arg
, Attr
, "unsigned");
1496 else if (ArgName
== "VariadicStringArgument")
1497 Ptr
= std::make_unique
<VariadicStringArgument
>(Arg
, Attr
);
1498 else if (ArgName
== "VariadicEnumArgument")
1499 Ptr
= std::make_unique
<VariadicEnumArgument
>(Arg
, Attr
);
1500 else if (ArgName
== "VariadicExprArgument")
1501 Ptr
= std::make_unique
<VariadicExprArgument
>(Arg
, Attr
);
1502 else if (ArgName
== "VariadicParamIdxArgument")
1503 Ptr
= std::make_unique
<VariadicParamIdxArgument
>(Arg
, Attr
);
1504 else if (ArgName
== "VariadicParamOrParamIdxArgument")
1505 Ptr
= std::make_unique
<VariadicParamOrParamIdxArgument
>(Arg
, Attr
);
1506 else if (ArgName
== "ParamIdxArgument")
1507 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "ParamIdx");
1508 else if (ArgName
== "VariadicIdentifierArgument")
1509 Ptr
= std::make_unique
<VariadicIdentifierArgument
>(Arg
, Attr
);
1510 else if (ArgName
== "VersionArgument")
1511 Ptr
= std::make_unique
<VersionArgument
>(Arg
, Attr
);
1512 else if (ArgName
== "WrappedAttr")
1513 Ptr
= std::make_unique
<WrappedAttr
>(Arg
, Attr
);
1514 else if (ArgName
== "OMPTraitInfoArgument")
1515 Ptr
= std::make_unique
<SimpleArgument
>(Arg
, Attr
, "OMPTraitInfo *");
1516 else if (ArgName
== "VariadicOMPInteropInfoArgument")
1517 Ptr
= std::make_unique
<VariadicOMPInteropInfoArgument
>(Arg
, Attr
);
1520 // Search in reverse order so that the most-derived type is handled first.
1521 for (const auto &[Base
, _
] : reverse(Search
->getSuperClasses())) {
1522 if ((Ptr
= createArgument(Arg
, Attr
, Base
)))
1527 if (Ptr
&& Arg
.getValueAsBit("Optional"))
1528 Ptr
->setOptional(true);
1530 if (Ptr
&& Arg
.getValueAsBit("Fake"))
1536 static void writeAvailabilityValue(raw_ostream
&OS
) {
1537 OS
<< "\" << getPlatform()->getName();\n"
1538 << " if (getStrict()) OS << \", strict\";\n"
1539 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1540 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1541 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1542 << " if (getUnavailable()) OS << \", unavailable\";\n"
1546 static void writeDeprecatedAttrValue(raw_ostream
&OS
, StringRef Variety
) {
1547 OS
<< "\\\"\" << getMessage() << \"\\\"\";\n";
1548 // Only GNU deprecated has an optional fixit argument at the second position.
1549 if (Variety
== "GNU")
1550 OS
<< " if (!getReplacement().empty()) OS << \", \\\"\""
1551 " << getReplacement() << \"\\\"\";\n";
1555 static void writeGetSpellingFunction(const Record
&R
, raw_ostream
&OS
) {
1556 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
1558 OS
<< "const char *" << R
.getName() << "Attr::getSpelling() const {\n";
1559 if (Spellings
.empty()) {
1560 OS
<< " return \"(No spelling)\";\n}\n\n";
1564 OS
<< " switch (getAttributeSpellingListIndex()) {\n"
1566 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1567 " return \"(No spelling)\";\n";
1569 for (const auto &[Idx
, S
] : enumerate(Spellings
)) {
1571 OS
<< " case " << Idx
<< ":\n"
1572 " return \"" << S
.name() << "\";\n";
1575 // End of the switch statement.
1577 // End of the getSpelling function.
1582 writePrettyPrintFunction(const Record
&R
,
1583 const std::vector
<std::unique_ptr
<Argument
>> &Args
,
1585 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
1587 OS
<< "void " << R
.getName() << "Attr::printPretty("
1588 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1590 if (Spellings
.empty()) {
1595 OS
<< " bool IsFirstArgument = true; (void)IsFirstArgument;\n"
1596 << " unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
1597 << " switch (getAttributeSpellingListIndex()) {\n"
1599 << " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1602 for (const auto &[Idx
, S
] : enumerate(Spellings
)) {
1603 SmallString
<16> Prefix
;
1604 SmallString
<8> Suffix
;
1605 // The actual spelling of the name and namespace (if applicable)
1606 // of an attribute without considering prefix and suffix.
1607 SmallString
<64> Spelling
;
1608 StringRef Name
= S
.name();
1609 StringRef Variety
= S
.variety();
1611 if (Variety
== "GNU") {
1612 Prefix
= "__attribute__((";
1614 } else if (Variety
== "CXX11" || Variety
== "C23") {
1617 StringRef Namespace
= S
.nameSpace();
1618 if (!Namespace
.empty()) {
1619 Spelling
+= Namespace
;
1622 } else if (Variety
== "Declspec") {
1623 Prefix
= "__declspec(";
1625 } else if (Variety
== "Microsoft") {
1628 } else if (Variety
== "Keyword") {
1631 } else if (Variety
== "Pragma") {
1632 Prefix
= "#pragma ";
1634 StringRef Namespace
= S
.nameSpace();
1635 if (!Namespace
.empty()) {
1636 Spelling
+= Namespace
;
1639 } else if (Variety
== "HLSLAnnotation") {
1643 llvm_unreachable("Unknown attribute syntax variety!");
1648 OS
<< " case " << Idx
<< " : {\n"
1649 << " OS << \"" << Prefix
<< Spelling
<< "\";\n";
1651 if (Variety
== "Pragma") {
1652 OS
<< " printPrettyPragma(OS, Policy);\n";
1653 OS
<< " OS << \"\\n\";";
1659 if (Spelling
== "availability") {
1661 writeAvailabilityValue(OS
);
1663 } else if (Spelling
== "deprecated" || Spelling
== "gnu::deprecated") {
1665 writeDeprecatedAttrValue(OS
, Variety
);
1668 // To avoid printing parentheses around an empty argument list or
1669 // printing spurious commas at the end of an argument list, we need to
1670 // determine where the last provided non-fake argument is.
1671 bool FoundNonOptArg
= false;
1672 for (const auto &arg
: reverse(Args
)) {
1677 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1678 // any way to detect whether the argument was omitted.
1679 if (!arg
->isOptional() || arg
->getIsOmitted() == "false") {
1680 FoundNonOptArg
= true;
1683 OS
<< " if (" << arg
->getIsOmitted() << ")\n"
1684 << " ++TrailingOmittedArgs;\n";
1686 unsigned ArgIndex
= 0;
1687 for (const auto &arg
: Args
) {
1690 std::string IsOmitted
= arg
->getIsOmitted();
1691 if (arg
->isOptional() && IsOmitted
!= "false")
1692 OS
<< " if (!(" << IsOmitted
<< ")) {\n";
1693 // Variadic arguments print their own leading comma.
1694 if (!arg
->isVariadic())
1695 OS
<< " DelimitAttributeArgument(OS, IsFirstArgument);\n";
1697 arg
->writeValue(OS
);
1699 if (arg
->isOptional() && IsOmitted
!= "false")
1704 OS
<< " if (!IsFirstArgument)\n"
1705 << " OS << \")\";\n";
1707 OS
<< " OS << \"" << Suffix
<< "\";\n"
1712 // End of the switch statement.
1714 // End of the print function.
1718 /// Return the index of a spelling in a spelling list.
1719 static unsigned getSpellingListIndex(ArrayRef
<FlattenedSpelling
> SpellingList
,
1720 const FlattenedSpelling
&Spelling
) {
1721 assert(!SpellingList
.empty() && "Spelling list is empty!");
1723 for (const auto &[Index
, S
] : enumerate(SpellingList
)) {
1724 if (S
.variety() == Spelling
.variety() &&
1725 S
.nameSpace() == Spelling
.nameSpace() && S
.name() == Spelling
.name())
1729 PrintFatalError("Unknown spelling: " + Spelling
.name());
1732 static void writeAttrAccessorDefinition(const Record
&R
, raw_ostream
&OS
) {
1733 std::vector
<const Record
*> Accessors
= R
.getValueAsListOfDefs("Accessors");
1734 if (Accessors
.empty())
1737 const std::vector
<FlattenedSpelling
> SpellingList
= GetFlattenedSpellings(R
);
1738 assert(!SpellingList
.empty() &&
1739 "Attribute with empty spelling list can't have accessors!");
1740 for (const auto *Accessor
: Accessors
) {
1741 const StringRef Name
= Accessor
->getValueAsString("Name");
1742 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(*Accessor
);
1744 OS
<< " bool " << Name
1745 << "() const { return getAttributeSpellingListIndex() == ";
1746 for (unsigned Index
= 0; Index
< Spellings
.size(); ++Index
) {
1747 OS
<< getSpellingListIndex(SpellingList
, Spellings
[Index
]);
1748 if (Index
!= Spellings
.size() - 1)
1749 OS
<< " ||\n getAttributeSpellingListIndex() == ";
1757 SpellingNamesAreCommon(const std::vector
<FlattenedSpelling
>& Spellings
) {
1758 assert(!Spellings
.empty() && "An empty list of spellings was provided");
1759 StringRef FirstName
=
1760 NormalizeNameForSpellingComparison(Spellings
.front().name());
1761 for (const auto &Spelling
: drop_begin(Spellings
)) {
1762 StringRef Name
= NormalizeNameForSpellingComparison(Spelling
.name());
1763 if (Name
!= FirstName
)
1769 typedef std::map
<unsigned, std::string
> SemanticSpellingMap
;
1771 CreateSemanticSpellings(const std::vector
<FlattenedSpelling
> &Spellings
,
1772 SemanticSpellingMap
&Map
) {
1773 // The enumerants are automatically generated based on the variety,
1774 // namespace (if present) and name for each attribute spelling. However,
1775 // care is taken to avoid trampling on the reserved namespace due to
1777 std::string
Ret(" enum Spelling {\n");
1778 std::set
<std::string
> Uniques
;
1781 // If we have a need to have this many spellings we likely need to add an
1782 // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1783 // value of SpellingNotCalculated there and here.
1784 assert(Spellings
.size() < 15 &&
1785 "Too many spellings, would step on SpellingNotCalculated in "
1786 "AttributeCommonInfo");
1787 for (auto I
= Spellings
.begin(), E
= Spellings
.end(); I
!= E
; ++I
, ++Idx
) {
1788 const FlattenedSpelling
&S
= *I
;
1789 StringRef Variety
= S
.variety();
1790 StringRef Spelling
= S
.name();
1791 StringRef Namespace
= S
.nameSpace();
1792 std::string EnumName
;
1794 EnumName
+= Variety
;
1796 if (!Namespace
.empty())
1797 EnumName
+= NormalizeNameForSpellingComparison(Namespace
).str() + "_";
1798 EnumName
+= NormalizeNameForSpellingComparison(Spelling
);
1800 // Even if the name is not unique, this spelling index corresponds to a
1801 // particular enumerant name that we've calculated.
1802 Map
[Idx
] = EnumName
;
1804 // Since we have been stripping underscores to avoid trampling on the
1805 // reserved namespace, we may have inadvertently created duplicate
1806 // enumerant names. These duplicates are not considered part of the
1807 // semantic spelling, and can be elided.
1808 if (!Uniques
.insert(EnumName
).second
)
1811 if (I
!= Spellings
.begin())
1813 // Duplicate spellings are not considered part of the semantic spelling
1814 // enumeration, but the spelling index and semantic spelling values are
1815 // meant to be equivalent, so we must specify a concrete value for each
1817 Ret
+= " " + EnumName
+ " = " + utostr(Idx
);
1819 Ret
+= ",\n SpellingNotCalculated = 15\n";
1824 static void WriteSemanticSpellingSwitch(StringRef VarName
,
1825 const SemanticSpellingMap
&Map
,
1827 OS
<< " switch (" << VarName
<< ") {\n default: "
1828 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1829 for (const auto &I
: Map
)
1830 OS
<< " case " << I
.first
<< ": return " << I
.second
<< ";\n";
1834 // Note: these values need to match the values used by LateAttrParseKind in
1836 enum class LateAttrParseKind
{ Never
= 0, Standard
= 1, ExperimentalExt
= 2 };
1838 static LateAttrParseKind
getLateAttrParseKind(const Record
*Attr
) {
1839 // This function basically does
1840 // `Attr->getValueAsDef("LateParsed")->getValueAsInt("Kind")` but does a bunch
1841 // of sanity checking to ensure that `LateAttrParseMode` in `Attr.td` is in
1842 // sync with the `LateAttrParseKind` enum in this source file.
1844 static constexpr StringRef LateParsedStr
= "LateParsed";
1845 static constexpr StringRef LateAttrParseKindStr
= "LateAttrParseKind";
1846 static constexpr StringRef KindFieldStr
= "Kind";
1848 auto *LAPK
= Attr
->getValueAsDef(LateParsedStr
);
1850 // Typecheck the `LateParsed` field.
1851 SmallVector
<const Record
*, 1> SuperClasses
;
1852 LAPK
->getDirectSuperClasses(SuperClasses
);
1853 if (SuperClasses
.size() != 1)
1854 PrintFatalError(Attr
, "Field `" + Twine(LateParsedStr
) +
1855 "`should only have one super class");
1857 if (SuperClasses
[0]->getName() != LateAttrParseKindStr
)
1859 Attr
, "Field `" + Twine(LateParsedStr
) + "`should only have type `" +
1860 Twine(LateAttrParseKindStr
) + "` but found type `" +
1861 SuperClasses
[0]->getName() + "`");
1863 // Get Kind and verify the enum name matches the name in `Attr.td`.
1864 unsigned Kind
= LAPK
->getValueAsInt(KindFieldStr
);
1865 switch (LateAttrParseKind(Kind
)) {
1867 case LateAttrParseKind::X: \
1868 if (LAPK->getName().compare("LateAttrParse" #X) != 0) { \
1871 "Field `" + Twine(LateParsedStr) + "` set to `" + LAPK->getName() + \
1872 "` but this converts to `LateAttrParseKind::" + Twine(#X) + \
1875 return LateAttrParseKind::X;
1879 CASE(ExperimentalExt
)
1883 // The Kind value is completely invalid
1884 auto KindValueStr
= utostr(Kind
);
1885 PrintFatalError(Attr
, "Field `" + Twine(LateParsedStr
) + "` set to `" +
1886 LAPK
->getName() + "` has unexpected `" +
1887 Twine(KindFieldStr
) + "` value of " + KindValueStr
);
1890 // Emits the LateParsed property for attributes.
1891 static void emitClangAttrLateParsedListImpl(const RecordKeeper
&Records
,
1893 LateAttrParseKind LateParseMode
) {
1894 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
1895 if (LateAttrParseKind LateParsed
= getLateAttrParseKind(Attr
);
1896 LateParsed
!= LateParseMode
)
1899 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(*Attr
);
1901 // FIXME: Handle non-GNU attributes
1902 for (const auto &I
: Spellings
) {
1903 if (I
.variety() != "GNU")
1905 OS
<< ".Case(\"" << I
.name() << "\", 1)\n";
1910 static void emitClangAttrLateParsedList(const RecordKeeper
&Records
,
1912 OS
<< "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
1913 emitClangAttrLateParsedListImpl(Records
, OS
, LateAttrParseKind::Standard
);
1914 OS
<< "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
1917 static void emitClangAttrLateParsedExperimentalList(const RecordKeeper
&Records
,
1919 OS
<< "#if defined(CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST)\n";
1920 emitClangAttrLateParsedListImpl(Records
, OS
,
1921 LateAttrParseKind::ExperimentalExt
);
1922 OS
<< "#endif // CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST\n\n";
1925 static bool hasGNUorCXX11Spelling(const Record
&Attribute
) {
1926 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attribute
);
1927 for (const auto &I
: Spellings
) {
1928 if (I
.variety() == "GNU" || I
.variety() == "CXX11")
1936 struct AttributeSubjectMatchRule
{
1937 const Record
*MetaSubject
;
1938 const Record
*Constraint
;
1940 AttributeSubjectMatchRule(const Record
*MetaSubject
, const Record
*Constraint
)
1941 : MetaSubject(MetaSubject
), Constraint(Constraint
) {
1942 assert(MetaSubject
&& "Missing subject");
1945 bool isSubRule() const { return Constraint
!= nullptr; }
1947 std::vector
<const Record
*> getSubjects() const {
1948 return (Constraint
? Constraint
: MetaSubject
)
1949 ->getValueAsListOfDefs("Subjects");
1952 std::vector
<const Record
*> getLangOpts() const {
1954 // Lookup the options in the sub-rule first, in case the sub-rule
1955 // overrides the rules options.
1956 std::vector
<const Record
*> Opts
=
1957 Constraint
->getValueAsListOfDefs("LangOpts");
1961 return MetaSubject
->getValueAsListOfDefs("LangOpts");
1964 // Abstract rules are used only for sub-rules
1965 bool isAbstractRule() const { return getSubjects().empty(); }
1967 StringRef
getName() const {
1968 return (Constraint
? Constraint
: MetaSubject
)->getValueAsString("Name");
1971 bool isNegatedSubRule() const {
1972 assert(isSubRule() && "Not a sub-rule");
1973 return Constraint
->getValueAsBit("Negated");
1976 std::string
getSpelling() const {
1977 std::string Result
= MetaSubject
->getValueAsString("Name").str();
1980 if (isNegatedSubRule())
1981 Result
+= "unless(";
1982 Result
+= getName();
1983 if (isNegatedSubRule())
1990 std::string
getEnumValueName() const {
1991 SmallString
<128> Result
;
1992 Result
+= "SubjectMatchRule_";
1993 Result
+= MetaSubject
->getValueAsString("Name");
1996 if (isNegatedSubRule())
1998 Result
+= Constraint
->getValueAsString("Name");
2000 if (isAbstractRule())
2001 Result
+= "_abstract";
2002 return std::string(Result
);
2005 std::string
getEnumValue() const { return "attr::" + getEnumValueName(); }
2007 static const char *EnumName
;
2010 const char *AttributeSubjectMatchRule::EnumName
= "attr::SubjectMatchRule";
2012 struct PragmaClangAttributeSupport
{
2013 std::vector
<AttributeSubjectMatchRule
> Rules
;
2015 class RuleOrAggregateRuleSet
{
2016 std::vector
<AttributeSubjectMatchRule
> Rules
;
2018 RuleOrAggregateRuleSet(ArrayRef
<AttributeSubjectMatchRule
> Rules
,
2020 : Rules(Rules
), IsRule(IsRule
) {}
2023 bool isRule() const { return IsRule
; }
2025 const AttributeSubjectMatchRule
&getRule() const {
2026 assert(IsRule
&& "not a rule!");
2030 ArrayRef
<AttributeSubjectMatchRule
> getAggregateRuleSet() const {
2034 static RuleOrAggregateRuleSet
2035 getRule(const AttributeSubjectMatchRule
&Rule
) {
2036 return RuleOrAggregateRuleSet(Rule
, /*IsRule=*/true);
2038 static RuleOrAggregateRuleSet
2039 getAggregateRuleSet(ArrayRef
<AttributeSubjectMatchRule
> Rules
) {
2040 return RuleOrAggregateRuleSet(Rules
, /*IsRule=*/false);
2043 DenseMap
<const Record
*, RuleOrAggregateRuleSet
> SubjectsToRules
;
2045 PragmaClangAttributeSupport(const RecordKeeper
&Records
);
2047 bool isAttributedSupported(const Record
&Attribute
);
2049 void emitMatchRuleList(raw_ostream
&OS
);
2051 void generateStrictConformsTo(const Record
&Attr
, raw_ostream
&OS
);
2053 void generateParsingHelpers(raw_ostream
&OS
);
2056 } // end anonymous namespace
2058 static bool isSupportedPragmaClangAttributeSubject(const Record
&Subject
) {
2059 // FIXME: #pragma clang attribute does not currently support statement
2060 // attributes, so test whether the subject is one that appertains to a
2061 // declaration node. However, it may be reasonable for support for statement
2062 // attributes to be added.
2063 if (Subject
.isSubClassOf("DeclNode") || Subject
.isSubClassOf("DeclBase") ||
2064 Subject
.getName() == "DeclBase")
2067 if (Subject
.isSubClassOf("SubsetSubject"))
2068 return isSupportedPragmaClangAttributeSubject(
2069 *Subject
.getValueAsDef("Base"));
2074 static bool doesDeclDeriveFrom(const Record
*D
, const Record
*Base
) {
2075 const Record
*CurrentBase
= D
->getValueAsOptionalDef(BaseFieldName
);
2078 if (CurrentBase
== Base
)
2080 return doesDeclDeriveFrom(CurrentBase
, Base
);
2083 PragmaClangAttributeSupport::PragmaClangAttributeSupport(
2084 const RecordKeeper
&Records
) {
2085 auto MapFromSubjectsToRules
= [this](const Record
*SubjectContainer
,
2086 const Record
*MetaSubject
,
2087 const Record
*Constraint
) {
2088 Rules
.emplace_back(MetaSubject
, Constraint
);
2089 for (const Record
*Subject
:
2090 SubjectContainer
->getValueAsListOfDefs("Subjects")) {
2093 .try_emplace(Subject
, RuleOrAggregateRuleSet::getRule(
2094 AttributeSubjectMatchRule(MetaSubject
,
2098 PrintFatalError("Attribute subject match rules should not represent"
2099 "same attribute subjects.");
2103 for (const auto *MetaSubject
:
2104 Records
.getAllDerivedDefinitions("AttrSubjectMatcherRule")) {
2105 MapFromSubjectsToRules(MetaSubject
, MetaSubject
, /*Constraints=*/nullptr);
2106 for (const Record
*Constraint
:
2107 MetaSubject
->getValueAsListOfDefs("Constraints"))
2108 MapFromSubjectsToRules(Constraint
, MetaSubject
, Constraint
);
2111 ArrayRef
<const Record
*> DeclNodes
=
2112 Records
.getAllDerivedDefinitions(DeclNodeClassName
);
2113 for (const auto *Aggregate
:
2114 Records
.getAllDerivedDefinitions("AttrSubjectMatcherAggregateRule")) {
2115 const Record
*SubjectDecl
= Aggregate
->getValueAsDef("Subject");
2117 // Gather sub-classes of the aggregate subject that act as attribute
2119 std::vector
<AttributeSubjectMatchRule
> Rules
;
2120 for (const auto *D
: DeclNodes
) {
2121 if (doesDeclDeriveFrom(D
, SubjectDecl
)) {
2122 auto It
= SubjectsToRules
.find(D
);
2123 if (It
== SubjectsToRules
.end())
2125 if (!It
->second
.isRule() || It
->second
.getRule().isSubRule())
2126 continue; // Assume that the rule will be included as well.
2127 Rules
.push_back(It
->second
.getRule());
2133 .try_emplace(SubjectDecl
,
2134 RuleOrAggregateRuleSet::getAggregateRuleSet(Rules
))
2137 PrintFatalError("Attribute subject match rules should not represent"
2138 "same attribute subjects.");
2143 static PragmaClangAttributeSupport
&
2144 getPragmaAttributeSupport(const RecordKeeper
&Records
) {
2145 static PragmaClangAttributeSupport
Instance(Records
);
2149 void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream
&OS
) {
2150 OS
<< "#ifndef ATTR_MATCH_SUB_RULE\n";
2151 OS
<< "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
2153 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
2155 for (const auto &Rule
: Rules
) {
2156 OS
<< (Rule
.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
2157 OS
<< Rule
.getEnumValueName() << ", \"" << Rule
.getSpelling() << "\", "
2158 << Rule
.isAbstractRule();
2159 if (Rule
.isSubRule())
2161 << AttributeSubjectMatchRule(Rule
.MetaSubject
, nullptr).getEnumValue()
2162 << ", " << Rule
.isNegatedSubRule();
2165 OS
<< "#undef ATTR_MATCH_SUB_RULE\n";
2168 bool PragmaClangAttributeSupport::isAttributedSupported(
2169 const Record
&Attribute
) {
2170 // If the attribute explicitly specified whether to support #pragma clang
2171 // attribute, use that setting.
2173 bool SpecifiedResult
=
2174 Attribute
.getValueAsBitOrUnset("PragmaAttributeSupport", Unset
);
2176 return SpecifiedResult
;
2180 // An attribute requires delayed parsing (LateParsed is on).
2181 switch (getLateAttrParseKind(&Attribute
)) {
2182 case LateAttrParseKind::Never
:
2184 case LateAttrParseKind::Standard
:
2186 case LateAttrParseKind::ExperimentalExt
:
2187 // This is only late parsed in certain parsing contexts when
2188 // `LangOpts.ExperimentalLateParseAttributes` is true. Information about the
2189 // parsing context and `LangOpts` is not available in this method so just
2190 // opt this attribute out.
2194 // An attribute has no GNU/CXX11 spelling
2195 if (!hasGNUorCXX11Spelling(Attribute
))
2197 // An attribute subject list has a subject that isn't covered by one of the
2198 // subject match rules or has no subjects at all.
2199 if (Attribute
.isValueUnset("Subjects"))
2201 const Record
*SubjectObj
= Attribute
.getValueAsDef("Subjects");
2202 bool HasAtLeastOneValidSubject
= false;
2203 for (const auto *Subject
: SubjectObj
->getValueAsListOfDefs("Subjects")) {
2204 if (!isSupportedPragmaClangAttributeSubject(*Subject
))
2206 if (!SubjectsToRules
.contains(Subject
))
2208 HasAtLeastOneValidSubject
= true;
2210 return HasAtLeastOneValidSubject
;
2213 static std::string
GenerateTestExpression(ArrayRef
<const Record
*> LangOpts
) {
2216 for (auto *E
: LangOpts
) {
2220 const StringRef Code
= E
->getValueAsString("CustomCode");
2221 if (!Code
.empty()) {
2225 if (!E
->getValueAsString("Name").empty()) {
2228 "non-empty 'Name' field ignored because 'CustomCode' was supplied");
2231 Test
+= "LangOpts.";
2232 Test
+= E
->getValueAsString("Name");
2243 PragmaClangAttributeSupport::generateStrictConformsTo(const Record
&Attr
,
2245 if (!isAttributedSupported(Attr
) || Attr
.isValueUnset("Subjects"))
2247 // Generate a function that constructs a set of matching rules that describe
2248 // to which declarations the attribute should apply to.
2249 OS
<< "void getPragmaAttributeMatchRules("
2250 << "llvm::SmallVectorImpl<std::pair<"
2251 << AttributeSubjectMatchRule::EnumName
2252 << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2253 const Record
*SubjectObj
= Attr
.getValueAsDef("Subjects");
2254 for (const auto *Subject
: SubjectObj
->getValueAsListOfDefs("Subjects")) {
2255 if (!isSupportedPragmaClangAttributeSubject(*Subject
))
2257 auto It
= SubjectsToRules
.find(Subject
);
2258 assert(It
!= SubjectsToRules
.end() &&
2259 "This attribute is unsupported by #pragma clang attribute");
2260 for (const auto &Rule
: It
->getSecond().getAggregateRuleSet()) {
2261 // The rule might be language specific, so only subtract it from the given
2262 // rules if the specific language options are specified.
2263 std::vector
<const Record
*> LangOpts
= Rule
.getLangOpts();
2264 OS
<< " MatchRules.push_back(std::make_pair(" << Rule
.getEnumValue()
2265 << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts
)
2272 void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream
&OS
) {
2273 // Generate routines that check the names of sub-rules.
2274 OS
<< "std::optional<attr::SubjectMatchRule> "
2275 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2276 OS
<< " return std::nullopt;\n";
2279 MapVector
<const Record
*, std::vector
<AttributeSubjectMatchRule
>>
2281 for (const auto &Rule
: Rules
) {
2282 if (!Rule
.isSubRule())
2284 SubMatchRules
[Rule
.MetaSubject
].push_back(Rule
);
2287 for (const auto &SubMatchRule
: SubMatchRules
) {
2288 OS
<< "std::optional<attr::SubjectMatchRule> "
2289 "isAttributeSubjectMatchSubRuleFor_"
2290 << SubMatchRule
.first
->getValueAsString("Name")
2291 << "(StringRef Name, bool IsUnless) {\n";
2292 OS
<< " if (IsUnless)\n";
2294 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2295 for (const auto &Rule
: SubMatchRule
.second
) {
2296 if (Rule
.isNegatedSubRule())
2297 OS
<< " Case(\"" << Rule
.getName() << "\", " << Rule
.getEnumValue()
2300 OS
<< " Default(std::nullopt);\n";
2302 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2303 for (const auto &Rule
: SubMatchRule
.second
) {
2304 if (!Rule
.isNegatedSubRule())
2305 OS
<< " Case(\"" << Rule
.getName() << "\", " << Rule
.getEnumValue()
2308 OS
<< " Default(std::nullopt);\n";
2312 // Generate the function that checks for the top-level rules.
2313 OS
<< "std::pair<std::optional<attr::SubjectMatchRule>, "
2314 "std::optional<attr::SubjectMatchRule> (*)(StringRef, "
2315 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2317 "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, "
2318 "std::optional<attr::SubjectMatchRule> (*) (StringRef, "
2320 for (const auto &Rule
: Rules
) {
2321 if (Rule
.isSubRule())
2323 std::string SubRuleFunction
;
2324 if (SubMatchRules
.count(Rule
.MetaSubject
))
2326 ("isAttributeSubjectMatchSubRuleFor_" + Rule
.getName()).str();
2328 SubRuleFunction
= "defaultIsAttributeSubjectMatchSubRuleFor";
2329 OS
<< " Case(\"" << Rule
.getName() << "\", std::make_pair("
2330 << Rule
.getEnumValue() << ", " << SubRuleFunction
<< ")).\n";
2332 OS
<< " Default(std::make_pair(std::nullopt, "
2333 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2336 // Generate the function that checks for the submatch rules.
2337 OS
<< "const char *validAttributeSubjectMatchSubRules("
2338 << AttributeSubjectMatchRule::EnumName
<< " Rule) {\n";
2339 OS
<< " switch (Rule) {\n";
2340 for (const auto &SubMatchRule
: SubMatchRules
) {
2342 << AttributeSubjectMatchRule(SubMatchRule
.first
, nullptr).getEnumValue()
2344 OS
<< " return \"'";
2345 bool IsFirst
= true;
2346 for (const auto &Rule
: SubMatchRule
.second
) {
2350 if (Rule
.isNegatedSubRule())
2352 OS
<< Rule
.getName();
2353 if (Rule
.isNegatedSubRule())
2359 OS
<< " default: return nullptr;\n";
2364 template <typename Fn
> static void forEachSpelling(const Record
&Attr
, Fn
&&F
) {
2365 for (const FlattenedSpelling
&S
: GetFlattenedSpellings(Attr
)) {
2370 static std::map
<StringRef
, std::vector
<const Record
*>> NameToAttrsMap
;
2372 /// Build a map from the attribute name to the Attrs that use that name. If more
2373 /// than one Attr use a name, the arguments could be different so a more complex
2374 /// check is needed in the generated switch.
2375 static void generateNameToAttrsMap(const RecordKeeper
&Records
) {
2376 for (const auto *A
: Records
.getAllDerivedDefinitions("Attr")) {
2377 for (const FlattenedSpelling
&S
: GetFlattenedSpellings(*A
)) {
2378 auto [It
, Inserted
] = NameToAttrsMap
.try_emplace(S
.name());
2379 if (Inserted
|| !is_contained(It
->second
, A
))
2380 It
->second
.emplace_back(A
);
2385 /// Generate the info needed to produce the case values in case more than one
2386 /// attribute has the same name. Store the info in a map that can be processed
2387 /// after all attributes are seen.
2388 static void generateFlattenedSpellingInfo(const Record
&Attr
,
2389 std::map
<StringRef
, FSIVecTy
> &Map
,
2390 uint32_t ArgMask
= 0) {
2391 std::string TargetTest
;
2392 if (Attr
.isSubClassOf("TargetSpecificAttr") &&
2393 !Attr
.isValueUnset("ParseKind")) {
2394 const Record
*T
= Attr
.getValueAsDef("Target");
2395 std::vector
<StringRef
> Arches
= T
->getValueAsListOfStrings("Arches");
2396 (void)GenerateTargetSpecificAttrChecks(T
, Arches
, TargetTest
, nullptr);
2399 forEachSpelling(Attr
, [&](const FlattenedSpelling
&S
) {
2400 Map
[S
.name()].emplace_back(S
.variety(), S
.nameSpace(), TargetTest
, ArgMask
);
2404 static bool nameAppliesToOneAttribute(StringRef Name
) {
2405 auto It
= NameToAttrsMap
.find(Name
);
2406 assert(It
!= NameToAttrsMap
.end());
2407 return It
->second
.size() == 1;
2410 static bool emitIfSimpleValue(StringRef Name
, uint32_t ArgMask
,
2412 if (nameAppliesToOneAttribute(Name
)) {
2413 OS
<< ".Case(\"" << Name
<< "\", ";
2415 OS
<< ArgMask
<< ")\n";
2423 static void emitSingleCondition(const FlattenedSpellingInfo
&FSI
,
2425 OS
<< "(Syntax==AttributeCommonInfo::AS_" << FSI
.Syntax
<< " && ";
2426 if (!FSI
.Scope
.empty())
2427 OS
<< "ScopeName && ScopeName->getName()==\"" << FSI
.Scope
<< "\"";
2430 if (!FSI
.TargetTest
.empty())
2431 OS
<< " && " << FSI
.TargetTest
;
2435 static void emitStringSwitchCases(std::map
<StringRef
, FSIVecTy
> &Map
,
2437 for (const auto &[Name
, Vec
] : Map
) {
2438 if (emitIfSimpleValue(Name
, Vec
[0].ArgMask
, OS
))
2441 // Not simple, build expressions for each case.
2442 OS
<< ".Case(\"" << Name
<< "\", ";
2443 for (unsigned I
= 0, E
= Vec
.size(); I
< E
; ++I
) {
2444 emitSingleCondition(Vec
[I
], OS
);
2445 uint32_t ArgMask
= Vec
[I
].ArgMask
;
2446 if (E
== 1 && ArgMask
== 0)
2449 // More than one or it's the Mask form. Create a conditional expression.
2450 uint32_t SuccessValue
= ArgMask
!= 0 ? ArgMask
: 1;
2451 OS
<< " ? " << SuccessValue
<< " : ";
2459 static bool isTypeArgument(const Record
*Arg
) {
2460 return !Arg
->getSuperClasses().empty() &&
2461 Arg
->getSuperClasses().back().first
->getName() == "TypeArgument";
2464 /// Emits the first-argument-is-type property for attributes.
2465 static void emitClangAttrTypeArgList(const RecordKeeper
&Records
,
2467 OS
<< "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2468 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2469 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
2470 // Determine whether the first argument is a type.
2471 std::vector
<const Record
*> Args
= Attr
->getValueAsListOfDefs("Args");
2475 if (!isTypeArgument(Args
[0]))
2477 generateFlattenedSpellingInfo(*Attr
, FSIMap
);
2479 emitStringSwitchCases(FSIMap
, OS
);
2480 OS
<< "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2483 /// Emits the parse-arguments-in-unevaluated-context property for
2485 static void emitClangAttrArgContextList(const RecordKeeper
&Records
,
2487 OS
<< "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2488 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2489 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
2490 for (const auto &I
: Attrs
) {
2491 const Record
&Attr
= *I
.second
;
2493 if (!Attr
.getValueAsBit("ParseArgumentsAsUnevaluated"))
2495 generateFlattenedSpellingInfo(Attr
, FSIMap
);
2497 emitStringSwitchCases(FSIMap
, OS
);
2498 OS
<< "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2501 static bool isIdentifierArgument(const Record
*Arg
) {
2502 return !Arg
->getSuperClasses().empty() &&
2503 StringSwitch
<bool>(Arg
->getSuperClasses().back().first
->getName())
2504 .Case("IdentifierArgument", true)
2505 .Case("EnumArgument", true)
2506 .Case("VariadicEnumArgument", true)
2510 static bool isVariadicIdentifierArgument(const Record
*Arg
) {
2511 return !Arg
->getSuperClasses().empty() &&
2512 StringSwitch
<bool>(Arg
->getSuperClasses().back().first
->getName())
2513 .Case("VariadicIdentifierArgument", true)
2514 .Case("VariadicParamOrParamIdxArgument", true)
2518 static bool isVariadicExprArgument(const Record
*Arg
) {
2519 return !Arg
->getSuperClasses().empty() &&
2520 StringSwitch
<bool>(Arg
->getSuperClasses().back().first
->getName())
2521 .Case("VariadicExprArgument", true)
2525 static bool isStringLiteralArgument(const Record
*Arg
) {
2526 if (Arg
->getSuperClasses().empty())
2528 StringRef ArgKind
= Arg
->getSuperClasses().back().first
->getName();
2529 if (ArgKind
== "EnumArgument")
2530 return Arg
->getValueAsBit("IsString");
2531 return ArgKind
== "StringArgument";
2534 static bool isVariadicStringLiteralArgument(const Record
*Arg
) {
2535 if (Arg
->getSuperClasses().empty())
2537 StringRef ArgKind
= Arg
->getSuperClasses().back().first
->getName();
2538 if (ArgKind
== "VariadicEnumArgument")
2539 return Arg
->getValueAsBit("IsString");
2540 return ArgKind
== "VariadicStringArgument";
2543 static void emitClangAttrVariadicIdentifierArgList(const RecordKeeper
&Records
,
2545 OS
<< "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2546 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2547 for (const auto *A
: Records
.getAllDerivedDefinitions("Attr")) {
2548 // Determine whether the first argument is a variadic identifier.
2549 std::vector
<const Record
*> Args
= A
->getValueAsListOfDefs("Args");
2550 if (Args
.empty() || !isVariadicIdentifierArgument(Args
[0]))
2552 generateFlattenedSpellingInfo(*A
, FSIMap
);
2554 emitStringSwitchCases(FSIMap
, OS
);
2555 OS
<< "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2558 // Emits the list of arguments that should be parsed as unevaluated string
2559 // literals for each attribute.
2561 emitClangAttrUnevaluatedStringLiteralList(const RecordKeeper
&Records
,
2563 OS
<< "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
2565 auto MakeMask
= [](ArrayRef
<const Record
*> Args
) {
2567 assert(Args
.size() <= 32 && "unsupported number of arguments in attribute");
2568 for (uint32_t N
= 0; N
< Args
.size(); ++N
) {
2569 Bits
|= (isStringLiteralArgument(Args
[N
]) << N
);
2570 // If we have a variadic string argument, set all the remaining bits to 1
2571 if (isVariadicStringLiteralArgument(Args
[N
])) {
2572 Bits
|= maskTrailingZeros
<decltype(Bits
)>(N
);
2579 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2580 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
2581 // Determine whether there are any string arguments.
2582 uint32_t ArgMask
= MakeMask(Attr
->getValueAsListOfDefs("Args"));
2585 generateFlattenedSpellingInfo(*Attr
, FSIMap
, ArgMask
);
2587 emitStringSwitchCases(FSIMap
, OS
);
2588 OS
<< "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
2591 // Emits the first-argument-is-identifier property for attributes.
2592 static void emitClangAttrIdentifierArgList(const RecordKeeper
&Records
,
2594 OS
<< "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2595 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2596 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
2597 // Determine whether the first argument is an identifier.
2598 std::vector
<const Record
*> Args
= Attr
->getValueAsListOfDefs("Args");
2599 if (Args
.empty() || !isIdentifierArgument(Args
[0]))
2601 generateFlattenedSpellingInfo(*Attr
, FSIMap
);
2603 emitStringSwitchCases(FSIMap
, OS
);
2604 OS
<< "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2607 // Emits the list for attributes having StrictEnumParameters.
2608 static void emitClangAttrStrictIdentifierArgList(const RecordKeeper
&Records
,
2610 OS
<< "#if defined(CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST)\n";
2611 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2612 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
2613 if (!Attr
->getValueAsBit("StrictEnumParameters"))
2615 // Check that there is really an identifier argument.
2616 std::vector
<const Record
*> Args
= Attr
->getValueAsListOfDefs("Args");
2617 if (none_of(Args
, [&](const Record
*R
) { return isIdentifierArgument(R
); }))
2619 generateFlattenedSpellingInfo(*Attr
, FSIMap
);
2621 emitStringSwitchCases(FSIMap
, OS
);
2622 OS
<< "#endif // CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST\n\n";
2625 static bool keywordThisIsaIdentifierInArgument(const Record
*Arg
) {
2626 return !Arg
->getSuperClasses().empty() &&
2627 StringSwitch
<bool>(Arg
->getSuperClasses().back().first
->getName())
2628 .Case("VariadicParamOrParamIdxArgument", true)
2632 static void emitClangAttrThisIsaIdentifierArgList(const RecordKeeper
&Records
,
2634 OS
<< "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2635 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2636 for (const auto *A
: Records
.getAllDerivedDefinitions("Attr")) {
2637 // Determine whether the first argument is a variadic identifier.
2638 std::vector
<const Record
*> Args
= A
->getValueAsListOfDefs("Args");
2639 if (Args
.empty() || !keywordThisIsaIdentifierInArgument(Args
[0]))
2641 generateFlattenedSpellingInfo(*A
, FSIMap
);
2643 emitStringSwitchCases(FSIMap
, OS
);
2644 OS
<< "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2647 static void emitClangAttrAcceptsExprPack(const RecordKeeper
&Records
,
2649 OS
<< "#if defined(CLANG_ATTR_ACCEPTS_EXPR_PACK)\n";
2650 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
2651 std::map
<StringRef
, FSIVecTy
> FSIMap
;
2652 for (const auto &I
: Attrs
) {
2653 const Record
&Attr
= *I
.second
;
2655 if (!Attr
.getValueAsBit("AcceptsExprPack"))
2657 generateFlattenedSpellingInfo(Attr
, FSIMap
);
2659 emitStringSwitchCases(FSIMap
, OS
);
2660 OS
<< "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
2663 static bool isRegularKeywordAttribute(const FlattenedSpelling
&S
) {
2664 return (S
.variety() == "Keyword" &&
2665 !S
.getSpellingRecord().getValueAsBit("HasOwnParseRules"));
2668 static void emitFormInitializer(raw_ostream
&OS
,
2669 const FlattenedSpelling
&Spelling
,
2670 StringRef SpellingIndex
) {
2672 (Spelling
.variety() == "Keyword" && Spelling
.name() == "alignas");
2673 OS
<< "{AttributeCommonInfo::AS_" << Spelling
.variety() << ", "
2674 << SpellingIndex
<< ", " << (IsAlignas
? "true" : "false")
2675 << " /*IsAlignas*/, "
2676 << (isRegularKeywordAttribute(Spelling
) ? "true" : "false")
2677 << " /*IsRegularKeywordAttribute*/}";
2680 static void emitAttributes(const RecordKeeper
&Records
, raw_ostream
&OS
,
2682 ParsedAttrMap AttrMap
= getParsedAttrList(Records
);
2684 // Helper to print the starting character of an attribute argument. If there
2685 // hasn't been an argument yet, it prints an opening parenthese; otherwise it
2687 OS
<< "static inline void DelimitAttributeArgument("
2688 << "raw_ostream& OS, bool& IsFirst) {\n"
2689 << " if (IsFirst) {\n"
2690 << " IsFirst = false;\n"
2691 << " OS << \"(\";\n"
2693 << " OS << \", \";\n"
2696 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
2697 const Record
&R
= *Attr
;
2699 // FIXME: Currently, documentation is generated as-needed due to the fact
2700 // that there is no way to allow a generated project "reach into" the docs
2701 // directory (for instance, it may be an out-of-tree build). However, we want
2702 // to ensure that every attribute has a Documentation field, and produce an
2703 // error if it has been neglected. Otherwise, the on-demand generation which
2704 // happens server-side will fail. This code is ensuring that functionality,
2705 // even though this Emitter doesn't technically need the documentation.
2706 // When attribute documentation can be generated as part of the build
2707 // itself, this code can be removed.
2708 (void)R
.getValueAsListOfDefs("Documentation");
2710 if (!R
.getValueAsBit("ASTNode"))
2713 ArrayRef
<std::pair
<const Record
*, SMRange
>> Supers
= R
.getSuperClasses();
2714 assert(!Supers
.empty() && "Forgot to specify a superclass for the attr");
2715 std::string SuperName
;
2716 bool Inheritable
= false;
2717 for (const auto &[R
, _
] : reverse(Supers
)) {
2718 if (R
->getName() != "TargetSpecificAttr" &&
2719 R
->getName() != "DeclOrTypeAttr" && SuperName
.empty())
2720 SuperName
= R
->getName().str();
2721 if (R
->getName() == "InheritableAttr")
2726 OS
<< "class CLANG_ABI " << R
.getName() << "Attr : public " << SuperName
2729 OS
<< "\n// " << R
.getName() << "Attr implementation\n\n";
2731 std::vector
<const Record
*> ArgRecords
= R
.getValueAsListOfDefs("Args");
2732 std::vector
<std::unique_ptr
<Argument
>> Args
;
2733 Args
.reserve(ArgRecords
.size());
2735 bool AttrAcceptsExprPack
= Attr
->getValueAsBit("AcceptsExprPack");
2736 if (AttrAcceptsExprPack
) {
2737 for (size_t I
= 0; I
< ArgRecords
.size(); ++I
) {
2738 const Record
*ArgR
= ArgRecords
[I
];
2739 if (isIdentifierArgument(ArgR
) || isVariadicIdentifierArgument(ArgR
) ||
2740 isTypeArgument(ArgR
))
2741 PrintFatalError(Attr
->getLoc(),
2742 "Attributes accepting packs cannot also "
2743 "have identifier or type arguments.");
2744 // When trying to determine if value-dependent expressions can populate
2745 // the attribute without prior instantiation, the decision is made based
2746 // on the assumption that only the last argument is ever variadic.
2747 if (I
< (ArgRecords
.size() - 1) && isVariadicExprArgument(ArgR
))
2748 PrintFatalError(Attr
->getLoc(),
2749 "Attributes accepting packs can only have the last "
2750 "argument be variadic.");
2754 bool HasOptArg
= false;
2755 bool HasFakeArg
= false;
2756 for (const auto *ArgRecord
: ArgRecords
) {
2757 Args
.emplace_back(createArgument(*ArgRecord
, R
.getName()));
2759 Args
.back()->writeDeclarations(OS
);
2763 // For these purposes, fake takes priority over optional.
2764 if (Args
.back()->isFake()) {
2766 } else if (Args
.back()->isOptional()) {
2771 std::unique_ptr
<VariadicExprArgument
> DelayedArgs
= nullptr;
2772 if (AttrAcceptsExprPack
) {
2774 std::make_unique
<VariadicExprArgument
>("DelayedArgs", R
.getName());
2776 DelayedArgs
->writeDeclarations(OS
);
2784 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
2786 // If there are zero or one spellings, all spelling-related functionality
2787 // can be elided. If all of the spellings share the same name, the spelling
2788 // functionality can also be elided.
2789 bool ElideSpelling
= (Spellings
.size() <= 1) ||
2790 SpellingNamesAreCommon(Spellings
);
2792 // This maps spelling index values to semantic Spelling enumerants.
2793 SemanticSpellingMap SemanticToSyntacticMap
;
2795 std::string SpellingEnum
;
2796 if (Spellings
.size() > 1)
2797 SpellingEnum
= CreateSemanticSpellings(Spellings
, SemanticToSyntacticMap
);
2801 const auto &ParsedAttrSpellingItr
=
2802 find_if(AttrMap
, [R
](const std::pair
<std::string
, const Record
*> &P
) {
2803 return &R
== P
.second
;
2806 // Emit CreateImplicit factory methods.
2807 auto emitCreate
= [&](bool Implicit
, bool DelayedArgsOnly
, bool emitFake
) {
2810 OS
<< R
.getName() << "Attr *";
2812 OS
<< R
.getName() << "Attr::";
2816 if (DelayedArgsOnly
)
2817 OS
<< "WithDelayedArgs";
2819 OS
<< "ASTContext &Ctx";
2820 if (!DelayedArgsOnly
) {
2821 for (auto const &ai
: Args
) {
2822 if (ai
->isFake() && !emitFake
)
2825 ai
->writeCtorParameters(OS
);
2829 DelayedArgs
->writeCtorParameters(OS
);
2831 OS
<< ", const AttributeCommonInfo &CommonInfo";
2839 OS
<< " auto *A = new (Ctx) " << R
.getName();
2840 OS
<< "Attr(Ctx, CommonInfo";
2842 if (!DelayedArgsOnly
) {
2843 for (auto const &ai
: Args
) {
2844 if (ai
->isFake() && !emitFake
)
2847 ai
->writeImplicitCtorArgs(OS
);
2852 OS
<< " A->setImplicit(true);\n";
2854 if (Implicit
|| ElideSpelling
) {
2855 OS
<< " if (!A->isAttributeSpellingListCalculated() && "
2856 "!A->getAttrName())\n";
2857 OS
<< " A->setAttributeSpellingListIndex(0);\n";
2859 if (DelayedArgsOnly
) {
2860 OS
<< " A->setDelayedArgs(Ctx, ";
2861 DelayedArgs
->writeImplicitCtorArgs(OS
);
2864 OS
<< " return A;\n}\n\n";
2867 auto emitCreateNoCI
= [&](bool Implicit
, bool DelayedArgsOnly
,
2871 OS
<< R
.getName() << "Attr *";
2873 OS
<< R
.getName() << "Attr::";
2877 if (DelayedArgsOnly
)
2878 OS
<< "WithDelayedArgs";
2880 OS
<< "ASTContext &Ctx";
2881 if (!DelayedArgsOnly
) {
2882 for (auto const &ai
: Args
) {
2883 if (ai
->isFake() && !emitFake
)
2886 ai
->writeCtorParameters(OS
);
2890 DelayedArgs
->writeCtorParameters(OS
);
2892 OS
<< ", SourceRange Range";
2895 if (Spellings
.size() > 1) {
2896 OS
<< ", Spelling S";
2898 OS
<< " = " << SemanticToSyntacticMap
[0];
2907 OS
<< " AttributeCommonInfo I(Range, ";
2909 if (ParsedAttrSpellingItr
!= std::end(AttrMap
))
2910 OS
<< "AT_" << ParsedAttrSpellingItr
->first
;
2912 OS
<< "NoSemaHandlerAttribute";
2914 if (Spellings
.size() == 0) {
2915 OS
<< ", AttributeCommonInfo::Form::Implicit()";
2916 } else if (Spellings
.size() == 1) {
2918 emitFormInitializer(OS
, Spellings
[0], "0");
2920 OS
<< ", [&]() {\n";
2921 OS
<< " switch (S) {\n";
2922 std::set
<std::string
> Uniques
;
2924 for (auto I
= Spellings
.begin(), E
= Spellings
.end(); I
!= E
;
2926 const FlattenedSpelling
&S
= *I
;
2927 const auto &Name
= SemanticToSyntacticMap
[Idx
];
2928 if (Uniques
.insert(Name
).second
) {
2929 OS
<< " case " << Name
<< ":\n";
2930 OS
<< " return AttributeCommonInfo::Form";
2931 emitFormInitializer(OS
, S
, Name
);
2935 OS
<< " default:\n";
2936 OS
<< " llvm_unreachable(\"Unknown attribute spelling!\");\n"
2937 << " return AttributeCommonInfo::Form";
2938 emitFormInitializer(OS
, Spellings
[0], "0");
2945 OS
<< " return Create";
2948 if (DelayedArgsOnly
)
2949 OS
<< "WithDelayedArgs";
2951 if (!DelayedArgsOnly
) {
2952 for (auto const &ai
: Args
) {
2953 if (ai
->isFake() && !emitFake
)
2956 ai
->writeImplicitCtorArgs(OS
);
2960 DelayedArgs
->writeImplicitCtorArgs(OS
);
2966 auto emitCreates
= [&](bool DelayedArgsOnly
, bool emitFake
) {
2967 emitCreate(true, DelayedArgsOnly
, emitFake
);
2968 emitCreate(false, DelayedArgsOnly
, emitFake
);
2969 emitCreateNoCI(true, DelayedArgsOnly
, emitFake
);
2970 emitCreateNoCI(false, DelayedArgsOnly
, emitFake
);
2974 OS
<< " // Factory methods\n";
2976 // Emit a CreateImplicit that takes all the arguments.
2977 emitCreates(false, true);
2979 // Emit a CreateImplicit that takes all the non-fake arguments.
2981 emitCreates(false, false);
2983 // Emit a CreateWithDelayedArgs that takes only the dependent argument
2986 emitCreates(true, false);
2988 // Emit constructors.
2989 auto emitCtor
= [&](bool emitOpt
, bool emitFake
, bool emitNoArgs
) {
2990 auto shouldEmitArg
= [=](const std::unique_ptr
<Argument
> &arg
) {
2995 if (arg
->isOptional())
3002 OS
<< R
.getName() << "Attr::";
3004 << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
3006 for (auto const &ai
: Args
) {
3007 if (!shouldEmitArg(ai
))
3010 ai
->writeCtorParameters(OS
);
3019 OS
<< "\n : " << SuperName
<< "(Ctx, CommonInfo, ";
3020 OS
<< "attr::" << R
.getName() << ", ";
3022 // Handle different late parsing modes.
3023 OS
<< "/*IsLateParsed=*/";
3024 switch (getLateAttrParseKind(&R
)) {
3025 case LateAttrParseKind::Never
:
3028 case LateAttrParseKind::ExperimentalExt
:
3029 // Currently no clients need to know the distinction between `Standard`
3030 // and `ExperimentalExt` so treat `ExperimentalExt` just like
3031 // `Standard` for now.
3032 case LateAttrParseKind::Standard
:
3033 // Note: This is misleading. `IsLateParsed` doesn't mean the
3034 // attribute was actually late parsed. Instead it means the attribute in
3035 // `Attr.td` is marked as being late parsed. Maybe it should be called
3036 // `IsLateParseable`?
3043 << (R
.getValueAsBit("InheritEvenIfAlreadyPresent") ? "true"
3048 for (auto const &ai
: Args
) {
3050 if (!shouldEmitArg(ai
)) {
3051 ai
->writeCtorDefaultInitializers(OS
);
3053 ai
->writeCtorInitializers(OS
);
3059 DelayedArgs
->writeCtorDefaultInitializers(OS
);
3065 for (auto const &ai
: Args
) {
3066 if (!shouldEmitArg(ai
))
3068 ai
->writeCtorBody(OS
);
3074 OS
<< "\n // Constructors\n";
3076 // Emit a constructor that includes all the arguments.
3077 // This is necessary for cloning.
3078 emitCtor(true, true, false);
3080 // Emit a constructor that takes all the non-fake arguments.
3082 emitCtor(true, false, false);
3084 // Emit a constructor that takes all the non-fake, non-optional arguments.
3086 emitCtor(false, false, false);
3088 // Emit constructors that takes no arguments if none already exists.
3089 // This is used for delaying arguments.
3090 bool HasRequiredArgs
=
3091 count_if(Args
, [=](const std::unique_ptr
<Argument
> &arg
) {
3092 return !arg
->isFake() && !arg
->isOptional();
3094 if (DelayedArgs
&& HasRequiredArgs
)
3095 emitCtor(false, false, true);
3099 OS
<< " " << R
.getName() << "Attr *clone(ASTContext &C) const;\n";
3100 OS
<< " void printPretty(raw_ostream &OS,\n"
3101 << " const PrintingPolicy &Policy) const;\n";
3102 OS
<< " const char *getSpelling() const;\n";
3105 if (!ElideSpelling
) {
3106 assert(!SemanticToSyntacticMap
.empty() && "Empty semantic mapping list");
3108 OS
<< " Spelling getSemanticSpelling() const;\n";
3110 OS
<< R
.getName() << "Attr::Spelling " << R
.getName()
3111 << "Attr::getSemanticSpelling() const {\n";
3112 WriteSemanticSpellingSwitch("getAttributeSpellingListIndex()",
3113 SemanticToSyntacticMap
, OS
);
3119 writeAttrAccessorDefinition(R
, OS
);
3121 for (auto const &ai
: Args
) {
3123 ai
->writeAccessors(OS
);
3125 ai
->writeAccessorDefinitions(OS
);
3129 // Don't write conversion routines for fake arguments.
3130 if (ai
->isFake()) continue;
3132 if (ai
->isEnumArg())
3133 static_cast<const EnumArgument
*>(ai
.get())->writeConversion(OS
,
3135 else if (ai
->isVariadicEnumArg())
3136 static_cast<const VariadicEnumArgument
*>(ai
.get())->writeConversion(
3142 DelayedArgs
->writeAccessors(OS
);
3143 DelayedArgs
->writeSetter(OS
);
3146 OS
<< R
.getValueAsString("AdditionalMembers");
3149 OS
<< " static bool classof(const Attr *A) { return A->getKind() == "
3150 << "attr::" << R
.getName() << "; }\n";
3155 DelayedArgs
->writeAccessorDefinitions(OS
);
3157 OS
<< R
.getName() << "Attr *" << R
.getName()
3158 << "Attr::clone(ASTContext &C) const {\n";
3159 OS
<< " auto *A = new (C) " << R
.getName() << "Attr(C, *this";
3160 for (auto const &ai
: Args
) {
3162 ai
->writeCloneArgs(OS
);
3165 OS
<< " A->Inherited = Inherited;\n";
3166 OS
<< " A->IsPackExpansion = IsPackExpansion;\n";
3167 OS
<< " A->setImplicit(Implicit);\n";
3169 OS
<< " A->setDelayedArgs(C, ";
3170 DelayedArgs
->writeCloneArgs(OS
);
3173 OS
<< " return A;\n}\n\n";
3175 writePrettyPrintFunction(R
, Args
, OS
);
3176 writeGetSpellingFunction(R
, OS
);
3180 // Emits the class definitions for attributes.
3181 void clang::EmitClangAttrClass(const RecordKeeper
&Records
, raw_ostream
&OS
) {
3182 emitSourceFileHeader("Attribute classes' definitions", OS
, Records
);
3184 OS
<< "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
3185 OS
<< "#define LLVM_CLANG_ATTR_CLASSES_INC\n";
3186 OS
<< "#include \"clang/Support/Compiler.h\"\n\n";
3188 emitAttributes(Records
, OS
, true);
3190 OS
<< "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
3193 // Emits the class method definitions for attributes.
3194 void clang::EmitClangAttrImpl(const RecordKeeper
&Records
, raw_ostream
&OS
) {
3195 emitSourceFileHeader("Attribute classes' member function definitions", OS
,
3198 emitAttributes(Records
, OS
, false);
3200 // Instead of relying on virtual dispatch we just create a huge dispatch
3201 // switch. This is both smaller and faster than virtual functions.
3202 auto EmitFunc
= [&](const char *Method
) {
3203 OS
<< " switch (getKind()) {\n";
3204 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
3205 const Record
&R
= *Attr
;
3206 if (!R
.getValueAsBit("ASTNode"))
3209 OS
<< " case attr::" << R
.getName() << ":\n";
3210 OS
<< " return cast<" << R
.getName() << "Attr>(this)->" << Method
3214 OS
<< " llvm_unreachable(\"Unexpected attribute kind!\");\n";
3218 OS
<< "const char *Attr::getSpelling() const {\n";
3219 EmitFunc("getSpelling()");
3221 OS
<< "Attr *Attr::clone(ASTContext &C) const {\n";
3222 EmitFunc("clone(C)");
3224 OS
<< "void Attr::printPretty(raw_ostream &OS, "
3225 "const PrintingPolicy &Policy) const {\n";
3226 EmitFunc("printPretty(OS, Policy)");
3229 static void emitAttrList(raw_ostream
&OS
, StringRef Class
,
3230 ArrayRef
<const Record
*> AttrList
) {
3231 for (auto Cur
: AttrList
) {
3232 OS
<< Class
<< "(" << Cur
->getName() << ")\n";
3236 // Determines if an attribute has a Pragma spelling.
3237 static bool AttrHasPragmaSpelling(const Record
*R
) {
3238 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(*R
);
3239 return any_of(Spellings
, [](const FlattenedSpelling
&S
) {
3240 return S
.variety() == "Pragma";
3246 struct AttrClassDescriptor
{
3247 const char * const MacroName
;
3248 const char * const TableGenName
;
3251 } // end anonymous namespace
3253 static const AttrClassDescriptor AttrClassDescriptors
[] = {
3255 {"TYPE_ATTR", "TypeAttr"},
3256 {"STMT_ATTR", "StmtAttr"},
3257 {"DECL_OR_STMT_ATTR", "DeclOrStmtAttr"},
3258 {"INHERITABLE_ATTR", "InheritableAttr"},
3259 {"DECL_OR_TYPE_ATTR", "DeclOrTypeAttr"},
3260 {"INHERITABLE_PARAM_ATTR", "InheritableParamAttr"},
3261 {"INHERITABLE_PARAM_OR_STMT_ATTR", "InheritableParamOrStmtAttr"},
3262 {"PARAMETER_ABI_ATTR", "ParameterABIAttr"},
3263 {"HLSL_ANNOTATION_ATTR", "HLSLAnnotationAttr"}};
3265 static void emitDefaultDefine(raw_ostream
&OS
, StringRef name
,
3266 const char *superName
) {
3267 OS
<< "#ifndef " << name
<< "\n";
3268 OS
<< "#define " << name
<< "(NAME) ";
3269 if (superName
) OS
<< superName
<< "(NAME)";
3270 OS
<< "\n#endif\n\n";
3275 /// A class of attributes.
3277 const AttrClassDescriptor
&Descriptor
;
3278 const Record
*TheRecord
;
3279 AttrClass
*SuperClass
= nullptr;
3280 std::vector
<AttrClass
*> SubClasses
;
3281 std::vector
<const Record
*> Attrs
;
3283 AttrClass(const AttrClassDescriptor
&Descriptor
, const Record
*R
)
3284 : Descriptor(Descriptor
), TheRecord(R
) {}
3286 void emitDefaultDefines(raw_ostream
&OS
) const {
3287 // Default the macro unless this is a root class (i.e. Attr).
3289 emitDefaultDefine(OS
, Descriptor
.MacroName
,
3290 SuperClass
->Descriptor
.MacroName
);
3294 void emitUndefs(raw_ostream
&OS
) const {
3295 OS
<< "#undef " << Descriptor
.MacroName
<< "\n";
3298 void emitAttrList(raw_ostream
&OS
) const {
3299 for (auto SubClass
: SubClasses
) {
3300 SubClass
->emitAttrList(OS
);
3303 ::emitAttrList(OS
, Descriptor
.MacroName
, Attrs
);
3306 void classifyAttrOnRoot(const Record
*Attr
) {
3307 bool result
= classifyAttr(Attr
);
3308 assert(result
&& "failed to classify on root"); (void) result
;
3311 void emitAttrRange(raw_ostream
&OS
) const {
3312 OS
<< "ATTR_RANGE(" << Descriptor
.TableGenName
3313 << ", " << getFirstAttr()->getName()
3314 << ", " << getLastAttr()->getName() << ")\n";
3318 bool classifyAttr(const Record
*Attr
) {
3319 // Check all the subclasses.
3320 for (auto SubClass
: SubClasses
) {
3321 if (SubClass
->classifyAttr(Attr
))
3325 // It's not more specific than this class, but it might still belong here.
3326 if (Attr
->isSubClassOf(TheRecord
)) {
3327 Attrs
.push_back(Attr
);
3334 const Record
*getFirstAttr() const {
3335 if (!SubClasses
.empty())
3336 return SubClasses
.front()->getFirstAttr();
3337 return Attrs
.front();
3340 const Record
*getLastAttr() const {
3342 return Attrs
.back();
3343 return SubClasses
.back()->getLastAttr();
3347 /// The entire hierarchy of attribute classes.
3348 class AttrClassHierarchy
{
3349 std::vector
<std::unique_ptr
<AttrClass
>> Classes
;
3352 AttrClassHierarchy(const RecordKeeper
&Records
) {
3353 // Find records for all the classes.
3354 for (auto &Descriptor
: AttrClassDescriptors
) {
3355 const Record
*ClassRecord
= Records
.getClass(Descriptor
.TableGenName
);
3356 AttrClass
*Class
= new AttrClass(Descriptor
, ClassRecord
);
3357 Classes
.emplace_back(Class
);
3360 // Link up the hierarchy.
3361 for (auto &Class
: Classes
) {
3362 if (AttrClass
*SuperClass
= findSuperClass(Class
->TheRecord
)) {
3363 Class
->SuperClass
= SuperClass
;
3364 SuperClass
->SubClasses
.push_back(Class
.get());
3369 for (auto i
= Classes
.begin(), e
= Classes
.end(); i
!= e
; ++i
) {
3370 assert((i
== Classes
.begin()) == ((*i
)->SuperClass
== nullptr) &&
3371 "only the first class should be a root class!");
3376 void emitDefaultDefines(raw_ostream
&OS
) const {
3377 for (auto &Class
: Classes
) {
3378 Class
->emitDefaultDefines(OS
);
3382 void emitUndefs(raw_ostream
&OS
) const {
3383 for (auto &Class
: Classes
) {
3384 Class
->emitUndefs(OS
);
3388 void emitAttrLists(raw_ostream
&OS
) const {
3389 // Just start from the root class.
3390 Classes
[0]->emitAttrList(OS
);
3393 void emitAttrRanges(raw_ostream
&OS
) const {
3394 for (auto &Class
: Classes
)
3395 Class
->emitAttrRange(OS
);
3398 void classifyAttr(const Record
*Attr
) {
3399 // Add the attribute to the root class.
3400 Classes
[0]->classifyAttrOnRoot(Attr
);
3404 AttrClass
*findClassByRecord(const Record
*R
) const {
3405 for (auto &Class
: Classes
) {
3406 if (Class
->TheRecord
== R
)
3412 AttrClass
*findSuperClass(const Record
*R
) const {
3413 // TableGen flattens the superclass list, so we just need to walk it
3415 auto SuperClasses
= R
->getSuperClasses();
3416 for (signed i
= 0, e
= SuperClasses
.size(); i
!= e
; ++i
) {
3417 auto SuperClass
= findClassByRecord(SuperClasses
[e
- i
- 1].first
);
3418 if (SuperClass
) return SuperClass
;
3424 } // end anonymous namespace
3428 // Emits the enumeration list for attributes.
3429 void EmitClangAttrList(const RecordKeeper
&Records
, raw_ostream
&OS
) {
3430 emitSourceFileHeader("List of all attributes that Clang recognizes", OS
,
3433 AttrClassHierarchy
Hierarchy(Records
);
3435 // Add defaulting macro definitions.
3436 Hierarchy
.emitDefaultDefines(OS
);
3437 emitDefaultDefine(OS
, "PRAGMA_SPELLING_ATTR", nullptr);
3439 std::vector
<const Record
*> PragmaAttrs
;
3440 for (auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
3441 if (!Attr
->getValueAsBit("ASTNode"))
3444 // Add the attribute to the ad-hoc groups.
3445 if (AttrHasPragmaSpelling(Attr
))
3446 PragmaAttrs
.push_back(Attr
);
3448 // Place it in the hierarchy.
3449 Hierarchy
.classifyAttr(Attr
);
3452 // Emit the main attribute list.
3453 Hierarchy
.emitAttrLists(OS
);
3455 // Emit the ad hoc groups.
3456 emitAttrList(OS
, "PRAGMA_SPELLING_ATTR", PragmaAttrs
);
3458 // Emit the attribute ranges.
3459 OS
<< "#ifdef ATTR_RANGE\n";
3460 Hierarchy
.emitAttrRanges(OS
);
3461 OS
<< "#undef ATTR_RANGE\n";
3464 Hierarchy
.emitUndefs(OS
);
3465 OS
<< "#undef PRAGMA_SPELLING_ATTR\n";
3468 // Emits the enumeration list for attributes.
3469 void EmitClangAttrSubjectMatchRuleList(const RecordKeeper
&Records
,
3471 emitSourceFileHeader(
3472 "List of all attribute subject matching rules that Clang recognizes", OS
,
3474 PragmaClangAttributeSupport
&PragmaAttributeSupport
=
3475 getPragmaAttributeSupport(Records
);
3476 emitDefaultDefine(OS
, "ATTR_MATCH_RULE", nullptr);
3477 PragmaAttributeSupport
.emitMatchRuleList(OS
);
3478 OS
<< "#undef ATTR_MATCH_RULE\n";
3481 // Emits the code to read an attribute from a precompiled header.
3482 void EmitClangAttrPCHRead(const RecordKeeper
&Records
, raw_ostream
&OS
) {
3483 emitSourceFileHeader("Attribute deserialization code", OS
, Records
);
3485 const Record
*InhClass
= Records
.getClass("InheritableAttr");
3486 std::vector
<const Record
*> ArgRecords
;
3487 std::vector
<std::unique_ptr
<Argument
>> Args
;
3488 std::unique_ptr
<VariadicExprArgument
> DelayedArgs
;
3490 OS
<< " switch (Kind) {\n";
3491 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
3492 const Record
&R
= *Attr
;
3493 if (!R
.getValueAsBit("ASTNode"))
3496 OS
<< " case attr::" << R
.getName() << ": {\n";
3497 if (R
.isSubClassOf(InhClass
))
3498 OS
<< " bool isInherited = Record.readInt();\n";
3499 OS
<< " bool isImplicit = Record.readInt();\n";
3500 OS
<< " bool isPackExpansion = Record.readInt();\n";
3501 DelayedArgs
= nullptr;
3502 if (Attr
->getValueAsBit("AcceptsExprPack")) {
3504 std::make_unique
<VariadicExprArgument
>("DelayedArgs", R
.getName());
3505 DelayedArgs
->writePCHReadDecls(OS
);
3507 ArgRecords
= R
.getValueAsListOfDefs("Args");
3509 for (const auto *Arg
: ArgRecords
) {
3510 Args
.emplace_back(createArgument(*Arg
, R
.getName()));
3511 Args
.back()->writePCHReadDecls(OS
);
3513 OS
<< " New = new (Context) " << R
.getName() << "Attr(Context, Info";
3514 for (auto const &ri
: Args
) {
3516 ri
->writePCHReadArgs(OS
);
3519 if (R
.isSubClassOf(InhClass
))
3520 OS
<< " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
3521 OS
<< " New->setImplicit(isImplicit);\n";
3522 OS
<< " New->setPackExpansion(isPackExpansion);\n";
3524 OS
<< " cast<" << R
.getName()
3525 << "Attr>(New)->setDelayedArgs(Context, ";
3526 DelayedArgs
->writePCHReadArgs(OS
);
3535 // Emits the code to write an attribute to a precompiled header.
3536 void EmitClangAttrPCHWrite(const RecordKeeper
&Records
, raw_ostream
&OS
) {
3537 emitSourceFileHeader("Attribute serialization code", OS
, Records
);
3539 const Record
*InhClass
= Records
.getClass("InheritableAttr");
3540 OS
<< " switch (A->getKind()) {\n";
3541 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
3542 const Record
&R
= *Attr
;
3543 if (!R
.getValueAsBit("ASTNode"))
3545 OS
<< " case attr::" << R
.getName() << ": {\n";
3546 std::vector
<const Record
*> Args
= R
.getValueAsListOfDefs("Args");
3547 if (R
.isSubClassOf(InhClass
) || !Args
.empty())
3548 OS
<< " const auto *SA = cast<" << R
.getName()
3550 if (R
.isSubClassOf(InhClass
))
3551 OS
<< " Record.push_back(SA->isInherited());\n";
3552 OS
<< " Record.push_back(A->isImplicit());\n";
3553 OS
<< " Record.push_back(A->isPackExpansion());\n";
3554 if (Attr
->getValueAsBit("AcceptsExprPack"))
3555 VariadicExprArgument("DelayedArgs", R
.getName()).writePCHWrite(OS
);
3557 for (const auto *Arg
: Args
)
3558 createArgument(*Arg
, R
.getName())->writePCHWrite(OS
);
3565 } // namespace clang
3567 // Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
3568 // parameter with only a single check type, if applicable.
3569 static bool GenerateTargetSpecificAttrCheck(const Record
*R
, std::string
&Test
,
3570 std::string
*FnName
,
3572 StringRef CheckAgainst
,
3574 if (!R
->isValueUnset(ListName
)) {
3576 std::vector
<StringRef
> Items
= R
->getValueAsListOfStrings(ListName
);
3577 for (auto I
= Items
.begin(), E
= Items
.end(); I
!= E
; ++I
) {
3578 StringRef Part
= *I
;
3579 Test
+= CheckAgainst
;
3594 // Generate a conditional expression to check if the current target satisfies
3595 // the conditions for a TargetSpecificAttr record, and append the code for
3596 // those checks to the Test string. If the FnName string pointer is non-null,
3597 // append a unique suffix to distinguish this set of target checks from other
3598 // TargetSpecificAttr records.
3599 static bool GenerateTargetSpecificAttrChecks(const Record
*R
,
3600 std::vector
<StringRef
> &Arches
,
3602 std::string
*FnName
) {
3603 bool AnyTargetChecks
= false;
3605 // It is assumed that there will be an Triple object
3606 // named "T" and a TargetInfo object named "Target" within
3607 // scope that can be used to determine whether the attribute exists in
3610 // If one or more architectures is specified, check those. Arches are handled
3611 // differently because GenerateTargetRequirements needs to combine the list
3613 if (!Arches
.empty()) {
3614 AnyTargetChecks
= true;
3616 for (auto I
= Arches
.begin(), E
= Arches
.end(); I
!= E
; ++I
) {
3617 StringRef Part
= *I
;
3618 Test
+= "T.getArch() == llvm::Triple::";
3628 // If the attribute is specific to particular OSes, check those.
3629 AnyTargetChecks
|= GenerateTargetSpecificAttrCheck(
3630 R
, Test
, FnName
, "OSes", "T.getOS()", "llvm::Triple::");
3632 // If one or more object formats is specified, check those.
3634 GenerateTargetSpecificAttrCheck(R
, Test
, FnName
, "ObjectFormats",
3635 "T.getObjectFormat()", "llvm::Triple::");
3637 // If custom code is specified, emit it.
3638 StringRef Code
= R
->getValueAsString("CustomCode");
3639 if (!Code
.empty()) {
3640 AnyTargetChecks
= true;
3646 return AnyTargetChecks
;
3649 static void GenerateHasAttrSpellingStringSwitch(
3650 ArrayRef
<std::pair
<const Record
*, FlattenedSpelling
>> Attrs
,
3651 raw_ostream
&OS
, StringRef Variety
, StringRef Scope
= "") {
3652 for (const auto &[Attr
, Spelling
] : Attrs
) {
3653 // C++11-style attributes have specific version information associated with
3654 // them. If the attribute has no scope, the version information must not
3655 // have the default value (1), as that's incorrect. Instead, the unscoped
3656 // attribute version information should be taken from the SD-6 standing
3657 // document, which can be found at:
3658 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3660 // C23-style attributes have the same kind of version information
3661 // associated with them. The unscoped attribute version information should
3662 // be taken from the specification of the attribute in the C Standard.
3664 // Clang-specific attributes have the same kind of version information
3665 // associated with them. This version is typically the default value (1).
3666 // These version values are clang-specific and should typically be
3667 // incremented once the attribute changes its syntax and/or semantics in a
3668 // a way that is impactful to the end user.
3671 assert(Spelling
.variety() == Variety
);
3672 std::string Name
= "";
3673 if (Spelling
.nameSpace().empty() || Scope
== Spelling
.nameSpace()) {
3674 Name
= Spelling
.name();
3675 Version
= static_cast<int>(
3676 Spelling
.getSpellingRecord().getValueAsInt("Version"));
3677 // Verify that explicitly specified CXX11 and C23 spellings (i.e.
3678 // not inferred from Clang/GCC spellings) have a version that's
3679 // different from the default (1).
3680 bool RequiresValidVersion
=
3681 (Variety
== "CXX11" || Variety
== "C23") &&
3682 Spelling
.getSpellingRecord().getValueAsString("Variety") == Variety
;
3683 if (RequiresValidVersion
&& Scope
.empty() && Version
== 1)
3684 PrintError(Spelling
.getSpellingRecord().getLoc(),
3685 "Standard attributes must have "
3686 "valid version information.");
3690 if (Attr
->isSubClassOf("TargetSpecificAttr")) {
3691 const Record
*R
= Attr
->getValueAsDef("Target");
3692 std::vector
<StringRef
> Arches
= R
->getValueAsListOfStrings("Arches");
3693 GenerateTargetSpecificAttrChecks(R
, Arches
, Test
, nullptr);
3694 } else if (!Attr
->getValueAsListOfDefs("TargetSpecificSpellings").empty()) {
3695 // Add target checks if this spelling is target-specific.
3696 for (const auto &TargetSpelling
:
3697 Attr
->getValueAsListOfDefs("TargetSpecificSpellings")) {
3698 // Find spelling that matches current scope and name.
3699 for (const auto &Spelling
: GetFlattenedSpellings(*TargetSpelling
)) {
3700 if (Scope
== Spelling
.nameSpace() && Name
== Spelling
.name()) {
3701 const Record
*Target
= TargetSpelling
->getValueAsDef("Target");
3702 std::vector
<StringRef
> Arches
=
3703 Target
->getValueAsListOfStrings("Arches");
3704 GenerateTargetSpecificAttrChecks(Target
, Arches
, Test
,
3705 /*FnName=*/nullptr);
3712 std::string TestStr
= !Test
.empty()
3713 ? Test
+ " ? " + itostr(Version
) + " : 0"
3715 if (Scope
.empty() || Scope
== Spelling
.nameSpace())
3716 OS
<< " .Case(\"" << Spelling
.name() << "\", " << TestStr
<< ")\n";
3718 OS
<< " .Default(0);\n";
3723 // Emits list of regular keyword attributes with info about their arguments.
3724 void EmitClangRegularKeywordAttributeInfo(const RecordKeeper
&Records
,
3726 emitSourceFileHeader(
3727 "A list of regular keyword attributes generated from the attribute"
3730 // Assume for now that the same token is not used in multiple regular
3731 // keyword attributes.
3732 for (auto *R
: Records
.getAllDerivedDefinitions("Attr"))
3733 for (const auto &S
: GetFlattenedSpellings(*R
)) {
3734 if (!isRegularKeywordAttribute(S
))
3736 std::vector
<const Record
*> Args
= R
->getValueAsListOfDefs("Args");
3737 bool HasArgs
= any_of(
3738 Args
, [](const Record
*Arg
) { return !Arg
->getValueAsBit("Fake"); });
3740 OS
<< "KEYWORD_ATTRIBUTE("
3741 << S
.getSpellingRecord().getValueAsString("Name") << ", "
3742 << (HasArgs
? "true" : "false") << ", )\n";
3744 OS
<< "#undef KEYWORD_ATTRIBUTE\n";
3747 // Emits the list of spellings for attributes.
3748 void EmitClangAttrHasAttrImpl(const RecordKeeper
&Records
, raw_ostream
&OS
) {
3749 emitSourceFileHeader("Code to implement the __has_attribute logic", OS
,
3752 // Separate all of the attributes out into four group: generic, C++11, GNU,
3753 // and declspecs. Then generate a big switch statement for each of them.
3754 using PairTy
= std::pair
<const Record
*, FlattenedSpelling
>;
3755 std::vector
<PairTy
> Declspec
, Microsoft
, GNU
, Pragma
, HLSLAnnotation
;
3756 std::map
<StringRef
, std::vector
<PairTy
>> CXX
, C23
;
3758 // Walk over the list of all attributes, and split them out based on the
3759 // spelling variety.
3760 for (auto *R
: Records
.getAllDerivedDefinitions("Attr")) {
3761 for (const FlattenedSpelling
&SI
: GetFlattenedSpellings(*R
)) {
3762 StringRef Variety
= SI
.variety();
3763 if (Variety
== "GNU")
3764 GNU
.emplace_back(R
, SI
);
3765 else if (Variety
== "Declspec")
3766 Declspec
.emplace_back(R
, SI
);
3767 else if (Variety
== "Microsoft")
3768 Microsoft
.emplace_back(R
, SI
);
3769 else if (Variety
== "CXX11")
3770 CXX
[SI
.nameSpace()].emplace_back(R
, SI
);
3771 else if (Variety
== "C23")
3772 C23
[SI
.nameSpace()].emplace_back(R
, SI
);
3773 else if (Variety
== "Pragma")
3774 Pragma
.emplace_back(R
, SI
);
3775 else if (Variety
== "HLSLAnnotation")
3776 HLSLAnnotation
.emplace_back(R
, SI
);
3780 OS
<< "const llvm::Triple &T = Target.getTriple();\n";
3781 OS
<< "switch (Syntax) {\n";
3782 OS
<< "case AttributeCommonInfo::Syntax::AS_GNU:\n";
3783 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3784 GenerateHasAttrSpellingStringSwitch(GNU
, OS
, "GNU");
3785 OS
<< "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
3786 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3787 GenerateHasAttrSpellingStringSwitch(Declspec
, OS
, "Declspec");
3788 OS
<< "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
3789 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3790 GenerateHasAttrSpellingStringSwitch(Microsoft
, OS
, "Microsoft");
3791 OS
<< "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
3792 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3793 GenerateHasAttrSpellingStringSwitch(Pragma
, OS
, "Pragma");
3794 OS
<< "case AttributeCommonInfo::Syntax::AS_HLSLAnnotation:\n";
3795 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3796 GenerateHasAttrSpellingStringSwitch(HLSLAnnotation
, OS
, "HLSLAnnotation");
3797 auto fn
= [&OS
](StringRef Spelling
,
3798 const std::map
<StringRef
, std::vector
<PairTy
>> &Map
) {
3799 OS
<< "case AttributeCommonInfo::Syntax::AS_" << Spelling
<< ": {\n";
3800 // C++11-style attributes are further split out based on the Scope.
3801 ListSeparator
LS(" else ");
3802 for (const auto &[Scope
, List
] : Map
) {
3804 OS
<< "if (ScopeName == \"" << Scope
<< "\") {\n";
3805 OS
<< " return llvm::StringSwitch<int>(Name)\n";
3806 GenerateHasAttrSpellingStringSwitch(List
, OS
, Spelling
, Scope
);
3809 OS
<< "\n} break;\n";
3813 OS
<< "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
3814 OS
<< "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
3815 OS
<< " llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
3816 OS
<< " return 0;\n";
3817 OS
<< "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
3818 OS
<< " llvm_unreachable (\"hasAttribute not supported for "
3819 "AS_Implicit\");\n";
3820 OS
<< " return 0;\n";
3825 void EmitClangAttrSpellingListIndex(const RecordKeeper
&Records
,
3827 emitSourceFileHeader("Code to translate different attribute spellings into "
3828 "internal identifiers",
3831 OS
<< " switch (getParsedKind()) {\n";
3832 OS
<< " case IgnoredAttribute:\n";
3833 OS
<< " case UnknownAttribute:\n";
3834 OS
<< " case NoSemaHandlerAttribute:\n";
3835 OS
<< " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
3837 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
3838 for (const auto &I
: Attrs
) {
3839 const Record
&R
= *I
.second
;
3840 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
3841 OS
<< " case AT_" << I
.first
<< ": {\n";
3843 // If there are none or one spelling to check, resort to the default
3844 // behavior of returning index as 0.
3845 if (Spellings
.size() <= 1) {
3846 OS
<< " return 0;\n"
3852 std::vector
<StringRef
> Names
;
3853 llvm::transform(Spellings
, std::back_inserter(Names
),
3854 [](const FlattenedSpelling
&FS
) { return FS
.name(); });
3856 Names
.erase(llvm::unique(Names
), Names
.end());
3858 for (const auto &[Idx
, FS
] : enumerate(Spellings
)) {
3860 if (Names
.size() > 1) {
3861 SmallVector
<StringRef
, 6> SameLenNames
;
3862 StringRef FSName
= FS
.name();
3864 Names
, std::back_inserter(SameLenNames
),
3865 [&](StringRef N
) { return N
.size() == FSName
.size(); });
3867 if (SameLenNames
.size() == 1) {
3868 OS
<< "Name.size() == " << FS
.name().size() << " && ";
3870 // FIXME: We currently fall back to comparing entire strings if there
3871 // are 2 or more spelling names with the same length. This can be
3872 // optimized to check only for the the first differing character
3873 // between them instead.
3874 OS
<< "Name == \"" << FS
.name() << "\""
3879 OS
<< "getSyntax() == AttributeCommonInfo::AS_" << FS
.variety()
3880 << " && ComputedScope == ";
3881 if (FS
.nameSpace() == "")
3882 OS
<< "AttributeCommonInfo::Scope::NONE";
3884 OS
<< "AttributeCommonInfo::Scope::" + FS
.nameSpace().upper();
3887 << " return " << Idx
<< ";\n";
3898 // Emits code used by RecursiveASTVisitor to visit attributes
3899 void EmitClangAttrASTVisitor(const RecordKeeper
&Records
, raw_ostream
&OS
) {
3900 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS
,
3902 // Write method declarations for Traverse* methods.
3903 // We emit this here because we only generate methods for attributes that
3904 // are declared as ASTNodes.
3905 OS
<< "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
3906 ArrayRef
<const Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
3907 for (const auto *Attr
: Attrs
) {
3908 const Record
&R
= *Attr
;
3909 if (!R
.getValueAsBit("ASTNode"))
3911 OS
<< " bool Traverse"
3912 << R
.getName() << "Attr(" << R
.getName() << "Attr *A);\n";
3914 << R
.getName() << "Attr(" << R
.getName() << "Attr *A) {\n"
3915 << " return true; \n"
3918 OS
<< "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
3920 // Write individual Traverse* methods for each attribute class.
3921 for (const auto *Attr
: Attrs
) {
3922 const Record
&R
= *Attr
;
3923 if (!R
.getValueAsBit("ASTNode"))
3926 OS
<< "template <typename Derived>\n"
3927 << "bool VISITORCLASS<Derived>::Traverse"
3928 << R
.getName() << "Attr(" << R
.getName() << "Attr *A) {\n"
3929 << " if (!getDerived().VisitAttr(A))\n"
3930 << " return false;\n"
3931 << " if (!getDerived().Visit" << R
.getName() << "Attr(A))\n"
3932 << " return false;\n";
3934 for (const auto *Arg
: R
.getValueAsListOfDefs("Args"))
3935 createArgument(*Arg
, R
.getName())->writeASTVisitorTraversal(OS
);
3937 if (Attr
->getValueAsBit("AcceptsExprPack"))
3938 VariadicExprArgument("DelayedArgs", R
.getName())
3939 .writeASTVisitorTraversal(OS
);
3941 OS
<< " return true;\n";
3945 // Write generic Traverse routine
3946 OS
<< "template <typename Derived>\n"
3947 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
3949 << " return true;\n"
3951 << " switch (A->getKind()) {\n";
3953 for (const auto *Attr
: Attrs
) {
3954 const Record
&R
= *Attr
;
3955 if (!R
.getValueAsBit("ASTNode"))
3958 OS
<< " case attr::" << R
.getName() << ":\n"
3959 << " return getDerived().Traverse" << R
.getName() << "Attr("
3960 << "cast<" << R
.getName() << "Attr>(A));\n";
3962 OS
<< " }\n"; // end switch
3963 OS
<< " llvm_unreachable(\"bad attribute kind\");\n";
3964 OS
<< "}\n"; // end function
3965 OS
<< "#endif // ATTR_VISITOR_DECLS_ONLY\n";
3969 EmitClangAttrTemplateInstantiateHelper(ArrayRef
<const Record
*> Attrs
,
3970 raw_ostream
&OS
, bool AppliesToDecl
) {
3972 OS
<< " switch (At->getKind()) {\n";
3973 for (const auto *Attr
: Attrs
) {
3974 const Record
&R
= *Attr
;
3975 if (!R
.getValueAsBit("ASTNode"))
3977 OS
<< " case attr::" << R
.getName() << ": {\n";
3978 bool ShouldClone
= R
.getValueAsBit("Clone") &&
3980 R
.getValueAsBit("MeaningfulToClassTemplateDefinition"));
3983 OS
<< " return nullptr;\n";
3988 OS
<< " const auto *A = cast<"
3989 << R
.getName() << "Attr>(At);\n";
3990 bool TDependent
= R
.getValueAsBit("TemplateDependent");
3993 OS
<< " return A->clone(C);\n";
3998 std::vector
<const Record
*> ArgRecords
= R
.getValueAsListOfDefs("Args");
3999 std::vector
<std::unique_ptr
<Argument
>> Args
;
4000 Args
.reserve(ArgRecords
.size());
4002 for (const auto *ArgRecord
: ArgRecords
)
4003 Args
.emplace_back(createArgument(*ArgRecord
, R
.getName()));
4005 for (auto const &ai
: Args
)
4006 ai
->writeTemplateInstantiation(OS
);
4008 OS
<< " return new (C) " << R
.getName() << "Attr(C, *A";
4009 for (auto const &ai
: Args
) {
4011 ai
->writeTemplateInstantiationArgs(OS
);
4016 OS
<< " } // end switch\n"
4017 << " llvm_unreachable(\"Unknown attribute!\");\n"
4018 << " return nullptr;\n";
4021 // Emits code to instantiate dependent attributes on templates.
4022 void EmitClangAttrTemplateInstantiate(const RecordKeeper
&Records
,
4024 emitSourceFileHeader("Template instantiation code for attributes", OS
,
4027 ArrayRef
<const Record
*> Attrs
= Records
.getAllDerivedDefinitions("Attr");
4029 OS
<< "namespace clang {\n"
4030 << "namespace sema {\n\n"
4031 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
4033 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4034 EmitClangAttrTemplateInstantiateHelper(Attrs
, OS
, /*AppliesToDecl*/false);
4036 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
4037 << " ASTContext &C, Sema &S,\n"
4038 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4039 EmitClangAttrTemplateInstantiateHelper(Attrs
, OS
, /*AppliesToDecl*/true);
4041 << "} // end namespace sema\n"
4042 << "} // end namespace clang\n";
4045 // Emits the list of parsed attributes.
4046 void EmitClangAttrParsedAttrList(const RecordKeeper
&Records
, raw_ostream
&OS
) {
4047 emitSourceFileHeader("List of all attributes that Clang recognizes", OS
,
4050 OS
<< "#ifndef PARSED_ATTR\n";
4051 OS
<< "#define PARSED_ATTR(NAME) NAME\n";
4054 ParsedAttrMap Names
= getParsedAttrList(Records
);
4055 for (const auto &I
: Names
) {
4056 OS
<< "PARSED_ATTR(" << I
.first
<< ")\n";
4060 static bool isArgVariadic(const Record
&R
, StringRef AttrName
) {
4061 return createArgument(R
, AttrName
)->isVariadic();
4064 static void emitArgInfo(const Record
&R
, raw_ostream
&OS
) {
4065 // This function will count the number of arguments specified for the
4066 // attribute and emit the number of required arguments followed by the
4067 // number of optional arguments.
4068 unsigned ArgCount
= 0, OptCount
= 0, ArgMemberCount
= 0;
4069 bool HasVariadic
= false;
4070 for (const auto *Arg
: R
.getValueAsListOfDefs("Args")) {
4071 // If the arg is fake, it's the user's job to supply it: general parsing
4072 // logic shouldn't need to know anything about it.
4073 if (Arg
->getValueAsBit("Fake"))
4075 Arg
->getValueAsBit("Optional") ? ++OptCount
: ++ArgCount
;
4077 if (!HasVariadic
&& isArgVariadic(*Arg
, R
.getName()))
4081 // If there is a variadic argument, we will set the optional argument count
4082 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
4083 OS
<< " /*NumArgs=*/" << ArgCount
<< ",\n";
4084 OS
<< " /*OptArgs=*/" << (HasVariadic
? 15 : OptCount
) << ",\n";
4085 OS
<< " /*NumArgMembers=*/" << ArgMemberCount
<< ",\n";
4088 static std::string
GetDiagnosticSpelling(const Record
&R
) {
4089 StringRef Ret
= R
.getValueAsString("DiagSpelling");
4093 // If we couldn't find the DiagSpelling in this object, we can check to see
4094 // if the object is one that has a base, and if it is, loop up to the Base
4095 // member recursively.
4096 if (auto Base
= R
.getValueAsOptionalDef(BaseFieldName
))
4097 return GetDiagnosticSpelling(*Base
);
4102 static std::string
CalculateDiagnostic(const Record
&S
) {
4103 // If the SubjectList object has a custom diagnostic associated with it,
4104 // return that directly.
4105 const StringRef CustomDiag
= S
.getValueAsString("CustomDiag");
4106 if (!CustomDiag
.empty())
4107 return ("\"" + Twine(CustomDiag
) + "\"").str();
4109 std::vector
<std::string
> DiagList
;
4110 for (const auto *Subject
: S
.getValueAsListOfDefs("Subjects")) {
4111 const Record
&R
= *Subject
;
4112 // Get the diagnostic text from the Decl or Stmt node given.
4113 std::string V
= GetDiagnosticSpelling(R
);
4115 PrintError(R
.getLoc(),
4116 "Could not determine diagnostic spelling for the node: " +
4117 R
.getName() + "; please add one to DeclNodes.td");
4119 // The node may contain a list of elements itself, so split the elements
4120 // by a comma, and trim any whitespace.
4121 SmallVector
<StringRef
, 2> Frags
;
4122 SplitString(V
, Frags
, ",");
4123 for (auto Str
: Frags
) {
4124 DiagList
.push_back(Str
.trim().str());
4129 if (DiagList
.empty()) {
4130 PrintFatalError(S
.getLoc(),
4131 "Could not deduce diagnostic argument for Attr subjects");
4135 // FIXME: this is not particularly good for localization purposes and ideally
4136 // should be part of the diagnostics engine itself with some sort of list
4139 // A single member of the list can be returned directly.
4140 if (DiagList
.size() == 1)
4141 return '"' + DiagList
.front() + '"';
4143 if (DiagList
.size() == 2)
4144 return '"' + DiagList
[0] + " and " + DiagList
[1] + '"';
4146 // If there are more than two in the list, we serialize the first N - 1
4147 // elements with a comma. This leaves the string in the state: foo, bar,
4148 // baz (but misses quux). We can then add ", and " for the last element
4150 std::string Diag
= join(DiagList
.begin(), DiagList
.end() - 1, ", ");
4151 return '"' + Diag
+ ", and " + *(DiagList
.end() - 1) + '"';
4154 static std::string
GetSubjectWithSuffix(const Record
*R
) {
4155 const std::string B
= R
->getName().str();
4156 if (B
== "DeclBase")
4161 static std::string
functionNameForCustomAppertainsTo(const Record
&Subject
) {
4162 return "is" + Subject
.getName().str();
4165 static void GenerateCustomAppertainsTo(const Record
&Subject
, raw_ostream
&OS
) {
4166 std::string FnName
= functionNameForCustomAppertainsTo(Subject
);
4168 // If this code has already been generated, we don't need to do anything.
4169 static std::set
<std::string
> CustomSubjectSet
;
4170 auto I
= CustomSubjectSet
.find(FnName
);
4171 if (I
!= CustomSubjectSet
.end())
4174 // This only works with non-root Decls.
4175 const Record
*Base
= Subject
.getValueAsDef(BaseFieldName
);
4177 // Not currently support custom subjects within custom subjects.
4178 if (Base
->isSubClassOf("SubsetSubject")) {
4179 PrintFatalError(Subject
.getLoc(),
4180 "SubsetSubjects within SubsetSubjects is not supported");
4184 OS
<< "static bool " << FnName
<< "(const Decl *D) {\n";
4185 OS
<< " if (const auto *S = dyn_cast<";
4186 OS
<< GetSubjectWithSuffix(Base
);
4188 OS
<< " return " << Subject
.getValueAsString("CheckCode") << ";\n";
4189 OS
<< " return false;\n";
4192 CustomSubjectSet
.insert(FnName
);
4195 static void GenerateAppertainsTo(const Record
&Attr
, raw_ostream
&OS
) {
4196 // If the attribute does not contain a Subjects definition, then use the
4197 // default appertainsTo logic.
4198 if (Attr
.isValueUnset("Subjects"))
4201 const Record
*SubjectObj
= Attr
.getValueAsDef("Subjects");
4202 std::vector
<const Record
*> Subjects
=
4203 SubjectObj
->getValueAsListOfDefs("Subjects");
4205 // If the list of subjects is empty, it is assumed that the attribute
4206 // appertains to everything.
4207 if (Subjects
.empty())
4210 bool Warn
= SubjectObj
->getValueAsDef("Diag")->getValueAsBit("Warn");
4212 // Split the subjects into declaration subjects and statement subjects.
4213 // FIXME: subset subjects are added to the declaration list until there are
4214 // enough statement attributes with custom subject needs to warrant
4215 // the implementation effort.
4216 std::vector
<const Record
*> DeclSubjects
, StmtSubjects
;
4217 copy_if(Subjects
, std::back_inserter(DeclSubjects
), [](const Record
*R
) {
4218 return R
->isSubClassOf("SubsetSubject") || !R
->isSubClassOf("StmtNode");
4220 copy_if(Subjects
, std::back_inserter(StmtSubjects
),
4221 [](const Record
*R
) { return R
->isSubClassOf("StmtNode"); });
4223 // We should have sorted all of the subjects into two lists.
4224 // FIXME: this assertion will be wrong if we ever add type attribute subjects.
4225 assert(DeclSubjects
.size() + StmtSubjects
.size() == Subjects
.size());
4227 if (DeclSubjects
.empty()) {
4228 // If there are no decl subjects but there are stmt subjects, diagnose
4229 // trying to apply a statement attribute to a declaration.
4230 if (!StmtSubjects
.empty()) {
4231 OS
<< "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
4232 OS
<< "const Decl *D) const override {\n";
4233 OS
<< " S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
4234 OS
<< " << AL << AL.isRegularKeywordAttribute() << "
4235 "D->getLocation();\n";
4236 OS
<< " return false;\n";
4240 // Otherwise, generate an appertainsTo check specific to this attribute
4241 // which checks all of the given subjects against the Decl passed in.
4242 OS
<< "bool diagAppertainsToDecl(Sema &S, ";
4243 OS
<< "const ParsedAttr &Attr, const Decl *D) const override {\n";
4245 for (auto I
= DeclSubjects
.begin(), E
= DeclSubjects
.end(); I
!= E
; ++I
) {
4246 // If the subject has custom code associated with it, use the generated
4247 // function for it. The function cannot be inlined into this check (yet)
4248 // because it requires the subject to be of a specific type, and were that
4249 // information inlined here, it would not support an attribute with
4250 // multiple custom subjects.
4251 if ((*I
)->isSubClassOf("SubsetSubject"))
4252 OS
<< "!" << functionNameForCustomAppertainsTo(**I
) << "(D)";
4254 OS
<< "!isa<" << GetSubjectWithSuffix(*I
) << ">(D)";
4260 OS
<< " S.Diag(Attr.getLoc(), diag::";
4261 OS
<< (Warn
? "warn_attribute_wrong_decl_type_str"
4262 : "err_attribute_wrong_decl_type_str");
4264 OS
<< " << Attr << Attr.isRegularKeywordAttribute() << ";
4265 OS
<< CalculateDiagnostic(*SubjectObj
) << ";\n";
4266 OS
<< " return false;\n";
4268 OS
<< " return true;\n";
4272 if (StmtSubjects
.empty()) {
4273 // If there are no stmt subjects but there are decl subjects, diagnose
4274 // trying to apply a declaration attribute to a statement.
4275 if (!DeclSubjects
.empty()) {
4276 OS
<< "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
4277 OS
<< "const Stmt *St) const override {\n";
4278 OS
<< " S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
4279 OS
<< " << AL << AL.isRegularKeywordAttribute() << "
4280 "St->getBeginLoc();\n";
4281 OS
<< " return false;\n";
4285 // Now, do the same for statements.
4286 OS
<< "bool diagAppertainsToStmt(Sema &S, ";
4287 OS
<< "const ParsedAttr &Attr, const Stmt *St) const override {\n";
4289 for (auto I
= StmtSubjects
.begin(), E
= StmtSubjects
.end(); I
!= E
; ++I
) {
4290 OS
<< "!isa<" << (*I
)->getName() << ">(St)";
4295 OS
<< " S.Diag(Attr.getLoc(), diag::";
4296 OS
<< (Warn
? "warn_attribute_wrong_decl_type_str"
4297 : "err_attribute_wrong_decl_type_str");
4299 OS
<< " << Attr << Attr.isRegularKeywordAttribute() << ";
4300 OS
<< CalculateDiagnostic(*SubjectObj
) << ";\n";
4301 OS
<< " return false;\n";
4303 OS
<< " return true;\n";
4308 // Generates the mutual exclusion checks. The checks for parsed attributes are
4309 // written into OS and the checks for merging declaration attributes are
4310 // written into MergeOS.
4311 static void GenerateMutualExclusionsChecks(const Record
&Attr
,
4312 const RecordKeeper
&Records
,
4314 raw_ostream
&MergeDeclOS
,
4315 raw_ostream
&MergeStmtOS
) {
4316 // We don't do any of this magic for type attributes yet.
4317 if (Attr
.isSubClassOf("TypeAttr"))
4320 // This means the attribute is either a statement attribute, a decl
4321 // attribute, or both; find out which.
4322 bool CurAttrIsStmtAttr
= Attr
.isSubClassOf("StmtAttr") ||
4323 Attr
.isSubClassOf("DeclOrStmtAttr") ||
4324 Attr
.isSubClassOf("InheritableParamOrStmtAttr");
4325 bool CurAttrIsDeclAttr
= !CurAttrIsStmtAttr
||
4326 Attr
.isSubClassOf("DeclOrStmtAttr") ||
4327 Attr
.isSubClassOf("InheritableParamOrStmtAttr");
4329 std::vector
<std::string
> DeclAttrs
, StmtAttrs
;
4331 // Find all of the definitions that inherit from MutualExclusions and include
4332 // the given attribute in the list of exclusions to generate the
4333 // diagMutualExclusion() check.
4334 for (const Record
*Exclusion
:
4335 Records
.getAllDerivedDefinitions("MutualExclusions")) {
4336 std::vector
<const Record
*> MutuallyExclusiveAttrs
=
4337 Exclusion
->getValueAsListOfDefs("Exclusions");
4338 auto IsCurAttr
= [Attr
](const Record
*R
) {
4339 return R
->getName() == Attr
.getName();
4341 if (any_of(MutuallyExclusiveAttrs
, IsCurAttr
)) {
4342 // This list of exclusions includes the attribute we're looking for, so
4343 // add the exclusive attributes to the proper list for checking.
4344 for (const Record
*AttrToExclude
: MutuallyExclusiveAttrs
) {
4345 if (IsCurAttr(AttrToExclude
))
4348 if (CurAttrIsStmtAttr
)
4349 StmtAttrs
.push_back((AttrToExclude
->getName() + "Attr").str());
4350 if (CurAttrIsDeclAttr
)
4351 DeclAttrs
.push_back((AttrToExclude
->getName() + "Attr").str());
4356 // If there are any decl or stmt attributes, silence -Woverloaded-virtual
4357 // warnings for them both.
4358 if (!DeclAttrs
.empty() || !StmtAttrs
.empty())
4359 OS
<< " using ParsedAttrInfo::diagMutualExclusion;\n\n";
4361 // If we discovered any decl or stmt attributes to test for, generate the
4362 // predicates for them now.
4363 if (!DeclAttrs
.empty()) {
4364 // Generate the ParsedAttrInfo subclass logic for declarations.
4365 OS
<< " bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
4366 << "const Decl *D) const override {\n";
4367 for (const std::string
&A
: DeclAttrs
) {
4368 OS
<< " if (const auto *A = D->getAttr<" << A
<< ">()) {\n";
4369 OS
<< " S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
4370 << " << AL << A << (AL.isRegularKeywordAttribute() ||"
4371 << " A->isRegularKeywordAttribute());\n";
4372 OS
<< " S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
4373 OS
<< " \nreturn false;\n";
4376 OS
<< " return true;\n";
4379 // Also generate the declaration attribute merging logic if the current
4380 // attribute is one that can be inheritted on a declaration. It is assumed
4381 // this code will be executed in the context of a function with parameters:
4382 // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
4383 // true on success).
4384 if (Attr
.isSubClassOf("InheritableAttr")) {
4385 MergeDeclOS
<< " if (const auto *Second = dyn_cast<"
4386 << (Attr
.getName() + "Attr").str() << ">(A)) {\n";
4387 for (const std::string
&A
: DeclAttrs
) {
4388 MergeDeclOS
<< " if (const auto *First = D->getAttr<" << A
4390 MergeDeclOS
<< " S.Diag(First->getLocation(), "
4391 << "diag::err_attributes_are_not_compatible) << First << "
4392 << "Second << (First->isRegularKeywordAttribute() || "
4393 << "Second->isRegularKeywordAttribute());\n";
4394 MergeDeclOS
<< " S.Diag(Second->getLocation(), "
4395 << "diag::note_conflicting_attribute);\n";
4396 MergeDeclOS
<< " return false;\n";
4397 MergeDeclOS
<< " }\n";
4399 MergeDeclOS
<< " return true;\n";
4400 MergeDeclOS
<< " }\n";
4404 // Statement attributes are a bit different from declarations. With
4405 // declarations, each attribute is added to the declaration as it is
4406 // processed, and so you can look on the Decl * itself to see if there is a
4407 // conflicting attribute. Statement attributes are processed as a group
4408 // because AttributedStmt needs to tail-allocate all of the attribute nodes
4409 // at once. This means we cannot check whether the statement already contains
4410 // an attribute to check for the conflict. Instead, we need to check whether
4411 // the given list of semantic attributes contain any conflicts. It is assumed
4412 // this code will be executed in the context of a function with parameters:
4413 // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
4414 // loop which loops over the container C with a loop variable named A to
4415 // represent the current attribute to check for conflicts.
4417 // FIXME: it would be nice not to walk over the list of potential attributes
4418 // to apply to the statement more than once, but statements typically don't
4419 // have long lists of attributes on them, so re-walking the list should not
4420 // be an expensive operation.
4421 if (!StmtAttrs
.empty()) {
4422 MergeStmtOS
<< " if (const auto *Second = dyn_cast<"
4423 << (Attr
.getName() + "Attr").str() << ">(A)) {\n";
4424 MergeStmtOS
<< " auto Iter = llvm::find_if(C, [](const Attr *Check) "
4427 StmtAttrs
, [&](StringRef Name
) { MergeStmtOS
<< Name
; },
4428 [&] { MergeStmtOS
<< ", "; });
4429 MergeStmtOS
<< ">(Check); });\n";
4430 MergeStmtOS
<< " if (Iter != C.end()) {\n";
4431 MergeStmtOS
<< " S.Diag((*Iter)->getLocation(), "
4432 << "diag::err_attributes_are_not_compatible) << *Iter << "
4433 << "Second << ((*Iter)->isRegularKeywordAttribute() || "
4434 << "Second->isRegularKeywordAttribute());\n";
4435 MergeStmtOS
<< " S.Diag(Second->getLocation(), "
4436 << "diag::note_conflicting_attribute);\n";
4437 MergeStmtOS
<< " return false;\n";
4438 MergeStmtOS
<< " }\n";
4439 MergeStmtOS
<< " }\n";
4444 emitAttributeMatchRules(PragmaClangAttributeSupport
&PragmaAttributeSupport
,
4446 OS
<< "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
4447 << AttributeSubjectMatchRule::EnumName
<< " rule) {\n";
4448 OS
<< " switch (rule) {\n";
4449 for (const auto &Rule
: PragmaAttributeSupport
.Rules
) {
4450 if (Rule
.isAbstractRule()) {
4451 OS
<< " case " << Rule
.getEnumValue() << ":\n";
4452 OS
<< " assert(false && \"Abstract matcher rule isn't allowed\");\n";
4453 OS
<< " return false;\n";
4456 std::vector
<const Record
*> Subjects
= Rule
.getSubjects();
4457 assert(!Subjects
.empty() && "Missing subjects");
4458 OS
<< " case " << Rule
.getEnumValue() << ":\n";
4460 for (auto I
= Subjects
.begin(), E
= Subjects
.end(); I
!= E
; ++I
) {
4461 // If the subject has custom code associated with it, use the function
4462 // that was generated for GenerateAppertainsTo to check if the declaration
4464 if ((*I
)->isSubClassOf("SubsetSubject"))
4465 OS
<< functionNameForCustomAppertainsTo(**I
) << "(D)";
4467 OS
<< "isa<" << GetSubjectWithSuffix(*I
) << ">(D)";
4475 OS
<< " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
4479 static void GenerateLangOptRequirements(const Record
&R
,
4481 // If the attribute has an empty or unset list of language requirements,
4482 // use the default handler.
4483 std::vector
<const Record
*> LangOpts
= R
.getValueAsListOfDefs("LangOpts");
4484 if (LangOpts
.empty())
4487 OS
<< "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
4488 OS
<< " return " << GenerateTestExpression(LangOpts
) << ";\n";
4492 static void GenerateTargetRequirements(const Record
&Attr
,
4493 const ParsedAttrMap
&Dupes
,
4495 // If the attribute is not a target specific attribute, use the default
4497 if (!Attr
.isSubClassOf("TargetSpecificAttr"))
4500 // Get the list of architectures to be tested for.
4501 const Record
*R
= Attr
.getValueAsDef("Target");
4502 std::vector
<StringRef
> Arches
= R
->getValueAsListOfStrings("Arches");
4504 // If there are other attributes which share the same parsed attribute kind,
4505 // such as target-specific attributes with a shared spelling, collapse the
4506 // duplicate architectures. This is required because a shared target-specific
4507 // attribute has only one ParsedAttr::Kind enumeration value, but it
4508 // applies to multiple target architectures. In order for the attribute to be
4509 // considered valid, all of its architectures need to be included.
4510 if (!Attr
.isValueUnset("ParseKind")) {
4511 const StringRef APK
= Attr
.getValueAsString("ParseKind");
4512 for (const auto &I
: Dupes
) {
4513 if (I
.first
== APK
) {
4514 std::vector
<StringRef
> DA
=
4515 I
.second
->getValueAsDef("Target")->getValueAsListOfStrings(
4517 Arches
.insert(Arches
.end(), DA
.begin(), DA
.end());
4522 std::string FnName
= "isTarget";
4524 bool UsesT
= GenerateTargetSpecificAttrChecks(R
, Arches
, Test
, &FnName
);
4526 OS
<< "bool existsInTarget(const TargetInfo &Target) const override {\n";
4528 OS
<< " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4529 OS
<< " return " << Test
<< ";\n";
4534 GenerateSpellingTargetRequirements(const Record
&Attr
,
4535 ArrayRef
<const Record
*> TargetSpellings
,
4537 // If there are no target specific spellings, use the default target handler.
4538 if (TargetSpellings
.empty())
4543 const std::vector
<FlattenedSpelling
> SpellingList
=
4544 GetFlattenedSpellings(Attr
);
4545 for (unsigned TargetIndex
= 0; TargetIndex
< TargetSpellings
.size();
4547 const auto &TargetSpelling
= TargetSpellings
[TargetIndex
];
4548 std::vector
<FlattenedSpelling
> Spellings
=
4549 GetFlattenedSpellings(*TargetSpelling
);
4551 Test
+= "((SpellingListIndex == ";
4552 for (unsigned Index
= 0; Index
< Spellings
.size(); ++Index
) {
4553 Test
+= itostr(getSpellingListIndex(SpellingList
, Spellings
[Index
]));
4554 if (Index
!= Spellings
.size() - 1)
4555 Test
+= " ||\n SpellingListIndex == ";
4560 const Record
*Target
= TargetSpelling
->getValueAsDef("Target");
4561 std::vector
<StringRef
> Arches
= Target
->getValueAsListOfStrings("Arches");
4562 std::string FnName
= "isTargetSpelling";
4563 UsesT
|= GenerateTargetSpecificAttrChecks(Target
, Arches
, Test
, &FnName
);
4565 if (TargetIndex
!= TargetSpellings
.size() - 1)
4569 OS
<< "bool spellingExistsInTarget(const TargetInfo &Target,\n";
4570 OS
<< " const unsigned SpellingListIndex) const "
4573 OS
<< " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4574 OS
<< " return " << Test
<< ";\n", OS
<< "}\n\n";
4577 static void GenerateSpellingIndexToSemanticSpelling(const Record
&Attr
,
4579 // If the attribute does not have a semantic form, we can bail out early.
4580 if (!Attr
.getValueAsBit("ASTNode"))
4583 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attr
);
4585 // If there are zero or one spellings, or all of the spellings share the same
4586 // name, we can also bail out early.
4587 if (Spellings
.size() <= 1 || SpellingNamesAreCommon(Spellings
))
4590 // Generate the enumeration we will use for the mapping.
4591 SemanticSpellingMap SemanticToSyntacticMap
;
4592 std::string Enum
= CreateSemanticSpellings(Spellings
, SemanticToSyntacticMap
);
4593 std::string Name
= Attr
.getName().str() + "AttrSpellingMap";
4595 OS
<< "unsigned spellingIndexToSemanticSpelling(";
4596 OS
<< "const ParsedAttr &Attr) const override {\n";
4598 OS
<< " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
4599 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap
, OS
);
4603 static void GenerateHandleDeclAttribute(const Record
&Attr
, raw_ostream
&OS
) {
4604 // Only generate if Attr can be handled simply.
4605 if (!Attr
.getValueAsBit("SimpleHandler"))
4608 // Generate a function which just converts from ParsedAttr to the Attr type.
4609 OS
<< "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
4610 OS
<< "const ParsedAttr &Attr) const override {\n";
4611 OS
<< " D->addAttr(::new (S.Context) " << Attr
.getName();
4612 OS
<< "Attr(S.Context, Attr));\n";
4613 OS
<< " return AttributeApplied;\n";
4617 static bool isParamExpr(const Record
*Arg
) {
4618 return !Arg
->getSuperClasses().empty() &&
4619 StringSwitch
<bool>(Arg
->getSuperClasses().back().first
->getName())
4620 .Case("ExprArgument", true)
4621 .Case("VariadicExprArgument", true)
4625 static void GenerateIsParamExpr(const Record
&Attr
, raw_ostream
&OS
) {
4626 OS
<< "bool isParamExpr(size_t N) const override {\n";
4628 auto Args
= Attr
.getValueAsListOfDefs("Args");
4629 for (size_t I
= 0; I
< Args
.size(); ++I
)
4630 if (isParamExpr(Args
[I
]))
4631 OS
<< "(N == " << I
<< ") || ";
4636 static void GenerateHandleAttrWithDelayedArgs(const RecordKeeper
&Records
,
4638 OS
<< "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
4639 OS
<< "const ParsedAttr &Attr) {\n";
4640 OS
<< " SmallVector<Expr *, 4> ArgExprs;\n";
4641 OS
<< " ArgExprs.reserve(Attr.getNumArgs());\n";
4642 OS
<< " for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
4643 OS
<< " assert(!Attr.isArgIdent(I));\n";
4644 OS
<< " ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
4646 OS
<< " clang::Attr *CreatedAttr = nullptr;\n";
4647 OS
<< " switch (Attr.getKind()) {\n";
4648 OS
<< " default:\n";
4649 OS
<< " llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
4650 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
4651 for (const auto &I
: Attrs
) {
4652 const Record
&R
= *I
.second
;
4653 if (!R
.getValueAsBit("AcceptsExprPack"))
4655 OS
<< " case ParsedAttr::AT_" << I
.first
<< ": {\n";
4656 OS
<< " CreatedAttr = " << R
.getName() << "Attr::CreateWithDelayedArgs";
4657 OS
<< "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
4662 OS
<< " D->addAttr(CreatedAttr);\n";
4666 static bool IsKnownToGCC(const Record
&Attr
) {
4667 // Look at the spellings for this subject; if there are any spellings which
4668 // claim to be known to GCC, the attribute is known to GCC.
4669 return any_of(GetFlattenedSpellings(Attr
),
4670 [](const FlattenedSpelling
&S
) { return S
.knownToGCC(); });
4673 /// Emits the parsed attribute helpers
4674 void EmitClangAttrParsedAttrImpl(const RecordKeeper
&Records
, raw_ostream
&OS
) {
4675 emitSourceFileHeader("Parsed attribute helpers", OS
, Records
);
4677 OS
<< "#if !defined(WANT_DECL_MERGE_LOGIC) && "
4678 << "!defined(WANT_STMT_MERGE_LOGIC)\n";
4679 PragmaClangAttributeSupport
&PragmaAttributeSupport
=
4680 getPragmaAttributeSupport(Records
);
4682 // Get the list of parsed attributes, and accept the optional list of
4683 // duplicates due to the ParseKind.
4684 ParsedAttrMap Dupes
;
4685 ParsedAttrMap Attrs
= getParsedAttrList(Records
, &Dupes
);
4687 // Generate all of the custom appertainsTo functions that the attributes
4689 for (const auto &I
: Attrs
) {
4690 const Record
&Attr
= *I
.second
;
4691 if (Attr
.isValueUnset("Subjects"))
4693 const Record
*SubjectObj
= Attr
.getValueAsDef("Subjects");
4694 for (const Record
*Subject
: SubjectObj
->getValueAsListOfDefs("Subjects"))
4695 if (Subject
->isSubClassOf("SubsetSubject"))
4696 GenerateCustomAppertainsTo(*Subject
, OS
);
4699 // This stream is used to collect all of the declaration attribute merging
4700 // logic for performing mutual exclusion checks. This gets emitted at the
4701 // end of the file in a helper function of its own.
4702 std::string DeclMergeChecks
, StmtMergeChecks
;
4703 raw_string_ostream
MergeDeclOS(DeclMergeChecks
), MergeStmtOS(StmtMergeChecks
);
4705 // Generate a ParsedAttrInfo struct for each of the attributes.
4706 for (auto I
= Attrs
.begin(), E
= Attrs
.end(); I
!= E
; ++I
) {
4707 // TODO: If the attribute's kind appears in the list of duplicates, that is
4708 // because it is a target-specific attribute that appears multiple times.
4709 // It would be beneficial to test whether the duplicates are "similar
4710 // enough" to each other to not cause problems. For instance, check that
4711 // the spellings are identical, and custom parsing rules match, etc.
4713 // We need to generate struct instances based off ParsedAttrInfo from
4715 const std::string
&AttrName
= I
->first
;
4716 const Record
&Attr
= *I
->second
;
4717 auto Spellings
= GetFlattenedSpellings(Attr
);
4718 if (!Spellings
.empty()) {
4719 OS
<< "static constexpr ParsedAttrInfo::Spelling " << I
->first
4720 << "Spellings[] = {\n";
4721 for (const auto &S
: Spellings
) {
4722 StringRef RawSpelling
= S
.name();
4723 std::string Spelling
;
4724 if (!S
.nameSpace().empty())
4725 Spelling
+= S
.nameSpace().str() + "::";
4726 if (S
.variety() == "GNU")
4727 Spelling
+= NormalizeGNUAttrSpelling(RawSpelling
);
4729 Spelling
+= RawSpelling
;
4730 OS
<< " {AttributeCommonInfo::AS_" << S
.variety();
4731 OS
<< ", \"" << Spelling
<< "\"},\n";
4736 std::vector
<std::string
> ArgNames
;
4737 for (const auto *Arg
: Attr
.getValueAsListOfDefs("Args")) {
4739 if (Arg
->getValueAsBitOrUnset("Fake", UnusedUnset
))
4741 ArgNames
.push_back(Arg
->getValueAsString("Name").str());
4742 for (const auto &[Class
, _
] : Arg
->getSuperClasses()) {
4743 if (Class
->getName().starts_with("Variadic")) {
4744 ArgNames
.back().append("...");
4749 if (!ArgNames
.empty()) {
4750 OS
<< "static constexpr const char *" << I
->first
<< "ArgNames[] = {\n";
4751 for (const auto &N
: ArgNames
)
4752 OS
<< '"' << N
<< "\",";
4756 OS
<< "struct ParsedAttrInfo" << I
->first
4757 << " final : public ParsedAttrInfo {\n";
4758 OS
<< " constexpr ParsedAttrInfo" << I
->first
<< "() : ParsedAttrInfo(\n";
4759 OS
<< " /*AttrKind=*/ParsedAttr::AT_" << AttrName
<< ",\n";
4760 emitArgInfo(Attr
, OS
);
4761 OS
<< " /*HasCustomParsing=*/";
4762 OS
<< Attr
.getValueAsBit("HasCustomParsing") << ",\n";
4763 OS
<< " /*AcceptsExprPack=*/";
4764 OS
<< Attr
.getValueAsBit("AcceptsExprPack") << ",\n";
4765 OS
<< " /*IsTargetSpecific=*/";
4766 OS
<< Attr
.isSubClassOf("TargetSpecificAttr") << ",\n";
4767 OS
<< " /*IsType=*/";
4768 OS
<< (Attr
.isSubClassOf("TypeAttr") || Attr
.isSubClassOf("DeclOrTypeAttr"))
4770 OS
<< " /*IsStmt=*/";
4771 OS
<< (Attr
.isSubClassOf("StmtAttr") || Attr
.isSubClassOf("DeclOrStmtAttr"))
4773 OS
<< " /*IsKnownToGCC=*/";
4774 OS
<< IsKnownToGCC(Attr
) << ",\n";
4775 OS
<< " /*IsSupportedByPragmaAttribute=*/";
4776 OS
<< PragmaAttributeSupport
.isAttributedSupported(*I
->second
) << ",\n";
4777 if (!Spellings
.empty())
4778 OS
<< " /*Spellings=*/" << I
->first
<< "Spellings,\n";
4780 OS
<< " /*Spellings=*/{},\n";
4781 if (!ArgNames
.empty())
4782 OS
<< " /*ArgNames=*/" << I
->first
<< "ArgNames";
4784 OS
<< " /*ArgNames=*/{}";
4786 GenerateAppertainsTo(Attr
, OS
);
4787 GenerateMutualExclusionsChecks(Attr
, Records
, OS
, MergeDeclOS
, MergeStmtOS
);
4788 GenerateLangOptRequirements(Attr
, OS
);
4789 GenerateTargetRequirements(Attr
, Dupes
, OS
);
4790 GenerateSpellingTargetRequirements(
4791 Attr
, Attr
.getValueAsListOfDefs("TargetSpecificSpellings"), OS
);
4792 GenerateSpellingIndexToSemanticSpelling(Attr
, OS
);
4793 PragmaAttributeSupport
.generateStrictConformsTo(*I
->second
, OS
);
4794 GenerateHandleDeclAttribute(Attr
, OS
);
4795 GenerateIsParamExpr(Attr
, OS
);
4796 OS
<< "static const ParsedAttrInfo" << I
->first
<< " Instance;\n";
4798 OS
<< "const ParsedAttrInfo" << I
->first
<< " ParsedAttrInfo" << I
->first
4802 OS
<< "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
4803 for (auto I
= Attrs
.begin(), E
= Attrs
.end(); I
!= E
; ++I
) {
4804 OS
<< "&ParsedAttrInfo" << I
->first
<< "::Instance,\n";
4808 // Generate function for handling attributes with delayed arguments
4809 GenerateHandleAttrWithDelayedArgs(Records
, OS
);
4811 // Generate the attribute match rules.
4812 emitAttributeMatchRules(PragmaAttributeSupport
, OS
);
4814 OS
<< "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
4816 // Write out the declaration merging check logic.
4817 OS
<< "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
4818 << "const Attr *A) {\n";
4819 OS
<< DeclMergeChecks
;
4820 OS
<< " return true;\n";
4823 OS
<< "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
4825 // Write out the statement merging check logic.
4826 OS
<< "static bool DiagnoseMutualExclusions(Sema &S, "
4827 << "const SmallVectorImpl<const Attr *> &C) {\n";
4828 OS
<< " for (const Attr *A : C) {\n";
4829 OS
<< StmtMergeChecks
;
4831 OS
<< " return true;\n";
4837 // Emits the kind list of parsed attributes
4838 void EmitClangAttrParsedAttrKinds(const RecordKeeper
&Records
,
4840 emitSourceFileHeader("Attribute name matcher", OS
, Records
);
4842 std::vector
<StringMatcher::StringPair
> GNU
, Declspec
, Microsoft
, CXX11
,
4843 Keywords
, Pragma
, C23
, HLSLAnnotation
;
4844 std::set
<StringRef
> Seen
;
4845 for (const auto *A
: Records
.getAllDerivedDefinitions("Attr")) {
4846 const Record
&Attr
= *A
;
4848 bool SemaHandler
= Attr
.getValueAsBit("SemaHandler");
4849 bool Ignored
= Attr
.getValueAsBit("Ignored");
4850 if (SemaHandler
|| Ignored
) {
4851 // Attribute spellings can be shared between target-specific attributes,
4852 // and can be shared between syntaxes for the same attribute. For
4853 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
4854 // specific attribute, or MSP430-specific attribute. Additionally, an
4855 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
4856 // for the same semantic attribute. Ultimately, we need to map each of
4857 // these to a single AttributeCommonInfo::Kind value, but the
4858 // StringMatcher class cannot handle duplicate match strings. So we
4859 // generate a list of string to match based on the syntax, and emit
4860 // multiple string matchers depending on the syntax used.
4861 std::string AttrName
;
4862 if (Attr
.isSubClassOf("TargetSpecificAttr") &&
4863 !Attr
.isValueUnset("ParseKind")) {
4864 StringRef ParseKind
= Attr
.getValueAsString("ParseKind");
4865 if (!Seen
.insert(ParseKind
).second
)
4867 AttrName
= ParseKind
.str();
4869 AttrName
= NormalizeAttrName(Attr
.getName()).str();
4872 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attr
);
4873 for (const auto &S
: Spellings
) {
4874 StringRef RawSpelling
= S
.name();
4875 std::vector
<StringMatcher::StringPair
> *Matches
= nullptr;
4876 std::string Spelling
;
4877 StringRef Variety
= S
.variety();
4878 if (Variety
== "CXX11") {
4880 if (!S
.nameSpace().empty())
4881 Spelling
+= S
.nameSpace().str() + "::";
4882 } else if (Variety
== "C23") {
4884 if (!S
.nameSpace().empty())
4885 Spelling
+= S
.nameSpace().str() + "::";
4886 } else if (Variety
== "GNU") {
4888 } else if (Variety
== "Declspec") {
4889 Matches
= &Declspec
;
4890 } else if (Variety
== "Microsoft") {
4891 Matches
= &Microsoft
;
4892 } else if (Variety
== "Keyword") {
4893 Matches
= &Keywords
;
4894 } else if (Variety
== "Pragma") {
4896 } else if (Variety
== "HLSLAnnotation") {
4897 Matches
= &HLSLAnnotation
;
4900 assert(Matches
&& "Unsupported spelling variety found");
4902 if (Variety
== "GNU")
4903 Spelling
+= NormalizeGNUAttrSpelling(RawSpelling
);
4905 Spelling
+= RawSpelling
;
4908 Matches
->push_back(StringMatcher::StringPair(
4909 Spelling
, "return AttributeCommonInfo::AT_" + AttrName
+ ";"));
4911 Matches
->push_back(StringMatcher::StringPair(
4912 Spelling
, "return AttributeCommonInfo::IgnoredAttribute;"));
4917 OS
<< "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
4918 OS
<< "AttributeCommonInfo::Syntax Syntax) {\n";
4919 OS
<< " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
4920 StringMatcher("Name", GNU
, OS
).Emit();
4921 OS
<< " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
4922 StringMatcher("Name", Declspec
, OS
).Emit();
4923 OS
<< " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
4924 StringMatcher("Name", Microsoft
, OS
).Emit();
4925 OS
<< " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
4926 StringMatcher("Name", CXX11
, OS
).Emit();
4927 OS
<< " } else if (AttributeCommonInfo::AS_C23 == Syntax) {\n";
4928 StringMatcher("Name", C23
, OS
).Emit();
4929 OS
<< " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
4930 OS
<< "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
4931 StringMatcher("Name", Keywords
, OS
).Emit();
4932 OS
<< " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
4933 StringMatcher("Name", Pragma
, OS
).Emit();
4934 OS
<< " } else if (AttributeCommonInfo::AS_HLSLAnnotation == Syntax) {\n";
4935 StringMatcher("Name", HLSLAnnotation
, OS
).Emit();
4937 OS
<< " return AttributeCommonInfo::UnknownAttribute;\n"
4941 // Emits the code to dump an attribute.
4942 void EmitClangAttrTextNodeDump(const RecordKeeper
&Records
, raw_ostream
&OS
) {
4943 emitSourceFileHeader("Attribute text node dumper", OS
, Records
);
4945 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
4946 const Record
&R
= *Attr
;
4947 if (!R
.getValueAsBit("ASTNode"))
4950 // If the attribute has a semantically-meaningful name (which is determined
4951 // by whether there is a Spelling enumeration for it), then write out the
4952 // spelling used for the attribute.
4954 std::string FunctionContent
;
4955 raw_string_ostream
SS(FunctionContent
);
4957 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(R
);
4958 if (Spellings
.size() > 1 && !SpellingNamesAreCommon(Spellings
))
4959 SS
<< " OS << \" \" << A->getSpelling();\n";
4961 std::vector
<const Record
*> Args
= R
.getValueAsListOfDefs("Args");
4962 for (const auto *Arg
: Args
)
4963 createArgument(*Arg
, R
.getName())->writeDump(SS
);
4965 if (Attr
->getValueAsBit("AcceptsExprPack"))
4966 VariadicExprArgument("DelayedArgs", R
.getName()).writeDump(OS
);
4969 OS
<< " void Visit" << R
.getName() << "Attr(const " << R
.getName()
4972 OS
<< " const auto *SA = cast<" << R
.getName()
4973 << "Attr>(A); (void)SA;\n";
4974 OS
<< FunctionContent
;
4980 void EmitClangAttrNodeTraverse(const RecordKeeper
&Records
, raw_ostream
&OS
) {
4981 emitSourceFileHeader("Attribute text node traverser", OS
, Records
);
4983 for (const auto *Attr
: Records
.getAllDerivedDefinitions("Attr")) {
4984 const Record
&R
= *Attr
;
4985 if (!R
.getValueAsBit("ASTNode"))
4988 std::string FunctionContent
;
4989 raw_string_ostream
SS(FunctionContent
);
4991 std::vector
<const Record
*> Args
= R
.getValueAsListOfDefs("Args");
4992 for (const auto *Arg
: Args
)
4993 createArgument(*Arg
, R
.getName())->writeDumpChildren(SS
);
4994 if (Attr
->getValueAsBit("AcceptsExprPack"))
4995 VariadicExprArgument("DelayedArgs", R
.getName()).writeDumpChildren(SS
);
4997 OS
<< " void Visit" << R
.getName() << "Attr(const " << R
.getName()
5000 OS
<< " const auto *SA = cast<" << R
.getName()
5001 << "Attr>(A); (void)SA;\n";
5002 OS
<< FunctionContent
;
5008 void EmitClangAttrParserStringSwitches(const RecordKeeper
&Records
,
5010 generateNameToAttrsMap(Records
);
5011 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS
, Records
);
5012 emitClangAttrArgContextList(Records
, OS
);
5013 emitClangAttrIdentifierArgList(Records
, OS
);
5014 emitClangAttrUnevaluatedStringLiteralList(Records
, OS
);
5015 emitClangAttrVariadicIdentifierArgList(Records
, OS
);
5016 emitClangAttrThisIsaIdentifierArgList(Records
, OS
);
5017 emitClangAttrAcceptsExprPack(Records
, OS
);
5018 emitClangAttrTypeArgList(Records
, OS
);
5019 emitClangAttrLateParsedList(Records
, OS
);
5020 emitClangAttrLateParsedExperimentalList(Records
, OS
);
5021 emitClangAttrStrictIdentifierArgList(Records
, OS
);
5024 void EmitClangAttrSubjectMatchRulesParserStringSwitches(
5025 const RecordKeeper
&Records
, raw_ostream
&OS
) {
5026 getPragmaAttributeSupport(Records
).generateParsingHelpers(OS
);
5029 void EmitClangAttrDocTable(const RecordKeeper
&Records
, raw_ostream
&OS
) {
5030 emitSourceFileHeader("Clang attribute documentation", OS
, Records
);
5032 for (const auto *A
: Records
.getAllDerivedDefinitions("Attr")) {
5033 if (!A
->getValueAsBit("ASTNode"))
5035 std::vector
<const Record
*> Docs
= A
->getValueAsListOfDefs("Documentation");
5036 assert(!Docs
.empty());
5037 // Only look at the first documentation if there are several.
5038 // (Currently there's only one such attr, revisit if this becomes common).
5040 Docs
.front()->getValueAsOptionalString("Content").value_or("");
5041 OS
<< "\nstatic const char AttrDoc_" << A
->getName() << "[] = "
5042 << "R\"reST(" << Text
.trim() << ")reST\";\n";
5046 enum class SpellingKind
: size_t {
5057 static const size_t NumSpellingKinds
= (size_t)SpellingKind::NumSpellingKinds
;
5059 class SpellingList
{
5060 std::vector
<std::string
> Spellings
[NumSpellingKinds
];
5063 ArrayRef
<std::string
> operator[](SpellingKind K
) const {
5064 return Spellings
[(size_t)K
];
5067 void add(const Record
&Attr
, FlattenedSpelling Spelling
) {
5069 StringSwitch
<SpellingKind
>(Spelling
.variety())
5070 .Case("GNU", SpellingKind::GNU
)
5071 .Case("CXX11", SpellingKind::CXX11
)
5072 .Case("C23", SpellingKind::C23
)
5073 .Case("Declspec", SpellingKind::Declspec
)
5074 .Case("Microsoft", SpellingKind::Microsoft
)
5075 .Case("Keyword", SpellingKind::Keyword
)
5076 .Case("Pragma", SpellingKind::Pragma
)
5077 .Case("HLSLAnnotation", SpellingKind::HLSLAnnotation
);
5079 StringRef NameSpace
= Spelling
.nameSpace();
5080 if (!NameSpace
.empty()) {
5083 case SpellingKind::CXX11
:
5084 case SpellingKind::C23
:
5087 case SpellingKind::Pragma
:
5091 PrintFatalError(Attr
.getLoc(), "Unexpected namespace in spelling");
5094 Name
+= Spelling
.name();
5096 Spellings
[(size_t)Kind
].push_back(Name
);
5100 class DocumentationData
{
5102 const Record
*Documentation
;
5103 const Record
*Attribute
;
5104 std::string Heading
;
5105 SpellingList SupportedSpellings
;
5107 DocumentationData(const Record
&Documentation
, const Record
&Attribute
,
5108 std::pair
<std::string
, SpellingList
> HeadingAndSpellings
)
5109 : Documentation(&Documentation
), Attribute(&Attribute
),
5110 Heading(std::move(HeadingAndSpellings
.first
)),
5111 SupportedSpellings(std::move(HeadingAndSpellings
.second
)) {}
5114 static void WriteCategoryHeader(const Record
*DocCategory
,
5116 const StringRef Name
= DocCategory
->getValueAsString("Name");
5117 OS
<< Name
<< "\n" << std::string(Name
.size(), '=') << "\n";
5119 // If there is content, print that as well.
5120 const StringRef ContentStr
= DocCategory
->getValueAsString("Content");
5121 // Trim leading and trailing newlines and spaces.
5122 OS
<< ContentStr
.trim();
5127 static std::pair
<std::string
, SpellingList
>
5128 GetAttributeHeadingAndSpellings(const Record
&Documentation
,
5129 const Record
&Attribute
,
5131 // FIXME: there is no way to have a per-spelling category for the attribute
5132 // documentation. This may not be a limiting factor since the spellings
5133 // should generally be consistently applied across the category.
5135 std::vector
<FlattenedSpelling
> Spellings
= GetFlattenedSpellings(Attribute
);
5136 if (Spellings
.empty())
5137 PrintFatalError(Attribute
.getLoc(),
5138 "Attribute has no supported spellings; cannot be "
5141 // Determine the heading to be used for this attribute.
5142 std::string Heading
= Documentation
.getValueAsString("Heading").str();
5143 if (Heading
.empty()) {
5144 // If there's only one spelling, we can simply use that.
5145 if (Spellings
.size() == 1)
5146 Heading
= Spellings
.begin()->name();
5148 std::set
<std::string
> Uniques
;
5149 for (auto I
= Spellings
.begin(), E
= Spellings
.end();
5151 std::string Spelling
=
5152 NormalizeNameForSpellingComparison(I
->name()).str();
5153 Uniques
.insert(Spelling
);
5155 // If the semantic map has only one spelling, that is sufficient for our
5157 if (Uniques
.size() == 1)
5158 Heading
= *Uniques
.begin();
5159 // If it's in the undocumented category, just construct a header by
5160 // concatenating all the spellings. Might not be great, but better than
5162 else if (Cat
== "Undocumented")
5163 Heading
= join(Uniques
.begin(), Uniques
.end(), ", ");
5167 // If the heading is still empty, it is an error.
5168 if (Heading
.empty())
5169 PrintFatalError(Attribute
.getLoc(),
5170 "This attribute requires a heading to be specified");
5172 SpellingList SupportedSpellings
;
5173 for (const auto &I
: Spellings
)
5174 SupportedSpellings
.add(Attribute
, I
);
5176 return std::make_pair(std::move(Heading
), std::move(SupportedSpellings
));
5179 static void WriteDocumentation(const RecordKeeper
&Records
,
5180 const DocumentationData
&Doc
, raw_ostream
&OS
) {
5181 if (StringRef Label
= Doc
.Documentation
->getValueAsString("Label");
5183 OS
<< ".. _" << Label
<< ":\n\n";
5184 OS
<< Doc
.Heading
<< "\n" << std::string(Doc
.Heading
.length(), '-') << "\n";
5186 // List what spelling syntaxes the attribute supports.
5187 // Note: "#pragma clang attribute" is handled outside the spelling kinds loop
5188 // so it must be last.
5189 OS
<< ".. csv-table:: Supported Syntaxes\n";
5190 OS
<< " :header: \"GNU\", \"C++11\", \"C23\", \"``__declspec``\",";
5191 OS
<< " \"Keyword\", \"``#pragma``\", \"HLSL Annotation\", \"``#pragma "
5193 OS
<< "attribute``\"\n\n \"";
5194 for (size_t Kind
= 0; Kind
!= NumSpellingKinds
; ++Kind
) {
5195 SpellingKind K
= (SpellingKind
)Kind
;
5196 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
5198 if (K
== SpellingKind::Microsoft
)
5201 bool PrintedAny
= false;
5202 for (StringRef Spelling
: Doc
.SupportedSpellings
[K
]) {
5205 OS
<< "``" << Spelling
<< "``";
5212 if (getPragmaAttributeSupport(Records
).isAttributedSupported(
5217 // If the attribute is deprecated, print a message about it, and possibly
5218 // provide a replacement attribute.
5219 if (!Doc
.Documentation
->isValueUnset("Deprecated")) {
5220 OS
<< "This attribute has been deprecated, and may be removed in a future "
5221 << "version of Clang.";
5222 const Record
&Deprecated
= *Doc
.Documentation
->getValueAsDef("Deprecated");
5223 const StringRef Replacement
= Deprecated
.getValueAsString("Replacement");
5224 if (!Replacement
.empty())
5225 OS
<< " This attribute has been superseded by ``" << Replacement
5230 const StringRef ContentStr
= Doc
.Documentation
->getValueAsString("Content");
5231 // Trim leading and trailing newlines and spaces.
5232 OS
<< ContentStr
.trim();
5237 void EmitClangAttrDocs(const RecordKeeper
&Records
, raw_ostream
&OS
) {
5238 // Get the documentation introduction paragraph.
5239 const Record
*Documentation
= Records
.getDef("GlobalDocumentation");
5240 if (!Documentation
) {
5241 PrintFatalError("The Documentation top-level definition is missing, "
5242 "no documentation will be generated.");
5246 OS
<< Documentation
->getValueAsString("Intro") << "\n";
5248 // Gather the Documentation lists from each of the attributes, based on the
5249 // category provided.
5250 struct CategoryLess
{
5251 bool operator()(const Record
*L
, const Record
*R
) const {
5252 return L
->getValueAsString("Name") < R
->getValueAsString("Name");
5255 std::map
<const Record
*, std::vector
<DocumentationData
>, CategoryLess
>
5257 for (const auto *A
: Records
.getAllDerivedDefinitions("Attr")) {
5258 const Record
&Attr
= *A
;
5259 std::vector
<const Record
*> Docs
=
5260 Attr
.getValueAsListOfDefs("Documentation");
5261 for (const auto *D
: Docs
) {
5262 const Record
&Doc
= *D
;
5263 const Record
*Category
= Doc
.getValueAsDef("Category");
5264 // If the category is "InternalOnly", then there cannot be any other
5265 // documentation categories (otherwise, the attribute would be
5266 // emitted into the docs).
5267 const StringRef Cat
= Category
->getValueAsString("Name");
5268 bool InternalOnly
= Cat
== "InternalOnly";
5269 if (InternalOnly
&& Docs
.size() > 1)
5270 PrintFatalError(Doc
.getLoc(),
5271 "Attribute is \"InternalOnly\", but has multiple "
5272 "documentation categories");
5275 SplitDocs
[Category
].push_back(DocumentationData(
5276 Doc
, Attr
, GetAttributeHeadingAndSpellings(Doc
, Attr
, Cat
)));
5280 // Having split the attributes out based on what documentation goes where,
5281 // we can begin to generate sections of documentation.
5282 for (auto &I
: SplitDocs
) {
5283 WriteCategoryHeader(I
.first
, OS
);
5286 [](const DocumentationData
&D1
, const DocumentationData
&D2
) {
5287 return D1
.Heading
< D2
.Heading
;
5290 // Walk over each of the attributes in the category and write out their
5292 for (const auto &Doc
: I
.second
)
5293 WriteDocumentation(Records
, Doc
, OS
);
5297 void EmitTestPragmaAttributeSupportedAttributes(const RecordKeeper
&Records
,
5299 PragmaClangAttributeSupport Support
= getPragmaAttributeSupport(Records
);
5300 ParsedAttrMap Attrs
= getParsedAttrList(Records
);
5301 OS
<< "#pragma clang attribute supports the following attributes:\n";
5302 for (const auto &I
: Attrs
) {
5303 if (!Support
.isAttributedSupported(*I
.second
))
5306 if (I
.second
->isValueUnset("Subjects")) {
5310 const Record
*SubjectObj
= I
.second
->getValueAsDef("Subjects");
5312 bool PrintComma
= false;
5313 for (const auto &Subject
:
5314 enumerate(SubjectObj
->getValueAsListOfDefs("Subjects"))) {
5315 if (!isSupportedPragmaClangAttributeSubject(*Subject
.value()))
5320 PragmaClangAttributeSupport::RuleOrAggregateRuleSet
&RuleSet
=
5321 Support
.SubjectsToRules
.find(Subject
.value())->getSecond();
5322 if (RuleSet
.isRule()) {
5323 OS
<< RuleSet
.getRule().getEnumValueName();
5327 for (const auto &Rule
: enumerate(RuleSet
.getAggregateRuleSet())) {
5330 OS
<< Rule
.value().getEnumValueName();
5336 OS
<< "End of supported attributes.\n";
5339 } // end namespace clang