1//===-- ClangAttrEmitter.cpp - Generate Clang attribute handling ----------===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8//
9// These tablegen backends emit Clang attribute processing code
10//
11//===----------------------------------------------------------------------===//
12
13#include "TableGenBackends.h"
14#include "ASTTableGen.h"
15
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/StringMap.h"
24#include "llvm/ADT/StringRef.h"
25#include "llvm/ADT/StringSwitch.h"
26#include "llvm/Support/ErrorHandling.h"
27#include "llvm/Support/raw_ostream.h"
28#include "llvm/TableGen/Error.h"
29#include "llvm/TableGen/Record.h"
30#include "llvm/TableGen/StringMatcher.h"
31#include "llvm/TableGen/TableGenBackend.h"
32#include <cassert>
33#include <cctype>
34#include <cstddef>
35#include <cstdint>
36#include <map>
37#include <memory>
38#include <optional>
39#include <set>
40#include <string>
41#include <utility>
42#include <vector>
43
44using namespace llvm;
45
46namespace {
47
48class FlattenedSpelling {
49 StringRef V, N, NS;
50 bool K = false;
51 const Record &OriginalSpelling;
52
53public:
54 FlattenedSpelling(StringRef Variety, StringRef Name, StringRef Namespace,
55 bool KnownToGCC, const Record &OriginalSpelling)
56 : V(Variety), N(Name), NS(Namespace), K(KnownToGCC),
57 OriginalSpelling(OriginalSpelling) {}
58 explicit FlattenedSpelling(const Record &Spelling)
59 : V(Spelling.getValueAsString(FieldName: "Variety")),
60 N(Spelling.getValueAsString(FieldName: "Name")), OriginalSpelling(Spelling) {
61 assert(V != "GCC" && V != "Clang" &&
62 "Given a GCC spelling, which means this hasn't been flattened!");
63 if (V == "CXX11" || V == "C23" || V == "Pragma")
64 NS = Spelling.getValueAsString(FieldName: "Namespace");
65 }
66
67 StringRef variety() const { return V; }
68 StringRef name() const { return N; }
69 StringRef nameSpace() const { return NS; }
70 bool knownToGCC() const { return K; }
71 const Record &getSpellingRecord() const { return OriginalSpelling; }
72};
73
74struct FlattenedSpellingInfo {
75 FlattenedSpellingInfo(StringRef Syntax, StringRef Scope,
76 const std::string &TargetTest, uint32_t ArgMask)
77 : Syntax(Syntax), Scope(Scope), TargetTest(TargetTest), ArgMask(ArgMask) {
78 }
79 StringRef Syntax;
80 StringRef Scope;
81 std::string TargetTest;
82 uint32_t ArgMask;
83};
84using FSIVecTy = std::vector<FlattenedSpellingInfo>;
85
86} // end anonymous namespace
87
88static bool GenerateTargetSpecificAttrChecks(const Record *R,
89 std::vector<StringRef> &Arches,
90 std::string &Test,
91 std::string *FnName);
92static bool isStringLiteralArgument(const Record *Arg);
93static bool isVariadicStringLiteralArgument(const Record *Arg);
94
95static std::vector<FlattenedSpelling>
96GetFlattenedSpellings(const Record &Attr) {
97 std::vector<FlattenedSpelling> Ret;
98
99 for (const auto &Spelling : Attr.getValueAsListOfDefs(FieldName: "Spellings")) {
100 StringRef Variety = Spelling->getValueAsString(FieldName: "Variety");
101 StringRef Name = Spelling->getValueAsString(FieldName: "Name");
102 if (Variety == "GCC") {
103 Ret.emplace_back(args: "GNU", args&: Name, args: "", args: true, args: *Spelling);
104 Ret.emplace_back(args: "CXX11", args&: Name, args: "gnu", args: true, args: *Spelling);
105 if (Spelling->getValueAsBit(FieldName: "AllowInC"))
106 Ret.emplace_back(args: "C23", args&: Name, args: "gnu", args: true, args: *Spelling);
107 } else if (Variety == "Clang") {
108 Ret.emplace_back(args: "GNU", args&: Name, args: "", args: false, args: *Spelling);
109 Ret.emplace_back(args: "CXX11", args&: Name, args: "clang", args: false, args: *Spelling);
110 if (Spelling->getValueAsBit(FieldName: "AllowInC"))
111 Ret.emplace_back(args: "C23", args&: Name, args: "clang", args: false, args: *Spelling);
112 } else if (Variety == "ClangGCC") {
113 Ret.emplace_back(args: "GNU", args&: Name, args: "", args: false, args: *Spelling);
114 Ret.emplace_back(args: "CXX11", args&: Name, args: "clang", args: false, args: *Spelling);
115 Ret.emplace_back(args: "CXX11", args&: Name, args: "gnu", args: false, args: *Spelling);
116 if (Spelling->getValueAsBit(FieldName: "AllowInC")) {
117 Ret.emplace_back(args: "C23", args&: Name, args: "clang", args: false, args: *Spelling);
118 Ret.emplace_back(args: "C23", args&: Name, args: "gnu", args: false, args: *Spelling);
119 }
120 } else {
121 Ret.push_back(x: FlattenedSpelling(*Spelling));
122 }
123 }
124
125 return Ret;
126}
127
128static std::string ReadPCHRecord(StringRef type) {
129 return StringSwitch<std::string>(type)
130 .EndsWith(S: "Decl *", Value: "Record.readDeclAs<" + type.drop_back().str() + ">()")
131 .Case(S: "TypeSourceInfo *", Value: "Record.readTypeSourceInfo()")
132 .Case(S: "Expr *", Value: "Record.readExpr()")
133 .Case(S: "const IdentifierInfo *", Value: "Record.readIdentifier()")
134 .Case(S: "StringRef", Value: "Record.readString()")
135 .Case(S: "ParamIdx", Value: "ParamIdx::deserialize(Record.readInt())")
136 .Case(S: "OMPTraitInfo *", Value: "Record.readOMPTraitInfo()")
137 .Default(Value: "Record.readInt()");
138}
139
140// Get a type that is suitable for storing an object of the specified type.
141static StringRef getStorageType(StringRef type) {
142 return StringSwitch<StringRef>(type)
143 .Case(S: "StringRef", Value: "std::string")
144 .Default(Value: type);
145}
146
147// Assumes that the way to get the value is SA->getname()
148static std::string WritePCHRecord(StringRef type, StringRef name) {
149 return "Record." +
150 StringSwitch<std::string>(type)
151 .EndsWith(S: "Decl *", Value: "AddDeclRef(" + name.str() + ");\n")
152 .Case(S: "TypeSourceInfo *",
153 Value: "AddTypeSourceInfo(" + name.str() + ");\n")
154 .Case(S: "Expr *", Value: "AddStmt(" + name.str() + ");\n")
155 .Case(S: "const IdentifierInfo *",
156 Value: "AddIdentifierRef(" + name.str() + ");\n")
157 .Case(S: "StringRef", Value: "AddString(" + name.str() + ");\n")
158 .Case(S: "ParamIdx", Value: "push_back(" + name.str() + ".serialize());\n")
159 .Case(S: "OMPTraitInfo *", Value: "writeOMPTraitInfo(" + name.str() + ");\n")
160 .Default(Value: "push_back(" + name.str() + ");\n");
161}
162
163// Normalize attribute name by removing leading and trailing
164// underscores. For example, __foo, foo__, __foo__ would
165// become foo.
166static StringRef NormalizeAttrName(StringRef AttrName) {
167 AttrName.consume_front(Prefix: "__");
168 AttrName.consume_back(Suffix: "__");
169 return AttrName;
170}
171
172// Normalize the name by removing any and all leading and trailing underscores.
173// This is different from NormalizeAttrName in that it also handles names like
174// _pascal and __pascal.
175static StringRef NormalizeNameForSpellingComparison(StringRef Name) {
176 return Name.trim(Chars: "_");
177}
178
179// Normalize the spelling of a GNU attribute (i.e. "x" in "__attribute__((x))"),
180// removing "__" if it appears at the beginning and end of the attribute's name.
181static StringRef NormalizeGNUAttrSpelling(StringRef AttrSpelling) {
182 if (AttrSpelling.starts_with(Prefix: "__") && AttrSpelling.ends_with(Suffix: "__")) {
183 AttrSpelling = AttrSpelling.substr(Start: 2, N: AttrSpelling.size() - 4);
184 }
185
186 return AttrSpelling;
187}
188
189typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap;
190
191static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records,
192 ParsedAttrMap *Dupes = nullptr,
193 bool SemaOnly = true) {
194 std::set<std::string> Seen;
195 ParsedAttrMap R;
196 for (const Record *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
197 if (!SemaOnly || Attr->getValueAsBit(FieldName: "SemaHandler")) {
198 std::string AN;
199 if (Attr->isSubClassOf(Name: "TargetSpecificAttr") &&
200 !Attr->isValueUnset(FieldName: "ParseKind")) {
201 AN = Attr->getValueAsString(FieldName: "ParseKind").str();
202
203 // If this attribute has already been handled, it does not need to be
204 // handled again.
205 if (!Seen.insert(x: AN).second) {
206 if (Dupes)
207 Dupes->push_back(x: std::make_pair(x&: AN, y&: Attr));
208 continue;
209 }
210 } else
211 AN = NormalizeAttrName(AttrName: Attr->getName()).str();
212
213 R.push_back(x: std::make_pair(x&: AN, y&: Attr));
214 }
215 }
216 return R;
217}
218
219namespace {
220
221 class Argument {
222 std::string lowerName, upperName;
223 StringRef attrName;
224 bool isOpt;
225 bool Fake;
226
227 public:
228 Argument(StringRef Arg, StringRef Attr)
229 : lowerName(Arg.str()), upperName(lowerName), attrName(Attr),
230 isOpt(false), Fake(false) {
231 if (!lowerName.empty()) {
232 lowerName[0] = std::tolower(c: lowerName[0]);
233 upperName[0] = std::toupper(c: upperName[0]);
234 }
235 // Work around MinGW's macro definition of 'interface' to 'struct'. We
236 // have an attribute argument called 'Interface', so only the lower case
237 // name conflicts with the macro definition.
238 if (lowerName == "interface")
239 lowerName = "interface_";
240 }
241 Argument(const Record &Arg, StringRef Attr)
242 : Argument(Arg.getValueAsString(FieldName: "Name"), Attr) {}
243 virtual ~Argument() = default;
244
245 StringRef getLowerName() const { return lowerName; }
246 StringRef getUpperName() const { return upperName; }
247 StringRef getAttrName() const { return attrName; }
248
249 bool isOptional() const { return isOpt; }
250 void setOptional(bool set) { isOpt = set; }
251
252 bool isFake() const { return Fake; }
253 void setFake(bool fake) { Fake = fake; }
254
255 // These functions print the argument contents formatted in different ways.
256 virtual void writeAccessors(raw_ostream &OS) const = 0;
257 virtual void writeAccessorDefinitions(raw_ostream &OS) const {}
258 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {}
259 virtual void writeCloneArgs(raw_ostream &OS) const = 0;
260 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0;
261 virtual void writeTemplateInstantiation(raw_ostream &OS) const {}
262 virtual void writeCtorBody(raw_ostream &OS) const {}
263 virtual void writeCtorInitializers(raw_ostream &OS) const = 0;
264 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0;
265 virtual void writeCtorParameters(raw_ostream &OS) const = 0;
266 virtual void writeDeclarations(raw_ostream &OS) const = 0;
267 virtual void writePCHReadArgs(raw_ostream &OS) const = 0;
268 virtual void writePCHReadDecls(raw_ostream &OS) const = 0;
269 virtual void writePCHWrite(raw_ostream &OS) const = 0;
270 virtual std::string getIsOmitted() const { return "false"; }
271 virtual void writeValue(raw_ostream &OS) const = 0;
272 virtual void writeDump(raw_ostream &OS) const = 0;
273 virtual void writeDumpChildren(raw_ostream &OS) const {}
274 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; }
275
276 virtual bool isEnumArg() const { return false; }
277 virtual bool isVariadicEnumArg() const { return false; }
278 virtual bool isVariadic() const { return false; }
279
280 virtual void writeImplicitCtorArgs(raw_ostream &OS) const {
281 OS << getUpperName();
282 }
283
284 constexpr StringRef getArgEqualityFn() const { return "equalAttrArgs"; }
285
286 virtual std::string emitAttrArgEqualityCheck() const {
287 std::string S = std::string("get") + std::string(getUpperName()) + "()";
288 return getArgEqualityFn().str() + "(" + S + ", Other." + S + ", Context)";
289 }
290
291 virtual std::string emitAttrArgProfileCall() const {
292 return "profileAttrArg(ID, Ctx, get" + getUpperName().str() + "())";
293 }
294 };
295
296 class SimpleArgument : public Argument {
297 std::string type;
298
299 public:
300 SimpleArgument(const Record &Arg, StringRef Attr, std::string T)
301 : Argument(Arg, Attr), type(std::move(T)) {}
302
303 std::string getType() const { return type; }
304
305 void writeAccessors(raw_ostream &OS) const override {
306 OS << " " << type << " get" << getUpperName() << "() const {\n";
307 OS << " return " << getLowerName() << ";\n";
308 OS << " }";
309 }
310
311 void writeCloneArgs(raw_ostream &OS) const override {
312 OS << getLowerName();
313 }
314
315 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
316 OS << "A->get" << getUpperName() << "()";
317 }
318
319 void writeCtorInitializers(raw_ostream &OS) const override {
320 OS << getLowerName() << "(" << getUpperName() << ")";
321 }
322
323 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
324 OS << getLowerName() << "()";
325 }
326
327 void writeCtorParameters(raw_ostream &OS) const override {
328 OS << type << " " << getUpperName();
329 }
330
331 void writeDeclarations(raw_ostream &OS) const override {
332 OS << type << " " << getLowerName() << ";";
333 }
334
335 void writePCHReadDecls(raw_ostream &OS) const override {
336 std::string read = ReadPCHRecord(type);
337 OS << " " << type << " " << getLowerName() << " = " << read << ";\n";
338 }
339
340 void writePCHReadArgs(raw_ostream &OS) const override {
341 OS << getLowerName();
342 }
343
344 void writePCHWrite(raw_ostream &OS) const override {
345 OS << " "
346 << WritePCHRecord(type, name: "SA->get" + getUpperName().str() + "()");
347 }
348
349 std::string getIsOmitted() const override {
350 auto IsOneOf = [](StringRef subject, auto... list) {
351 return ((subject == list) || ...);
352 };
353
354 if (IsOneOf(type, "const IdentifierInfo *", "Expr *"))
355 return "!get" + getUpperName().str() + "()";
356 if (IsOneOf(type, "TypeSourceInfo *"))
357 return "!get" + getUpperName().str() + "Loc()";
358 if (IsOneOf(type, "ParamIdx"))
359 return "!get" + getUpperName().str() + "().isValid()";
360
361 assert(IsOneOf(type, "unsigned", "int", "bool", "FunctionDecl *",
362 "VarDecl *"));
363 return "false";
364 }
365
366 void writeValue(raw_ostream &OS) const override {
367 if (type == "FunctionDecl *")
368 OS << "\" << get" << getUpperName()
369 << "()->getNameInfo().getAsString() << \"";
370 else if (type == "const IdentifierInfo *")
371 // Some non-optional (comma required) identifier arguments can be the
372 // empty string but are then recorded as a nullptr.
373 OS << "\" << (get" << getUpperName() << "() ? get" << getUpperName()
374 << "()->getName() : \"\") << \"";
375 else if (type == "VarDecl *")
376 OS << "\" << get" << getUpperName() << "()->getName() << \"";
377 else if (type == "TypeSourceInfo *")
378 OS << "\" << get" << getUpperName() << "().getAsString() << \"";
379 else if (type == "ParamIdx")
380 OS << "\" << get" << getUpperName() << "().getSourceIndex() << \"";
381 else
382 OS << "\" << get" << getUpperName() << "() << \"";
383 }
384
385 void writeDump(raw_ostream &OS) const override {
386 if (StringRef(type).ends_with(Suffix: "Decl *")) {
387 OS << " OS << \" \";\n";
388 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n";
389 } else if (type == "const IdentifierInfo *") {
390 // Some non-optional (comma required) identifier arguments can be the
391 // empty string but are then recorded as a nullptr.
392 OS << " if (SA->get" << getUpperName() << "())\n"
393 << " OS << \" \" << SA->get" << getUpperName()
394 << "()->getName();\n";
395 } else if (type == "TypeSourceInfo *") {
396 if (isOptional())
397 OS << " if (SA->get" << getUpperName() << "Loc())";
398 OS << " OS << \" \" << SA->get" << getUpperName()
399 << "().getAsString();\n";
400 } else if (type == "bool") {
401 OS << " if (SA->get" << getUpperName() << "()) OS << \" "
402 << getUpperName() << "\";\n";
403 } else if (type == "int" || type == "unsigned") {
404 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
405 } else if (type == "ParamIdx") {
406 if (isOptional())
407 OS << " if (SA->get" << getUpperName() << "().isValid())\n ";
408 OS << " OS << \" \" << SA->get" << getUpperName()
409 << "().getSourceIndex();\n";
410 } else if (type == "OMPTraitInfo *") {
411 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
412 } else {
413 llvm_unreachable("Unknown SimpleArgument type!");
414 }
415 }
416 };
417
418 class DefaultSimpleArgument : public SimpleArgument {
419 int64_t Default;
420
421 public:
422 DefaultSimpleArgument(const Record &Arg, StringRef Attr, std::string T,
423 int64_t Default)
424 : SimpleArgument(Arg, Attr, std::move(T)), Default(Default) {}
425
426 void writeAccessors(raw_ostream &OS) const override {
427 SimpleArgument::writeAccessors(OS);
428
429 OS << "\n\n static const " << getType() << " Default" << getUpperName()
430 << " = ";
431 if (getType() == "bool")
432 OS << (Default != 0 ? "true" : "false");
433 else
434 OS << Default;
435 OS << ";";
436 }
437 };
438
439 class StringArgument : public Argument {
440 public:
441 StringArgument(const Record &Arg, StringRef Attr)
442 : Argument(Arg, Attr)
443 {}
444
445 void writeAccessors(raw_ostream &OS) const override {
446 OS << " llvm::StringRef get" << getUpperName() << "() const {\n";
447 OS << " return llvm::StringRef(" << getLowerName() << ", "
448 << getLowerName() << "Length);\n";
449 OS << " }\n";
450 OS << " unsigned get" << getUpperName() << "Length() const {\n";
451 OS << " return " << getLowerName() << "Length;\n";
452 OS << " }\n";
453 OS << " void set" << getUpperName()
454 << "(ASTContext &C, llvm::StringRef S) {\n";
455 OS << " " << getLowerName() << "Length = S.size();\n";
456 OS << " this->" << getLowerName() << " = new (C, 1) char ["
457 << getLowerName() << "Length];\n";
458 OS << " if (!S.empty())\n";
459 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), "
460 << getLowerName() << "Length);\n";
461 OS << " }";
462 }
463
464 void writeCloneArgs(raw_ostream &OS) const override {
465 OS << "get" << getUpperName() << "()";
466 }
467
468 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
469 OS << "A->get" << getUpperName() << "()";
470 }
471
472 void writeCtorBody(raw_ostream &OS) const override {
473 OS << " if (!" << getUpperName() << ".empty())\n";
474 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName()
475 << ".data(), " << getLowerName() << "Length);\n";
476 }
477
478 void writeCtorInitializers(raw_ostream &OS) const override {
479 OS << getLowerName() << "Length(" << getUpperName() << ".size()),"
480 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName()
481 << "Length])";
482 }
483
484 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
485 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)";
486 }
487
488 void writeCtorParameters(raw_ostream &OS) const override {
489 OS << "llvm::StringRef " << getUpperName();
490 }
491
492 void writeDeclarations(raw_ostream &OS) const override {
493 OS << "unsigned " << getLowerName() << "Length;\n";
494 OS << "char *" << getLowerName() << ";";
495 }
496
497 void writePCHReadDecls(raw_ostream &OS) const override {
498 OS << " std::string " << getLowerName()
499 << "= Record.readString();\n";
500 }
501
502 void writePCHReadArgs(raw_ostream &OS) const override {
503 OS << getLowerName();
504 }
505
506 void writePCHWrite(raw_ostream &OS) const override {
507 OS << " Record.AddString(SA->get" << getUpperName() << "());\n";
508 }
509
510 void writeValue(raw_ostream &OS) const override {
511 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\"";
512 }
513
514 void writeDump(raw_ostream &OS) const override {
515 OS << " OS << \" \\\"\" << SA->get" << getUpperName()
516 << "() << \"\\\"\";\n";
517 }
518 };
519
520 class AlignedArgument : public Argument {
521 public:
522 AlignedArgument(const Record &Arg, StringRef Attr)
523 : Argument(Arg, Attr)
524 {}
525
526 void writeAccessors(raw_ostream &OS) const override {
527 OS << " bool is" << getUpperName() << "Dependent() const;\n";
528 OS << " bool is" << getUpperName() << "ErrorDependent() const;\n";
529
530 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n";
531
532 OS << " bool is" << getUpperName() << "Expr() const {\n";
533 OS << " return is" << getLowerName() << "Expr;\n";
534 OS << " }\n";
535
536 OS << " Expr *get" << getUpperName() << "Expr() const {\n";
537 OS << " assert(is" << getLowerName() << "Expr);\n";
538 OS << " return " << getLowerName() << "Expr;\n";
539 OS << " }\n";
540
541 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n";
542 OS << " assert(!is" << getLowerName() << "Expr);\n";
543 OS << " return " << getLowerName() << "Type;\n";
544 OS << " }";
545
546 OS << " std::optional<unsigned> getCached" << getUpperName()
547 << "Value() const {\n";
548 OS << " return " << getLowerName() << "Cache;\n";
549 OS << " }";
550
551 OS << " void setCached" << getUpperName()
552 << "Value(unsigned AlignVal) {\n";
553 OS << " " << getLowerName() << "Cache = AlignVal;\n";
554 OS << " }";
555 }
556
557 void writeAccessorDefinitions(raw_ostream &OS) const override {
558 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
559 << "Dependent() const {\n";
560 OS << " if (is" << getLowerName() << "Expr)\n";
561 OS << " return " << getLowerName() << "Expr && (" << getLowerName()
562 << "Expr->isValueDependent() || " << getLowerName()
563 << "Expr->isTypeDependent());\n";
564 OS << " else\n";
565 OS << " return " << getLowerName()
566 << "Type->getType()->isDependentType();\n";
567 OS << "}\n";
568
569 OS << "bool " << getAttrName() << "Attr::is" << getUpperName()
570 << "ErrorDependent() const {\n";
571 OS << " if (is" << getLowerName() << "Expr)\n";
572 OS << " return " << getLowerName() << "Expr && " << getLowerName()
573 << "Expr->containsErrors();\n";
574 OS << " return " << getLowerName()
575 << "Type->getType()->containsErrors();\n";
576 OS << "}\n";
577 }
578
579 void writeASTVisitorTraversal(raw_ostream &OS) const override {
580 StringRef Name = getUpperName();
581 OS << " if (A->is" << Name << "Expr()) {\n"
582 << " if (!getDerived().TraverseStmt(A->get" << Name << "Expr()))\n"
583 << " return false;\n"
584 << " } else if (auto *TSI = A->get" << Name << "Type()) {\n"
585 << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n"
586 << " return false;\n"
587 << " }\n";
588 }
589
590 void writeCloneArgs(raw_ostream &OS) const override {
591 OS << "is" << getLowerName() << "Expr, is" << getLowerName()
592 << "Expr ? static_cast<void*>(" << getLowerName()
593 << "Expr) : " << getLowerName()
594 << "Type";
595 }
596
597 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
598 // FIXME: move the definition in Sema::InstantiateAttrs to here.
599 // In the meantime, aligned attributes are cloned.
600 }
601
602 void writeCtorBody(raw_ostream &OS) const override {
603 OS << " if (is" << getLowerName() << "Expr)\n";
604 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>("
605 << getUpperName() << ");\n";
606 OS << " else\n";
607 OS << " " << getLowerName()
608 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName()
609 << ");\n";
610 }
611
612 void writeCtorInitializers(raw_ostream &OS) const override {
613 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)";
614 }
615
616 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
617 OS << "is" << getLowerName() << "Expr(false)";
618 }
619
620 void writeCtorParameters(raw_ostream &OS) const override {
621 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName();
622 }
623
624 void writeImplicitCtorArgs(raw_ostream &OS) const override {
625 OS << "Is" << getUpperName() << "Expr, " << getUpperName();
626 }
627
628 void writeDeclarations(raw_ostream &OS) const override {
629 OS << "bool is" << getLowerName() << "Expr;\n";
630 OS << "union {\n";
631 OS << "Expr *" << getLowerName() << "Expr;\n";
632 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n";
633 OS << "};\n";
634 OS << "std::optional<unsigned> " << getLowerName() << "Cache;\n";
635 }
636
637 void writePCHReadArgs(raw_ostream &OS) const override {
638 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr";
639 }
640
641 void writePCHReadDecls(raw_ostream &OS) const override {
642 OS << " bool is" << getLowerName() << "Expr = Record.readInt();\n";
643 OS << " void *" << getLowerName() << "Ptr;\n";
644 OS << " if (is" << getLowerName() << "Expr)\n";
645 OS << " " << getLowerName() << "Ptr = Record.readExpr();\n";
646 OS << " else\n";
647 OS << " " << getLowerName()
648 << "Ptr = Record.readTypeSourceInfo();\n";
649 }
650
651 void writePCHWrite(raw_ostream &OS) const override {
652 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n";
653 OS << " if (SA->is" << getUpperName() << "Expr())\n";
654 OS << " Record.AddStmt(SA->get" << getUpperName() << "Expr());\n";
655 OS << " else\n";
656 OS << " Record.AddTypeSourceInfo(SA->get" << getUpperName()
657 << "Type());\n";
658 }
659
660 std::string getIsOmitted() const override {
661 return "!((is" + getLowerName().str() + "Expr && " +
662 getLowerName().str() + "Expr) || (!is" + getLowerName().str() +
663 "Expr && " + getLowerName().str() + "Type))";
664 }
665
666 void writeValue(raw_ostream &OS) const override {
667 OS << "\";\n";
668 OS << " if (is" << getLowerName() << "Expr && " << getLowerName()
669 << "Expr)";
670 OS << " " << getLowerName()
671 << "Expr->printPretty(OS, nullptr, Policy);\n";
672 OS << " if (!is" << getLowerName() << "Expr && " << getLowerName()
673 << "Type)";
674 OS << " " << getLowerName()
675 << "Type->getType().print(OS, Policy);\n";
676 OS << " OS << \"";
677 }
678
679 void writeDump(raw_ostream &OS) const override {
680 OS << " if (!SA->is" << getUpperName() << "Expr())\n";
681 OS << " dumpType(SA->get" << getUpperName()
682 << "Type()->getType());\n";
683 }
684
685 void writeDumpChildren(raw_ostream &OS) const override {
686 OS << " if (SA->is" << getUpperName() << "Expr())\n";
687 OS << " Visit(SA->get" << getUpperName() << "Expr());\n";
688 }
689
690 void writeHasChildren(raw_ostream &OS) const override {
691 OS << "SA->is" << getUpperName() << "Expr()";
692 }
693
694 std::string emitAttrArgEqualityCheck() const override {
695 auto GetStr = [&](bool Other) {
696 std::string CtxStr = Other ? "Context.ToCtx" : "Context.FromCtx";
697 std::string S = std::string("get") + std::string(getUpperName()) + "(" +
698 CtxStr + ")";
699 return S;
700 };
701 return getArgEqualityFn().str() + "(" + GetStr(false) + ", Other." +
702 GetStr(true) + ", Context)";
703 }
704 };
705
706 class VariadicArgument : public Argument {
707 std::string Type, ArgName, ArgSizeName, RangeName;
708
709 protected:
710 // Assumed to receive a parameter: raw_ostream OS.
711 virtual void writeValueImpl(raw_ostream &OS) const {
712 OS << " OS << Val;\n";
713 }
714 // Assumed to receive a parameter: raw_ostream OS.
715 virtual void writeDumpImpl(raw_ostream &OS) const {
716 OS << " OS << \" \" << Val;\n";
717 }
718
719 public:
720 VariadicArgument(const Record &Arg, StringRef Attr, std::string T)
721 : Argument(Arg, Attr), Type(std::move(T)),
722 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
723 RangeName(getLowerName().str()) {}
724
725 VariadicArgument(StringRef Arg, StringRef Attr, std::string T)
726 : Argument(Arg, Attr), Type(std::move(T)),
727 ArgName(getLowerName().str() + "_"), ArgSizeName(ArgName + "Size"),
728 RangeName(getLowerName().str()) {}
729
730 const std::string &getType() const { return Type; }
731 const std::string &getArgName() const { return ArgName; }
732 const std::string &getArgSizeName() const { return ArgSizeName; }
733 bool isVariadic() const override { return true; }
734
735 void writeAccessors(raw_ostream &OS) const override {
736 std::string IteratorType = getLowerName().str() + "_iterator";
737 std::string BeginFn = getLowerName().str() + "_begin()";
738 std::string EndFn = getLowerName().str() + "_end()";
739
740 OS << " typedef " << Type << "* " << IteratorType << ";\n";
741 OS << " " << IteratorType << " " << BeginFn << " const {"
742 << " return " << ArgName << "; }\n";
743 OS << " " << IteratorType << " " << EndFn << " const {"
744 << " return " << ArgName << " + " << ArgSizeName << "; }\n";
745 OS << " unsigned " << getLowerName() << "_size() const {"
746 << " return " << ArgSizeName << "; }\n";
747 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName
748 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn
749 << "); }\n";
750 }
751
752 void writeSetter(raw_ostream &OS) const {
753 OS << " void set" << getUpperName() << "(ASTContext &Ctx, ";
754 writeCtorParameters(OS);
755 OS << ") {\n";
756 OS << " " << ArgSizeName << " = " << getUpperName() << "Size;\n";
757 OS << " " << ArgName << " = new (Ctx, 16) " << getType() << "["
758 << ArgSizeName << "];\n";
759 OS << " ";
760 writeCtorBody(OS);
761 OS << " }\n";
762 }
763
764 void writeCloneArgs(raw_ostream &OS) const override {
765 OS << ArgName << ", " << ArgSizeName;
766 }
767
768 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
769 // This isn't elegant, but we have to go through public methods...
770 OS << "A->" << getLowerName() << "_begin(), "
771 << "A->" << getLowerName() << "_size()";
772 }
773
774 void writeASTVisitorTraversal(raw_ostream &OS) const override {
775 // FIXME: Traverse the elements.
776 }
777
778 void writeCtorBody(raw_ostream &OS) const override {
779 OS << " std::copy(" << getUpperName() << ", " << getUpperName() << " + "
780 << ArgSizeName << ", " << ArgName << ");\n";
781 }
782
783 void writeCtorInitializers(raw_ostream &OS) const override {
784 OS << ArgSizeName << "(" << getUpperName() << "Size), "
785 << ArgName << "(new (Ctx, 16) " << getType() << "["
786 << ArgSizeName << "])";
787 }
788
789 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
790 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)";
791 }
792
793 void writeCtorParameters(raw_ostream &OS) const override {
794 OS << getType() << " *" << getUpperName() << ", unsigned "
795 << getUpperName() << "Size";
796 }
797
798 void writeImplicitCtorArgs(raw_ostream &OS) const override {
799 OS << getUpperName() << ", " << getUpperName() << "Size";
800 }
801
802 void writeDeclarations(raw_ostream &OS) const override {
803 OS << " unsigned " << ArgSizeName << ";\n";
804 OS << " " << getType() << " *" << ArgName << ";";
805 }
806
807 void writePCHReadDecls(raw_ostream &OS) const override {
808 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
809 OS << " SmallVector<" << getType() << ", 4> "
810 << getLowerName() << ";\n";
811 OS << " " << getLowerName() << ".reserve(" << getLowerName()
812 << "Size);\n";
813
814 // If we can't store the values in the current type (if it's something
815 // like StringRef), store them in a different type and convert the
816 // container afterwards.
817 std::string StorageType = getStorageType(type: getType()).str();
818 std::string StorageName = getLowerName().str();
819 if (StorageType != getType()) {
820 StorageName += "Storage";
821 OS << " SmallVector<" << StorageType << ", 4> "
822 << StorageName << ";\n";
823 OS << " " << StorageName << ".reserve(" << getLowerName()
824 << "Size);\n";
825 }
826
827 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
828 std::string read = ReadPCHRecord(type: Type);
829 OS << " " << StorageName << ".push_back(" << read << ");\n";
830
831 if (StorageType != getType()) {
832 OS << " for (unsigned i = 0; i != " << getLowerName() << "Size; ++i)\n";
833 OS << " " << getLowerName() << ".push_back("
834 << StorageName << "[i]);\n";
835 }
836 }
837
838 void writePCHReadArgs(raw_ostream &OS) const override {
839 OS << getLowerName() << ".data(), " << getLowerName() << "Size";
840 }
841
842 void writePCHWrite(raw_ostream &OS) const override {
843 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
844 OS << " for (auto &Val : SA->" << RangeName << "())\n";
845 OS << " " << WritePCHRecord(type: Type, name: "Val");
846 }
847
848 void writeValue(raw_ostream &OS) const override {
849 OS << "\";\n";
850 OS << " for (const auto &Val : " << RangeName << "()) {\n"
851 << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
852 writeValueImpl(OS);
853 OS << " }\n";
854 OS << " OS << \"";
855 }
856
857 void writeDump(raw_ostream &OS) const override {
858 OS << " for (const auto &Val : SA->" << RangeName << "())\n";
859 writeDumpImpl(OS);
860 }
861
862 std::string emitAttrArgEqualityCheck() const override {
863 auto GenIter = [&](bool IsOther, const std::string &Suffix) {
864 std::string S = IsOther ? "Other." : "";
865 std::string LN = getLowerName().str();
866 S += LN + "_" + Suffix + "()";
867 return S;
868 };
869
870 return getArgEqualityFn().str() + "(" + GenIter(false, "begin") + ", " +
871 GenIter(false, "end") + ", " + GenIter(true, "begin") + ", " +
872 GenIter(true, "end") + ", Context)";
873 }
874
875 std::string emitAttrArgProfileCall() const override {
876 std::string LN = getLowerName().str();
877 return "profileAttrArg(ID, Ctx, " + LN + "_begin(), " + LN + "_end())";
878 }
879 };
880
881 class VariadicOMPInteropInfoArgument : public VariadicArgument {
882 public:
883 VariadicOMPInteropInfoArgument(const Record &Arg, StringRef Attr)
884 : VariadicArgument(Arg, Attr, "OMPInteropInfo") {}
885
886 void writeDump(raw_ostream &OS) const override {
887 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
888 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
889 << getLowerName() << "_end(); I != E; ++I) {\n";
890 OS << " if (I->IsTarget && I->IsTargetSync)\n";
891 OS << " OS << \" Target_TargetSync\";\n";
892 OS << " else if (I->IsTarget)\n";
893 OS << " OS << \" Target\";\n";
894 OS << " else\n";
895 OS << " OS << \" TargetSync\";\n";
896 OS << " }\n";
897 }
898
899 void writePCHReadDecls(raw_ostream &OS) const override {
900 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
901 OS << " SmallVector<OMPInteropInfo, 4> " << getLowerName() << ";\n";
902 OS << " " << getLowerName() << ".reserve(" << getLowerName()
903 << "Size);\n";
904 OS << " for (unsigned I = 0, E = " << getLowerName() << "Size; ";
905 OS << "I != E; ++I) {\n";
906 OS << " bool IsTarget = Record.readBool();\n";
907 OS << " bool IsTargetSync = Record.readBool();\n";
908 OS << " " << getLowerName()
909 << ".emplace_back(IsTarget, IsTargetSync);\n";
910 OS << " }\n";
911 }
912
913 void writePCHWrite(raw_ostream &OS) const override {
914 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
915 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
916 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
917 << getLowerName() << "_end(); I != E; ++I) {\n";
918 OS << " Record.writeBool(I->IsTarget);\n";
919 OS << " Record.writeBool(I->IsTargetSync);\n";
920 OS << " }\n";
921 }
922 };
923
924 class VariadicParamIdxArgument : public VariadicArgument {
925 public:
926 VariadicParamIdxArgument(const Record &Arg, StringRef Attr)
927 : VariadicArgument(Arg, Attr, "ParamIdx") {}
928
929 public:
930 void writeValueImpl(raw_ostream &OS) const override {
931 OS << " OS << Val.getSourceIndex();\n";
932 }
933
934 void writeDumpImpl(raw_ostream &OS) const override {
935 OS << " OS << \" \" << Val.getSourceIndex();\n";
936 }
937 };
938
939 struct VariadicParamOrParamIdxArgument : public VariadicArgument {
940 VariadicParamOrParamIdxArgument(const Record &Arg, StringRef Attr)
941 : VariadicArgument(Arg, Attr, "int") {}
942 };
943
944 // Unique the enums, but maintain the original declaration ordering.
945 std::vector<StringRef>
946 uniqueEnumsInOrder(const std::vector<StringRef> &enums) {
947 std::vector<StringRef> uniques;
948 SmallDenseSet<StringRef, 8> unique_set;
949 for (const auto &i : enums) {
950 if (unique_set.insert(V: i).second)
951 uniques.push_back(x: i);
952 }
953 return uniques;
954 }
955
956 class EnumArgument : public Argument {
957 std::string fullType;
958 StringRef shortType;
959 std::vector<StringRef> values, enums, uniques;
960 bool isExternal;
961 bool isCovered;
962
963 public:
964 EnumArgument(const Record &Arg, StringRef Attr)
965 : Argument(Arg, Attr), values(Arg.getValueAsListOfStrings(FieldName: "Values")),
966 enums(Arg.getValueAsListOfStrings(FieldName: "Enums")),
967 uniques(uniqueEnumsInOrder(enums)),
968 isExternal(Arg.getValueAsBit(FieldName: "IsExternalType")),
969 isCovered(Arg.getValueAsBit(FieldName: "IsCovered")) {
970 StringRef Type = Arg.getValueAsString(FieldName: "Type");
971 shortType = isExternal ? Type.rsplit(Separator: "::").second : Type;
972 // If shortType didn't contain :: at all rsplit will give us an empty
973 // string.
974 if (shortType.empty())
975 shortType = Type;
976 fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
977
978 // FIXME: Emit a proper error
979 assert(!uniques.empty());
980 }
981
982 bool isEnumArg() const override { return true; }
983
984 void writeAccessors(raw_ostream &OS) const override {
985 OS << " " << fullType << " get" << getUpperName() << "() const {\n";
986 OS << " return " << getLowerName() << ";\n";
987 OS << " }";
988 }
989
990 void writeCloneArgs(raw_ostream &OS) const override {
991 OS << getLowerName();
992 }
993
994 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
995 OS << "A->get" << getUpperName() << "()";
996 }
997 void writeCtorInitializers(raw_ostream &OS) const override {
998 OS << getLowerName() << "(" << getUpperName() << ")";
999 }
1000 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1001 OS << getLowerName() << "(" << fullType << "(0))";
1002 }
1003 void writeCtorParameters(raw_ostream &OS) const override {
1004 OS << fullType << " " << getUpperName();
1005 }
1006 void writeDeclarations(raw_ostream &OS) const override {
1007 if (!isExternal) {
1008 auto i = uniques.cbegin(), e = uniques.cend();
1009 // The last one needs to not have a comma.
1010 --e;
1011
1012 OS << "public:\n";
1013 OS << " enum " << shortType << " {\n";
1014 for (; i != e; ++i)
1015 OS << " " << *i << ",\n";
1016 OS << " " << *e << "\n";
1017 OS << " };\n";
1018 }
1019
1020 OS << "private:\n";
1021 OS << " " << fullType << " " << getLowerName() << ";";
1022 }
1023
1024 void writePCHReadDecls(raw_ostream &OS) const override {
1025 OS << " " << fullType << " " << getLowerName() << "(static_cast<"
1026 << fullType << ">(Record.readInt()));\n";
1027 }
1028
1029 void writePCHReadArgs(raw_ostream &OS) const override {
1030 OS << getLowerName();
1031 }
1032
1033 void writePCHWrite(raw_ostream &OS) const override {
1034 OS << "Record.push_back(static_cast<uint64_t>(SA->get" << getUpperName()
1035 << "()));\n";
1036 }
1037
1038 void writeValue(raw_ostream &OS) const override {
1039 // FIXME: this isn't 100% correct -- some enum arguments require printing
1040 // as a string literal, while others require printing as an identifier.
1041 // Tablegen currently does not distinguish between the two forms.
1042 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << shortType
1043 << "ToStr(get" << getUpperName() << "()) << \"\\\"";
1044 }
1045
1046 void writeDump(raw_ostream &OS) const override {
1047 OS << " switch(SA->get" << getUpperName() << "()) {\n";
1048 for (const auto &I : uniques) {
1049 OS << " case " << fullType << "::" << I << ":\n";
1050 OS << " OS << \" " << I << "\";\n";
1051 OS << " break;\n";
1052 }
1053 if (!isCovered) {
1054 OS << " default:\n";
1055 OS << " llvm_unreachable(\"Invalid attribute value\");\n";
1056 }
1057 OS << " }\n";
1058 }
1059
1060 void writeConversion(raw_ostream &OS, bool Header) const {
1061 if (Header) {
1062 OS << " static bool ConvertStrTo" << shortType << "(StringRef Val, "
1063 << fullType << " &Out);\n";
1064 OS << " static const char *Convert" << shortType << "ToStr("
1065 << fullType << " Val);\n";
1066 return;
1067 }
1068
1069 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1070 << "(StringRef Val, " << fullType << " &Out) {\n";
1071 OS << " std::optional<" << fullType << "> "
1072 << "R = llvm::StringSwitch<std::optional<" << fullType << ">>(Val)\n";
1073 for (size_t I = 0; I < enums.size(); ++I) {
1074 OS << " .Case(\"" << values[I] << "\", ";
1075 OS << fullType << "::" << enums[I] << ")\n";
1076 }
1077 OS << " .Default(std::optional<" << fullType << ">());\n";
1078 OS << " if (R) {\n";
1079 OS << " Out = *R;\n return true;\n }\n";
1080 OS << " return false;\n";
1081 OS << "}\n\n";
1082
1083 // Mapping from enumeration values back to enumeration strings isn't
1084 // trivial because some enumeration values have multiple named
1085 // enumerators, such as type_visibility(internal) and
1086 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden.
1087 OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1088 << "ToStr(" << fullType << " Val) {\n"
1089 << " switch(Val) {\n";
1090 SmallDenseSet<StringRef, 8> Uniques;
1091 for (size_t I = 0; I < enums.size(); ++I) {
1092 if (Uniques.insert(V: enums[I]).second)
1093 OS << " case " << fullType << "::" << enums[I] << ": return \""
1094 << values[I] << "\";\n";
1095 }
1096 if (!isCovered) {
1097 OS << " default: llvm_unreachable(\"Invalid attribute value\");\n";
1098 }
1099 OS << " }\n"
1100 << " llvm_unreachable(\"No enumerator with that value\");\n"
1101 << "}\n";
1102 }
1103 };
1104
1105 class VariadicEnumArgument: public VariadicArgument {
1106 std::string fullType;
1107 StringRef shortType;
1108 std::vector<StringRef> values, enums, uniques;
1109 bool isExternal;
1110 bool isCovered;
1111
1112 protected:
1113 void writeValueImpl(raw_ostream &OS) const override {
1114 // FIXME: this isn't 100% correct -- some enum arguments require printing
1115 // as a string literal, while others require printing as an identifier.
1116 // Tablegen currently does not distinguish between the two forms.
1117 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert"
1118 << shortType << "ToStr(Val)"
1119 << "<< \"\\\"\";\n";
1120 }
1121
1122 public:
1123 VariadicEnumArgument(const Record &Arg, StringRef Attr)
1124 : VariadicArgument(Arg, Attr, Arg.getValueAsString(FieldName: "Type").str()),
1125 values(Arg.getValueAsListOfStrings(FieldName: "Values")),
1126 enums(Arg.getValueAsListOfStrings(FieldName: "Enums")),
1127 uniques(uniqueEnumsInOrder(enums)),
1128 isExternal(Arg.getValueAsBit(FieldName: "IsExternalType")),
1129 isCovered(Arg.getValueAsBit(FieldName: "IsCovered")) {
1130 StringRef Type = Arg.getValueAsString(FieldName: "Type");
1131 shortType = isExternal ? Type.rsplit(Separator: "::").second : Type;
1132 // If shortType didn't contain :: at all rsplit will give us an empty
1133 // string.
1134 if (shortType.empty())
1135 shortType = Type;
1136 fullType = isExternal ? Type : (getAttrName() + "Attr::" + Type).str();
1137
1138 // FIXME: Emit a proper error
1139 assert(!uniques.empty());
1140 }
1141
1142 bool isVariadicEnumArg() const override { return true; }
1143
1144 void writeDeclarations(raw_ostream &OS) const override {
1145 if (!isExternal) {
1146 auto i = uniques.cbegin(), e = uniques.cend();
1147 // The last one needs to not have a comma.
1148 --e;
1149
1150 OS << "public:\n";
1151 OS << " enum " << shortType << " {\n";
1152 for (; i != e; ++i)
1153 OS << " " << *i << ",\n";
1154 OS << " " << *e << "\n";
1155 OS << " };\n";
1156 }
1157 OS << "private:\n";
1158
1159 VariadicArgument::writeDeclarations(OS);
1160 }
1161
1162 void writeDump(raw_ostream &OS) const override {
1163 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1164 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1165 << getLowerName() << "_end(); I != E; ++I) {\n";
1166 OS << " switch(*I) {\n";
1167 for (const auto &UI : uniques) {
1168 OS << " case " << fullType << "::" << UI << ":\n";
1169 OS << " OS << \" " << UI << "\";\n";
1170 OS << " break;\n";
1171 }
1172 if (!isCovered) {
1173 OS << " default:\n";
1174 OS << " llvm_unreachable(\"Invalid attribute value\");\n";
1175 }
1176 OS << " }\n";
1177 OS << " }\n";
1178 }
1179
1180 void writePCHReadDecls(raw_ostream &OS) const override {
1181 OS << " unsigned " << getLowerName() << "Size = Record.readInt();\n";
1182 OS << " SmallVector<" << fullType << ", 4> " << getLowerName()
1183 << ";\n";
1184 OS << " " << getLowerName() << ".reserve(" << getLowerName()
1185 << "Size);\n";
1186 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n";
1187 OS << " " << getLowerName() << ".push_back("
1188 << "static_cast<" << fullType << ">(Record.readInt()));\n";
1189 }
1190
1191 void writePCHWrite(raw_ostream &OS) const override {
1192 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n";
1193 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1194 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->"
1195 << getLowerName() << "_end(); i != e; ++i)\n";
1196 OS << " " << WritePCHRecord(type: fullType, name: "(*i)");
1197 }
1198
1199 void writeConversion(raw_ostream &OS, bool Header) const {
1200 if (Header) {
1201 OS << " static bool ConvertStrTo" << shortType << "(StringRef Val, "
1202 << fullType << " &Out);\n";
1203 OS << " static const char *Convert" << shortType << "ToStr("
1204 << fullType << " Val);\n";
1205 return;
1206 }
1207
1208 OS << "bool " << getAttrName() << "Attr::ConvertStrTo" << shortType
1209 << "(StringRef Val, ";
1210 OS << fullType << " &Out) {\n";
1211 OS << " std::optional<" << fullType
1212 << "> R = llvm::StringSwitch<std::optional<";
1213 OS << fullType << ">>(Val)\n";
1214 for (size_t I = 0; I < enums.size(); ++I) {
1215 OS << " .Case(\"" << values[I] << "\", ";
1216 OS << fullType << "::" << enums[I] << ")\n";
1217 }
1218 OS << " .Default(std::optional<" << fullType << ">());\n";
1219 OS << " if (R) {\n";
1220 OS << " Out = *R;\n return true;\n }\n";
1221 OS << " return false;\n";
1222 OS << "}\n\n";
1223
1224 OS << "const char *" << getAttrName() << "Attr::Convert" << shortType
1225 << "ToStr(" << fullType << " Val) {\n"
1226 << " switch(Val) {\n";
1227 SmallDenseSet<StringRef, 8> Uniques;
1228 for (size_t I = 0; I < enums.size(); ++I) {
1229 if (Uniques.insert(V: enums[I]).second)
1230 OS << " case " << fullType << "::" << enums[I] << ": return \""
1231 << values[I] << "\";\n";
1232 }
1233 if (!isCovered) {
1234 OS << " default: llvm_unreachable(\"Invalid attribute value\");\n";
1235 }
1236 OS << " }\n"
1237 << " llvm_unreachable(\"No enumerator with that value\");\n"
1238 << "}\n";
1239 }
1240 };
1241
1242 class VersionArgument : public Argument {
1243 public:
1244 VersionArgument(const Record &Arg, StringRef Attr)
1245 : Argument(Arg, Attr)
1246 {}
1247
1248 void writeAccessors(raw_ostream &OS) const override {
1249 OS << " VersionTuple get" << getUpperName() << "() const {\n";
1250 OS << " return " << getLowerName() << ";\n";
1251 OS << " }\n";
1252 OS << " void set" << getUpperName()
1253 << "(ASTContext &C, VersionTuple V) {\n";
1254 OS << " " << getLowerName() << " = V;\n";
1255 OS << " }";
1256 }
1257
1258 void writeCloneArgs(raw_ostream &OS) const override {
1259 OS << "get" << getUpperName() << "()";
1260 }
1261
1262 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1263 OS << "A->get" << getUpperName() << "()";
1264 }
1265
1266 void writeCtorInitializers(raw_ostream &OS) const override {
1267 OS << getLowerName() << "(" << getUpperName() << ")";
1268 }
1269
1270 void writeCtorDefaultInitializers(raw_ostream &OS) const override {
1271 OS << getLowerName() << "()";
1272 }
1273
1274 void writeCtorParameters(raw_ostream &OS) const override {
1275 OS << "VersionTuple " << getUpperName();
1276 }
1277
1278 void writeDeclarations(raw_ostream &OS) const override {
1279 OS << "VersionTuple " << getLowerName() << ";\n";
1280 }
1281
1282 void writePCHReadDecls(raw_ostream &OS) const override {
1283 OS << " VersionTuple " << getLowerName()
1284 << "= Record.readVersionTuple();\n";
1285 }
1286
1287 void writePCHReadArgs(raw_ostream &OS) const override {
1288 OS << getLowerName();
1289 }
1290
1291 void writePCHWrite(raw_ostream &OS) const override {
1292 OS << " Record.AddVersionTuple(SA->get" << getUpperName() << "());\n";
1293 }
1294
1295 void writeValue(raw_ostream &OS) const override {
1296 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \"";
1297 }
1298
1299 void writeDump(raw_ostream &OS) const override {
1300 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n";
1301 }
1302 };
1303
1304 class ExprArgument : public SimpleArgument {
1305 public:
1306 ExprArgument(const Record &Arg, StringRef Attr)
1307 : SimpleArgument(Arg, Attr, "Expr *")
1308 {}
1309
1310 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1311 OS << " if (!"
1312 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n";
1313 OS << " return false;\n";
1314 }
1315
1316 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1317 OS << "tempInst" << getUpperName();
1318 }
1319
1320 void writeTemplateInstantiation(raw_ostream &OS) const override {
1321 OS << " " << getType() << " tempInst" << getUpperName() << ";\n";
1322 OS << " {\n";
1323 OS << " EnterExpressionEvaluationContext "
1324 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1325 OS << " ExprResult " << "Result = S.SubstExpr("
1326 << "A->get" << getUpperName() << "(), TemplateArgs);\n";
1327 OS << " if (Result.isInvalid())\n";
1328 OS << " return nullptr;\n";
1329 OS << " tempInst" << getUpperName() << " = Result.get();\n";
1330 OS << " }\n";
1331 }
1332
1333 void writeValue(raw_ostream &OS) const override {
1334 OS << "\";\n";
1335 OS << " get" << getUpperName()
1336 << "()->printPretty(OS, nullptr, Policy);\n";
1337 OS << " OS << \"";
1338 }
1339
1340 void writeDump(raw_ostream &OS) const override {}
1341
1342 void writeDumpChildren(raw_ostream &OS) const override {
1343 OS << " Visit(SA->get" << getUpperName() << "());\n";
1344 }
1345
1346 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; }
1347 };
1348
1349 class VariadicExprArgument : public VariadicArgument {
1350 public:
1351 VariadicExprArgument(const Record &Arg, StringRef Attr)
1352 : VariadicArgument(Arg, Attr, "Expr *")
1353 {}
1354
1355 VariadicExprArgument(StringRef ArgName, StringRef Attr)
1356 : VariadicArgument(ArgName, Attr, "Expr *") {}
1357
1358 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1359 OS << " {\n";
1360 OS << " " << getType() << " *I = A->" << getLowerName()
1361 << "_begin();\n";
1362 OS << " " << getType() << " *E = A->" << getLowerName()
1363 << "_end();\n";
1364 OS << " for (; I != E; ++I) {\n";
1365 OS << " if (!getDerived().TraverseStmt(*I))\n";
1366 OS << " return false;\n";
1367 OS << " }\n";
1368 OS << " }\n";
1369 }
1370
1371 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1372 OS << "tempInst" << getUpperName() << ", "
1373 << "numTempInst" << getUpperName();
1374 }
1375
1376 void writeTemplateInstantiation(raw_ostream &OS) const override {
1377 OS << " size_t numTempInst" << getUpperName() << ";\n";
1378 OS << " " << getType() << "*tempInst" << getUpperName() << ";\n";
1379 OS << " {\n";
1380 OS << " EnterExpressionEvaluationContext "
1381 << "Unevaluated(S, Sema::ExpressionEvaluationContext::Unevaluated);\n";
1382 OS << " ArrayRef<" << getType() << "> ArgsToInstantiate(A->"
1383 << getLowerName() << "_begin(), A->" << getLowerName() << "_end());\n";
1384 OS << " SmallVector<" << getType() << ", 4> InstArgs;\n";
1385 OS << " if (S.SubstExprs(ArgsToInstantiate, /*IsCall=*/false, "
1386 "TemplateArgs, InstArgs))\n";
1387 OS << " return nullptr;\n";
1388 OS << " numTempInst" << getUpperName() << " = InstArgs.size();\n";
1389 OS << " tempInst" << getUpperName() << " = new (C, 16) "
1390 << getType() << "[numTempInst" << getUpperName() << "];\n";
1391 OS << " std::copy(InstArgs.begin(), InstArgs.end(), tempInst"
1392 << getUpperName() << ");\n";
1393 OS << " }\n";
1394 }
1395
1396 void writeDump(raw_ostream &OS) const override {}
1397
1398 void writeDumpChildren(raw_ostream &OS) const override {
1399 OS << " for (" << getAttrName() << "Attr::" << getLowerName()
1400 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->"
1401 << getLowerName() << "_end(); I != E; ++I)\n";
1402 OS << " Visit(*I);\n";
1403 }
1404
1405 void writeHasChildren(raw_ostream &OS) const override {
1406 OS << "SA->" << getLowerName() << "_begin() != "
1407 << "SA->" << getLowerName() << "_end()";
1408 }
1409 };
1410
1411 class VariadicIdentifierArgument : public VariadicArgument {
1412 public:
1413 VariadicIdentifierArgument(const Record &Arg, StringRef Attr)
1414 : VariadicArgument(Arg, Attr, "const IdentifierInfo *") {}
1415 };
1416
1417 class VariadicStringArgument : public VariadicArgument {
1418 public:
1419 VariadicStringArgument(const Record &Arg, StringRef Attr)
1420 : VariadicArgument(Arg, Attr, "StringRef")
1421 {}
1422
1423 void writeCtorBody(raw_ostream &OS) const override {
1424 OS << " for (size_t I = 0, E = " << getArgSizeName() << "; I != E;\n"
1425 " ++I) {\n"
1426 " StringRef Ref = " << getUpperName() << "[I];\n"
1427 " if (!Ref.empty()) {\n"
1428 " char *Mem = new (Ctx, 1) char[Ref.size()];\n"
1429 " std::memcpy(Mem, Ref.data(), Ref.size());\n"
1430 " " << getArgName() << "[I] = StringRef(Mem, Ref.size());\n"
1431 " }\n"
1432 " }\n";
1433 }
1434
1435 void writeValueImpl(raw_ostream &OS) const override {
1436 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n";
1437 }
1438 };
1439
1440 class TypeArgument : public SimpleArgument {
1441 public:
1442 TypeArgument(const Record &Arg, StringRef Attr)
1443 : SimpleArgument(Arg, Attr, "TypeSourceInfo *")
1444 {}
1445
1446 void writeAccessors(raw_ostream &OS) const override {
1447 OS << " QualType get" << getUpperName() << "() const {\n";
1448 OS << " return " << getLowerName() << "->getType();\n";
1449 OS << " }";
1450 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n";
1451 OS << " return " << getLowerName() << ";\n";
1452 OS << " }";
1453 }
1454
1455 void writeASTVisitorTraversal(raw_ostream &OS) const override {
1456 OS << " if (auto *TSI = A->get" << getUpperName() << "Loc())\n";
1457 OS << " if (!getDerived().TraverseTypeLoc(TSI->getTypeLoc()))\n";
1458 OS << " return false;\n";
1459 }
1460
1461 void writeTemplateInstantiation(raw_ostream &OS) const override {
1462 OS << " " << getType() << " tempInst" << getUpperName() << " =\n";
1463 OS << " S.SubstType(A->get" << getUpperName() << "Loc(), "
1464 << "TemplateArgs, A->getLoc(), A->getAttrName());\n";
1465 OS << " if (!tempInst" << getUpperName() << ")\n";
1466 OS << " return nullptr;\n";
1467 }
1468
1469 void writeTemplateInstantiationArgs(raw_ostream &OS) const override {
1470 OS << "tempInst" << getUpperName();
1471 }
1472
1473 void writePCHWrite(raw_ostream &OS) const override {
1474 OS << " "
1475 << WritePCHRecord(type: getType(),
1476 name: "SA->get" + getUpperName().str() + "Loc()");
1477 }
1478 };
1479
1480 class WrappedAttr : public SimpleArgument {
1481 std::string AttrType; // C++ class name for the wrapped attr
1482
1483 public:
1484 WrappedAttr(const Record &Arg, StringRef Attr)
1485 : SimpleArgument(Arg, Attr, "Attr *"),
1486 AttrType(Arg.getValueAsString(FieldName: "AttrType")) {}
1487
1488 void writeAccessors(raw_ostream &OS) const override {
1489 // The field is always stored as Attr * regardless of AttrType. This is
1490 // required because the generated isEquivalent method calls
1491 // equalAttrArgs(getInferredAttr(), Other.getInferredAttr(), Context).
1492 // If the field were AttrType * (e.g. AvailabilityAttr *), that call
1493 // would instantiate equalAttrArgs<AvailabilityAttr *>, which has no
1494 // specialization and returns false. Storing Attr * routes the call
1495 // through equalAttrArgs<Attr *>, which handles null and calls
1496 // isEquivalent. Typed get<Name>As() / set<Name>As() accessors are
1497 // provided for callers that need the specific type.
1498 OS << " Attr *get" << getUpperName() << "() const {\n";
1499 OS << " return " << getLowerName() << ";\n";
1500 OS << " }\n";
1501 OS << " void set" << getUpperName() << "(Attr *V) {\n";
1502 OS << " " << getLowerName() << " = V;\n";
1503 OS << " }";
1504 if (!AttrType.empty()) {
1505 OS << "\n";
1506 OS << " " << AttrType << " *get" << getUpperName() << "As() const {\n";
1507 OS << " return llvm::cast_or_null<" << AttrType << ">("
1508 << getLowerName() << ");\n";
1509 OS << " }\n";
1510 OS << " void set" << getUpperName() << "As(" << AttrType << " *V) {\n";
1511 OS << " " << getLowerName() << " = V;\n";
1512 OS << " }";
1513 }
1514 }
1515
1516 void writePCHReadDecls(raw_ostream &OS) const override {
1517 OS << " Attr *" << getLowerName() << " = Record.readAttr();";
1518 }
1519
1520 void writePCHWrite(raw_ostream &OS) const override {
1521 OS << " AddAttr(SA->get" << getUpperName() << "());";
1522 }
1523
1524 std::string getIsOmitted() const override {
1525 if (isOptional())
1526 return "!get" + getUpperName().str() + "()";
1527 return "false";
1528 }
1529
1530 void writeValue(raw_ostream &OS) const override {}
1531
1532 void writeDump(raw_ostream &OS) const override {}
1533
1534 void writeDumpChildren(raw_ostream &OS) const override {
1535 if (isOptional()) {
1536 OS << " if (auto *W = SA->get" << getUpperName() << "())\n";
1537 OS << " Visit(W);\n";
1538 } else {
1539 OS << " Visit(SA->get" << getUpperName() << "());\n";
1540 }
1541 }
1542
1543 void writeHasChildren(raw_ostream &OS) const override {
1544 if (isOptional())
1545 OS << "SA->get" << getUpperName() << "() != nullptr";
1546 else
1547 OS << "true";
1548 }
1549 };
1550
1551 } // end anonymous namespace
1552
1553static std::unique_ptr<Argument>
1554createArgument(const Record &Arg, StringRef Attr,
1555 const Record *Search = nullptr) {
1556 if (!Search)
1557 Search = &Arg;
1558
1559 std::unique_ptr<Argument> Ptr;
1560 StringRef ArgName = Search->getName();
1561
1562 if (ArgName == "AlignedArgument")
1563 Ptr = std::make_unique<AlignedArgument>(args: Arg, args&: Attr);
1564 else if (ArgName == "EnumArgument")
1565 Ptr = std::make_unique<EnumArgument>(args: Arg, args&: Attr);
1566 else if (ArgName == "ExprArgument")
1567 Ptr = std::make_unique<ExprArgument>(args: Arg, args&: Attr);
1568 else if (ArgName == "DeclArgument")
1569 Ptr = std::make_unique<SimpleArgument>(
1570 args: Arg, args&: Attr, args: (Arg.getValueAsDef(FieldName: "Kind")->getName() + "Decl *").str());
1571 else if (ArgName == "IdentifierArgument")
1572 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "const IdentifierInfo *");
1573 else if (ArgName == "DefaultBoolArgument")
1574 Ptr = std::make_unique<DefaultSimpleArgument>(
1575 args: Arg, args&: Attr, args: "bool", args: Arg.getValueAsBit(FieldName: "Default"));
1576 else if (ArgName == "BoolArgument")
1577 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "bool");
1578 else if (ArgName == "DefaultIntArgument")
1579 Ptr = std::make_unique<DefaultSimpleArgument>(
1580 args: Arg, args&: Attr, args: "int", args: Arg.getValueAsInt(FieldName: "Default"));
1581 else if (ArgName == "IntArgument")
1582 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "int");
1583 else if (ArgName == "StringArgument")
1584 Ptr = std::make_unique<StringArgument>(args: Arg, args&: Attr);
1585 else if (ArgName == "TypeArgument")
1586 Ptr = std::make_unique<TypeArgument>(args: Arg, args&: Attr);
1587 else if (ArgName == "UnsignedArgument")
1588 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "unsigned");
1589 else if (ArgName == "VariadicUnsignedArgument")
1590 Ptr = std::make_unique<VariadicArgument>(args: Arg, args&: Attr, args: "unsigned");
1591 else if (ArgName == "VariadicStringArgument")
1592 Ptr = std::make_unique<VariadicStringArgument>(args: Arg, args&: Attr);
1593 else if (ArgName == "VariadicEnumArgument")
1594 Ptr = std::make_unique<VariadicEnumArgument>(args: Arg, args&: Attr);
1595 else if (ArgName == "VariadicExprArgument")
1596 Ptr = std::make_unique<VariadicExprArgument>(args: Arg, args&: Attr);
1597 else if (ArgName == "VariadicParamIdxArgument")
1598 Ptr = std::make_unique<VariadicParamIdxArgument>(args: Arg, args&: Attr);
1599 else if (ArgName == "VariadicParamOrParamIdxArgument")
1600 Ptr = std::make_unique<VariadicParamOrParamIdxArgument>(args: Arg, args&: Attr);
1601 else if (ArgName == "ParamIdxArgument")
1602 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "ParamIdx");
1603 else if (ArgName == "VariadicIdentifierArgument")
1604 Ptr = std::make_unique<VariadicIdentifierArgument>(args: Arg, args&: Attr);
1605 else if (ArgName == "VersionArgument")
1606 Ptr = std::make_unique<VersionArgument>(args: Arg, args&: Attr);
1607 else if (ArgName == "WrappedAttr")
1608 Ptr = std::make_unique<WrappedAttr>(args: Arg, args&: Attr);
1609 else if (ArgName == "OMPTraitInfoArgument")
1610 Ptr = std::make_unique<SimpleArgument>(args: Arg, args&: Attr, args: "OMPTraitInfo *");
1611 else if (ArgName == "VariadicOMPInteropInfoArgument")
1612 Ptr = std::make_unique<VariadicOMPInteropInfoArgument>(args: Arg, args&: Attr);
1613
1614 if (!Ptr) {
1615 // Search in reverse order so that the most-derived type is handled first.
1616 std::vector<const Record *> SCs = Search->getSuperClasses();
1617 for (const Record *Base : reverse(C&: SCs)) {
1618 if ((Ptr = createArgument(Arg, Attr, Search: Base)))
1619 break;
1620 }
1621 }
1622
1623 if (Ptr && Arg.getValueAsBit(FieldName: "Optional"))
1624 Ptr->setOptional(true);
1625
1626 if (Ptr && Arg.getValueAsBit(FieldName: "Fake"))
1627 Ptr->setFake(true);
1628
1629 return Ptr;
1630}
1631
1632static void writeAvailabilityValue(raw_ostream &OS) {
1633 OS << "\" << getPlatform()->getName();\n"
1634 << " if (getStrict()) OS << \", strict\";\n"
1635 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n"
1636 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n"
1637 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n"
1638 << " if (getUnavailable()) OS << \", unavailable\";\n"
1639 << " OS << \"";
1640}
1641
1642static void writeDeprecatedAttrValue(raw_ostream &OS, StringRef Variety) {
1643 OS << "\\\"\" << getMessage() << \"\\\"\";\n";
1644 // Only GNU deprecated has an optional fixit argument at the second position.
1645 if (Variety == "GNU")
1646 OS << " if (!getReplacement().empty()) OS << \", \\\"\""
1647 " << getReplacement() << \"\\\"\";\n";
1648 OS << " OS << \"";
1649}
1650
1651static void writeGetSpellingFunction(const Record &R, raw_ostream &OS) {
1652 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
1653
1654 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n";
1655 if (Spellings.empty()) {
1656 OS << " return \"(No spelling)\";\n}\n\n";
1657 return;
1658 }
1659
1660 OS << " switch (getAttributeSpellingListIndex()) {\n"
1661 " default:\n"
1662 " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1663 " return \"(No spelling)\";\n";
1664
1665 for (const auto &[Idx, S] : enumerate(First&: Spellings)) {
1666 // clang-format off
1667 OS << " case " << Idx << ":\n"
1668 " return \"" << S.name() << "\";\n";
1669 // clang-format on
1670 }
1671 // End of the switch statement.
1672 OS << " }\n";
1673 // End of the getSpelling function.
1674 OS << "}\n\n";
1675}
1676
1677static void
1678writePrettyPrintFunction(const Record &R,
1679 const std::vector<std::unique_ptr<Argument>> &Args,
1680 raw_ostream &OS) {
1681 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
1682
1683 OS << "void " << R.getName() << "Attr::printPretty("
1684 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n";
1685
1686 if (Spellings.empty()) {
1687 OS << "}\n\n";
1688 return;
1689 }
1690
1691 OS << " bool IsFirstArgument = true; (void)IsFirstArgument;\n"
1692 << " unsigned TrailingOmittedArgs = 0; (void)TrailingOmittedArgs;\n"
1693 << " switch (getAttributeSpellingListIndex()) {\n"
1694 << " default:\n"
1695 << " llvm_unreachable(\"Unknown attribute spelling!\");\n"
1696 << " break;\n";
1697
1698 for (const auto &[Idx, S] : enumerate(First&: Spellings)) {
1699 SmallString<16> Prefix;
1700 SmallString<8> Suffix;
1701 // The actual spelling of the name and namespace (if applicable)
1702 // of an attribute without considering prefix and suffix.
1703 SmallString<64> Spelling;
1704 StringRef Name = S.name();
1705 StringRef Variety = S.variety();
1706
1707 if (Variety == "GNU") {
1708 Prefix = "__attribute__((";
1709 Suffix = "))";
1710 } else if (Variety == "CXX11" || Variety == "C23") {
1711 Prefix = "[[";
1712 Suffix = "]]";
1713 StringRef Namespace = S.nameSpace();
1714 if (!Namespace.empty()) {
1715 Spelling += Namespace;
1716 Spelling += "::";
1717 }
1718 } else if (Variety == "Declspec") {
1719 Prefix = "__declspec(";
1720 Suffix = ")";
1721 } else if (Variety == "Microsoft") {
1722 Prefix = "[";
1723 Suffix = "]";
1724 } else if (Variety == "Keyword") {
1725 Prefix = "";
1726 Suffix = "";
1727 } else if (Variety == "Pragma") {
1728 Prefix = "#pragma ";
1729 Suffix = "\n";
1730 StringRef Namespace = S.nameSpace();
1731 if (!Namespace.empty()) {
1732 Spelling += Namespace;
1733 Spelling += " ";
1734 }
1735 } else if (Variety == "HLSLAnnotation") {
1736 Prefix = ":";
1737 Suffix = "";
1738 } else {
1739 llvm_unreachable("Unknown attribute syntax variety!");
1740 }
1741
1742 Spelling += Name;
1743
1744 OS << " case " << Idx << " : {\n"
1745 << " OS << \"" << Prefix << Spelling << "\";\n";
1746
1747 if (Variety == "Pragma") {
1748 OS << " printPrettyPragma(OS, Policy);\n";
1749 OS << " OS << \"\\n\";";
1750 OS << " break;\n";
1751 OS << " }\n";
1752 continue;
1753 }
1754
1755 if (Spelling == "availability") {
1756 OS << " OS << \"(";
1757 writeAvailabilityValue(OS);
1758 OS << ")\";\n";
1759 } else if (Spelling == "deprecated" || Spelling == "gnu::deprecated") {
1760 OS << " OS << \"(";
1761 writeDeprecatedAttrValue(OS, Variety);
1762 OS << ")\";\n";
1763 } else {
1764 // To avoid printing parentheses around an empty argument list or
1765 // printing spurious commas at the end of an argument list, we need to
1766 // determine where the last provided non-fake argument is.
1767 bool FoundNonOptArg = false;
1768 for (const auto &arg : reverse(C: Args)) {
1769 if (arg->isFake())
1770 continue;
1771 if (FoundNonOptArg)
1772 continue;
1773 // FIXME: arg->getIsOmitted() == "false" means we haven't implemented
1774 // any way to detect whether the argument was omitted.
1775 if (!arg->isOptional() || arg->getIsOmitted() == "false") {
1776 FoundNonOptArg = true;
1777 continue;
1778 }
1779 OS << " if (" << arg->getIsOmitted() << ")\n"
1780 << " ++TrailingOmittedArgs;\n";
1781 }
1782 unsigned ArgIndex = 0;
1783 for (const auto &arg : Args) {
1784 if (arg->isFake())
1785 continue;
1786 std::string IsOmitted = arg->getIsOmitted();
1787 if (arg->isOptional() && IsOmitted != "false")
1788 OS << " if (!(" << IsOmitted << ")) {\n";
1789 // Variadic arguments print their own leading comma.
1790 if (!arg->isVariadic())
1791 OS << " DelimitAttributeArgument(OS, IsFirstArgument);\n";
1792 OS << " OS << \"";
1793 arg->writeValue(OS);
1794 OS << "\";\n";
1795 if (arg->isOptional() && IsOmitted != "false")
1796 OS << " }\n";
1797 ++ArgIndex;
1798 }
1799 if (ArgIndex != 0)
1800 OS << " if (!IsFirstArgument)\n"
1801 << " OS << \")\";\n";
1802 }
1803 OS << " OS << \"" << Suffix << "\";\n"
1804 << " break;\n"
1805 << " }\n";
1806 }
1807
1808 // End of the switch statement.
1809 OS << "}\n";
1810 // End of the print function.
1811 OS << "}\n\n";
1812}
1813
1814/// Return the index of a spelling in a spelling list.
1815static unsigned getSpellingListIndex(ArrayRef<FlattenedSpelling> SpellingList,
1816 const FlattenedSpelling &Spelling) {
1817 assert(!SpellingList.empty() && "Spelling list is empty!");
1818
1819 for (const auto &[Index, S] : enumerate(First&: SpellingList)) {
1820 if (S.variety() == Spelling.variety() &&
1821 S.nameSpace() == Spelling.nameSpace() && S.name() == Spelling.name())
1822 return Index;
1823 }
1824
1825 PrintFatalError(Msg: "Unknown spelling: " + Spelling.name());
1826}
1827
1828static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) {
1829 std::vector<const Record *> Accessors = R.getValueAsListOfDefs(FieldName: "Accessors");
1830 if (Accessors.empty())
1831 return;
1832
1833 const std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(Attr: R);
1834 assert(!SpellingList.empty() &&
1835 "Attribute with empty spelling list can't have accessors!");
1836 for (const auto *Accessor : Accessors) {
1837 const StringRef Name = Accessor->getValueAsString(FieldName: "Name");
1838 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: *Accessor);
1839
1840 OS << " bool " << Name
1841 << "() const { return getAttributeSpellingListIndex() == ";
1842 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
1843 OS << getSpellingListIndex(SpellingList, Spelling: Spellings[Index]);
1844 if (Index != Spellings.size() - 1)
1845 OS << " ||\n getAttributeSpellingListIndex() == ";
1846 else
1847 OS << "; }\n";
1848 }
1849 }
1850}
1851
1852static bool
1853SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) {
1854 assert(!Spellings.empty() && "An empty list of spellings was provided");
1855 StringRef FirstName =
1856 NormalizeNameForSpellingComparison(Name: Spellings.front().name());
1857 for (const auto &Spelling : drop_begin(RangeOrContainer: Spellings)) {
1858 StringRef Name = NormalizeNameForSpellingComparison(Name: Spelling.name());
1859 if (Name != FirstName)
1860 return false;
1861 }
1862 return true;
1863}
1864
1865typedef std::map<unsigned, std::string> SemanticSpellingMap;
1866static std::string
1867CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings,
1868 SemanticSpellingMap &Map) {
1869 // The enumerants are automatically generated based on the variety,
1870 // namespace (if present) and name for each attribute spelling. However,
1871 // care is taken to avoid trampling on the reserved namespace due to
1872 // underscores.
1873 std::string Ret(" enum Spelling {\n");
1874 std::set<std::string> Uniques;
1875 unsigned Idx = 0;
1876
1877 // If we have a need to have this many spellings we likely need to add an
1878 // extra bit to the SpellingIndex in AttributeCommonInfo, then increase the
1879 // value of SpellingNotCalculated there and here.
1880 assert(Spellings.size() < 15 &&
1881 "Too many spellings, would step on SpellingNotCalculated in "
1882 "AttributeCommonInfo");
1883 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) {
1884 const FlattenedSpelling &S = *I;
1885 StringRef Variety = S.variety();
1886 StringRef Spelling = S.name();
1887 StringRef Namespace = S.nameSpace();
1888 std::string EnumName;
1889
1890 EnumName += Variety;
1891 EnumName += "_";
1892 if (!Namespace.empty())
1893 EnumName += NormalizeNameForSpellingComparison(Name: Namespace).str() + "_";
1894 EnumName += NormalizeNameForSpellingComparison(Name: Spelling);
1895
1896 // Even if the name is not unique, this spelling index corresponds to a
1897 // particular enumerant name that we've calculated.
1898 Map[Idx] = EnumName;
1899
1900 // Since we have been stripping underscores to avoid trampling on the
1901 // reserved namespace, we may have inadvertently created duplicate
1902 // enumerant names. These duplicates are not considered part of the
1903 // semantic spelling, and can be elided.
1904 if (!Uniques.insert(x: EnumName).second)
1905 continue;
1906
1907 if (I != Spellings.begin())
1908 Ret += ",\n";
1909 // Duplicate spellings are not considered part of the semantic spelling
1910 // enumeration, but the spelling index and semantic spelling values are
1911 // meant to be equivalent, so we must specify a concrete value for each
1912 // enumerator.
1913 Ret += " " + EnumName + " = " + utostr(X: Idx);
1914 }
1915 Ret += ",\n SpellingNotCalculated = 15\n";
1916 Ret += "\n };\n\n";
1917 return Ret;
1918}
1919
1920static void WriteSemanticSpellingSwitch(StringRef VarName,
1921 const SemanticSpellingMap &Map,
1922 raw_ostream &OS) {
1923 OS << " switch (" << VarName << ") {\n default: "
1924 << "llvm_unreachable(\"Unknown spelling list index\");\n";
1925 for (const auto &I : Map)
1926 OS << " case " << I.first << ": return " << I.second << ";\n";
1927 OS << " }\n";
1928}
1929
1930// Note: these values need to match the values used by LateAttrParseKind in
1931// `Attr.td`
1932enum class LateAttrParseKind { Never = 0, Standard = 1, ExperimentalExt = 2 };
1933
1934static LateAttrParseKind getLateAttrParseKind(const Record *Attr) {
1935 // This function basically does
1936 // `Attr->getValueAsDef("LateParsed")->getValueAsInt("Kind")` but does a bunch
1937 // of sanity checking to ensure that `LateAttrParseMode` in `Attr.td` is in
1938 // sync with the `LateAttrParseKind` enum in this source file.
1939
1940 static constexpr StringRef LateParsedStr = "LateParsed";
1941 static constexpr StringRef LateAttrParseKindStr = "LateAttrParseKind";
1942 static constexpr StringRef KindFieldStr = "Kind";
1943
1944 auto *LAPK = Attr->getValueAsDef(FieldName: LateParsedStr);
1945
1946 // Typecheck the `LateParsed` field.
1947 if (LAPK->getDirectSuperClasses().size() != 1)
1948 PrintFatalError(Rec: Attr, Msg: "Field `" + Twine(LateParsedStr) +
1949 "`should only have one super class");
1950
1951 const Record *SuperClass = LAPK->getDirectSuperClasses()[0].first;
1952 if (SuperClass->getName() != LateAttrParseKindStr)
1953 PrintFatalError(
1954 Rec: Attr, Msg: "Field `" + Twine(LateParsedStr) + "`should only have type `" +
1955 Twine(LateAttrParseKindStr) + "` but found type `" +
1956 SuperClass->getName() + "`");
1957
1958 // Get Kind and verify the enum name matches the name in `Attr.td`.
1959 unsigned Kind = LAPK->getValueAsInt(FieldName: KindFieldStr);
1960 switch (LateAttrParseKind(Kind)) {
1961#define CASE(X) \
1962 case LateAttrParseKind::X: \
1963 if (LAPK->getName().compare("LateAttrParse" #X) != 0) { \
1964 PrintFatalError( \
1965 Attr, \
1966 "Field `" + Twine(LateParsedStr) + "` set to `" + LAPK->getName() + \
1967 "` but this converts to `LateAttrParseKind::" + Twine(#X) + \
1968 "`"); \
1969 } \
1970 return LateAttrParseKind::X;
1971
1972 CASE(Never)
1973 CASE(Standard)
1974 CASE(ExperimentalExt)
1975#undef CASE
1976 }
1977
1978 // The Kind value is completely invalid
1979 auto KindValueStr = utostr(X: Kind);
1980 PrintFatalError(Rec: Attr, Msg: "Field `" + Twine(LateParsedStr) + "` set to `" +
1981 LAPK->getName() + "` has unexpected `" +
1982 Twine(KindFieldStr) + "` value of " + KindValueStr);
1983}
1984
1985// Emits the LateParsed property for attributes.
1986static void emitClangAttrLateParsedListImpl(const RecordKeeper &Records,
1987 raw_ostream &OS,
1988 LateAttrParseKind LateParseMode) {
1989 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
1990 if (LateAttrParseKind LateParsed = getLateAttrParseKind(Attr);
1991 LateParsed != LateParseMode)
1992 continue;
1993
1994 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: *Attr);
1995
1996 // FIXME: Handle non-GNU attributes
1997 for (const auto &I : Spellings) {
1998 if (I.variety() != "GNU")
1999 continue;
2000 OS << ".Case(\"" << I.name() << "\", 1)\n";
2001 }
2002 }
2003}
2004
2005static void emitClangAttrLateParsedList(const RecordKeeper &Records,
2006 raw_ostream &OS) {
2007 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n";
2008 emitClangAttrLateParsedListImpl(Records, OS, LateParseMode: LateAttrParseKind::Standard);
2009 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n";
2010}
2011
2012static void emitClangAttrLateParsedExperimentalList(const RecordKeeper &Records,
2013 raw_ostream &OS) {
2014 OS << "#if defined(CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST)\n";
2015 emitClangAttrLateParsedListImpl(Records, OS,
2016 LateParseMode: LateAttrParseKind::ExperimentalExt);
2017 OS << "#endif // CLANG_ATTR_LATE_PARSED_EXPERIMENTAL_EXT_LIST\n\n";
2018}
2019
2020// Emits a list of attributes whose argument list is parsed inside a function
2021// prototype scope so it can refer to the enclosing function's parameters.
2022static void
2023emitClangAttrParseArgsInFunctionScopeList(const RecordKeeper &Records,
2024 raw_ostream &OS) {
2025 OS << "#if defined(CLANG_ATTR_PARSE_ARGS_IN_FUNCTION_SCOPE_LIST)\n";
2026 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2027 if (!Attr->getValueAsBit(FieldName: "ParseArgsInFunctionScope"))
2028 continue;
2029 // FIXME: Handle non-GNU attributes
2030 for (const auto &I : GetFlattenedSpellings(Attr: *Attr))
2031 if (I.variety() == "GNU")
2032 OS << ".Case(\"" << I.name() << "\", 1)\n";
2033 }
2034 OS << "#endif // CLANG_ATTR_PARSE_ARGS_IN_FUNCTION_SCOPE_LIST\n\n";
2035}
2036
2037static bool hasGNUorCXX11Spelling(const Record &Attribute) {
2038 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: Attribute);
2039 for (const auto &I : Spellings) {
2040 if (I.variety() == "GNU" || I.variety() == "CXX11")
2041 return true;
2042 }
2043 return false;
2044}
2045
2046namespace {
2047
2048struct AttributeSubjectMatchRule {
2049 const Record *MetaSubject;
2050 const Record *Constraint;
2051
2052 AttributeSubjectMatchRule(const Record *MetaSubject, const Record *Constraint)
2053 : MetaSubject(MetaSubject), Constraint(Constraint) {
2054 assert(MetaSubject && "Missing subject");
2055 }
2056
2057 bool isSubRule() const { return Constraint != nullptr; }
2058
2059 std::vector<const Record *> getSubjects() const {
2060 return (Constraint ? Constraint : MetaSubject)
2061 ->getValueAsListOfDefs(FieldName: "Subjects");
2062 }
2063
2064 std::vector<const Record *> getLangOpts() const {
2065 if (Constraint) {
2066 // Lookup the options in the sub-rule first, in case the sub-rule
2067 // overrides the rules options.
2068 std::vector<const Record *> Opts =
2069 Constraint->getValueAsListOfDefs(FieldName: "LangOpts");
2070 if (!Opts.empty())
2071 return Opts;
2072 }
2073 return MetaSubject->getValueAsListOfDefs(FieldName: "LangOpts");
2074 }
2075
2076 // Abstract rules are used only for sub-rules
2077 bool isAbstractRule() const { return getSubjects().empty(); }
2078
2079 StringRef getName() const {
2080 return (Constraint ? Constraint : MetaSubject)->getValueAsString(FieldName: "Name");
2081 }
2082
2083 bool isNegatedSubRule() const {
2084 assert(isSubRule() && "Not a sub-rule");
2085 return Constraint->getValueAsBit(FieldName: "Negated");
2086 }
2087
2088 std::string getSpelling() const {
2089 std::string Result = MetaSubject->getValueAsString(FieldName: "Name").str();
2090 if (isSubRule()) {
2091 Result += '(';
2092 if (isNegatedSubRule())
2093 Result += "unless(";
2094 Result += getName();
2095 if (isNegatedSubRule())
2096 Result += ')';
2097 Result += ')';
2098 }
2099 return Result;
2100 }
2101
2102 std::string getEnumValueName() const {
2103 SmallString<128> Result;
2104 Result += "SubjectMatchRule_";
2105 Result += MetaSubject->getValueAsString(FieldName: "Name");
2106 if (isSubRule()) {
2107 Result += "_";
2108 if (isNegatedSubRule())
2109 Result += "not_";
2110 Result += Constraint->getValueAsString(FieldName: "Name");
2111 }
2112 if (isAbstractRule())
2113 Result += "_abstract";
2114 return std::string(Result);
2115 }
2116
2117 std::string getEnumValue() const { return "attr::" + getEnumValueName(); }
2118
2119 static const char *EnumName;
2120};
2121
2122const char *AttributeSubjectMatchRule::EnumName = "attr::SubjectMatchRule";
2123
2124struct PragmaClangAttributeSupport {
2125 std::vector<AttributeSubjectMatchRule> Rules;
2126
2127 class RuleOrAggregateRuleSet {
2128 std::vector<AttributeSubjectMatchRule> Rules;
2129 bool IsRule;
2130 RuleOrAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules,
2131 bool IsRule)
2132 : Rules(Rules), IsRule(IsRule) {}
2133
2134 public:
2135 bool isRule() const { return IsRule; }
2136
2137 const AttributeSubjectMatchRule &getRule() const {
2138 assert(IsRule && "not a rule!");
2139 return Rules[0];
2140 }
2141
2142 ArrayRef<AttributeSubjectMatchRule> getAggregateRuleSet() const {
2143 return Rules;
2144 }
2145
2146 static RuleOrAggregateRuleSet
2147 getRule(const AttributeSubjectMatchRule &Rule) {
2148 return RuleOrAggregateRuleSet(Rule, /*IsRule=*/true);
2149 }
2150 static RuleOrAggregateRuleSet
2151 getAggregateRuleSet(ArrayRef<AttributeSubjectMatchRule> Rules) {
2152 return RuleOrAggregateRuleSet(Rules, /*IsRule=*/false);
2153 }
2154 };
2155 DenseMap<const Record *, RuleOrAggregateRuleSet> SubjectsToRules;
2156
2157 PragmaClangAttributeSupport(const RecordKeeper &Records);
2158
2159 bool isAttributedSupported(const Record &Attribute);
2160
2161 void emitMatchRuleList(raw_ostream &OS);
2162
2163 void generateStrictConformsTo(const Record &Attr, raw_ostream &OS);
2164
2165 void generateParsingHelpers(raw_ostream &OS);
2166};
2167
2168} // end anonymous namespace
2169
2170static bool isSupportedPragmaClangAttributeSubject(const Record &Subject) {
2171 // FIXME: #pragma clang attribute does not currently support statement
2172 // attributes, so test whether the subject is one that appertains to a
2173 // declaration node. However, it may be reasonable for support for statement
2174 // attributes to be added.
2175 if (Subject.isSubClassOf(Name: "DeclNode") || Subject.isSubClassOf(Name: "DeclBase") ||
2176 Subject.getName() == "DeclBase")
2177 return true;
2178
2179 if (Subject.isSubClassOf(Name: "SubsetSubject"))
2180 return isSupportedPragmaClangAttributeSubject(
2181 Subject: *Subject.getValueAsDef(FieldName: "Base"));
2182
2183 return false;
2184}
2185
2186static bool doesDeclDeriveFrom(const Record *D, const Record *Base) {
2187 const Record *CurrentBase = D->getValueAsOptionalDef(BaseFieldName);
2188 if (!CurrentBase)
2189 return false;
2190 if (CurrentBase == Base)
2191 return true;
2192 return doesDeclDeriveFrom(D: CurrentBase, Base);
2193}
2194
2195PragmaClangAttributeSupport::PragmaClangAttributeSupport(
2196 const RecordKeeper &Records) {
2197 auto MapFromSubjectsToRules = [this](const Record *SubjectContainer,
2198 const Record *MetaSubject,
2199 const Record *Constraint) {
2200 Rules.emplace_back(args&: MetaSubject, args&: Constraint);
2201 for (const Record *Subject :
2202 SubjectContainer->getValueAsListOfDefs(FieldName: "Subjects")) {
2203 bool Inserted =
2204 SubjectsToRules
2205 .try_emplace(Key: Subject, Args: RuleOrAggregateRuleSet::getRule(
2206 Rule: AttributeSubjectMatchRule(MetaSubject,
2207 Constraint)))
2208 .second;
2209 if (!Inserted) {
2210 PrintFatalError(Msg: "Attribute subject match rules should not represent"
2211 "same attribute subjects.");
2212 }
2213 }
2214 };
2215 for (const auto *MetaSubject :
2216 Records.getAllDerivedDefinitions(ClassName: "AttrSubjectMatcherRule")) {
2217 MapFromSubjectsToRules(MetaSubject, MetaSubject, /*Constraints=*/nullptr);
2218 for (const Record *Constraint :
2219 MetaSubject->getValueAsListOfDefs(FieldName: "Constraints"))
2220 MapFromSubjectsToRules(Constraint, MetaSubject, Constraint);
2221 }
2222
2223 ArrayRef<const Record *> DeclNodes =
2224 Records.getAllDerivedDefinitions(DeclNodeClassName);
2225 for (const auto *Aggregate :
2226 Records.getAllDerivedDefinitions(ClassName: "AttrSubjectMatcherAggregateRule")) {
2227 const Record *SubjectDecl = Aggregate->getValueAsDef(FieldName: "Subject");
2228
2229 // Gather sub-classes of the aggregate subject that act as attribute
2230 // subject rules.
2231 std::vector<AttributeSubjectMatchRule> Rules;
2232 for (const auto *D : DeclNodes) {
2233 if (doesDeclDeriveFrom(D, Base: SubjectDecl)) {
2234 auto It = SubjectsToRules.find(Val: D);
2235 if (It == SubjectsToRules.end())
2236 continue;
2237 if (!It->second.isRule() || It->second.getRule().isSubRule())
2238 continue; // Assume that the rule will be included as well.
2239 Rules.push_back(x: It->second.getRule());
2240 }
2241 }
2242
2243 bool Inserted =
2244 SubjectsToRules
2245 .try_emplace(Key: SubjectDecl,
2246 Args: RuleOrAggregateRuleSet::getAggregateRuleSet(Rules))
2247 .second;
2248 if (!Inserted) {
2249 PrintFatalError(Msg: "Attribute subject match rules should not represent"
2250 "same attribute subjects.");
2251 }
2252 }
2253}
2254
2255static PragmaClangAttributeSupport &
2256getPragmaAttributeSupport(const RecordKeeper &Records) {
2257 static PragmaClangAttributeSupport Instance(Records);
2258 return Instance;
2259}
2260
2261void PragmaClangAttributeSupport::emitMatchRuleList(raw_ostream &OS) {
2262 OS << "#ifndef ATTR_MATCH_SUB_RULE\n";
2263 OS << "#define ATTR_MATCH_SUB_RULE(Value, Spelling, IsAbstract, Parent, "
2264 "IsNegated) "
2265 << "ATTR_MATCH_RULE(Value, Spelling, IsAbstract)\n";
2266 OS << "#endif\n";
2267 for (const auto &Rule : Rules) {
2268 OS << (Rule.isSubRule() ? "ATTR_MATCH_SUB_RULE" : "ATTR_MATCH_RULE") << '(';
2269 OS << Rule.getEnumValueName() << ", \"" << Rule.getSpelling() << "\", "
2270 << Rule.isAbstractRule();
2271 if (Rule.isSubRule())
2272 OS << ", "
2273 << AttributeSubjectMatchRule(Rule.MetaSubject, nullptr).getEnumValue()
2274 << ", " << Rule.isNegatedSubRule();
2275 OS << ")\n";
2276 }
2277 OS << "#undef ATTR_MATCH_SUB_RULE\n";
2278}
2279
2280bool PragmaClangAttributeSupport::isAttributedSupported(
2281 const Record &Attribute) {
2282 // If the attribute explicitly specified whether to support #pragma clang
2283 // attribute, use that setting.
2284 bool Unset;
2285 bool SpecifiedResult =
2286 Attribute.getValueAsBitOrUnset(FieldName: "PragmaAttributeSupport", Unset);
2287 if (!Unset)
2288 return SpecifiedResult;
2289
2290 // Opt-out rules:
2291
2292 // An attribute requires delayed parsing (LateParsed is on).
2293 switch (getLateAttrParseKind(Attr: &Attribute)) {
2294 case LateAttrParseKind::Never:
2295 break;
2296 case LateAttrParseKind::Standard:
2297 return false;
2298 case LateAttrParseKind::ExperimentalExt:
2299 // This is only late parsed in certain parsing contexts when
2300 // `LangOpts.ExperimentalLateParseAttributes` is true. Information about the
2301 // parsing context and `LangOpts` is not available in this method so just
2302 // opt this attribute out.
2303 return false;
2304 }
2305
2306 // An attribute has no GNU/CXX11 spelling
2307 if (!hasGNUorCXX11Spelling(Attribute))
2308 return false;
2309 // An attribute subject list has a subject that isn't covered by one of the
2310 // subject match rules or has no subjects at all.
2311 if (Attribute.isValueUnset(FieldName: "Subjects"))
2312 return false;
2313 const Record *SubjectObj = Attribute.getValueAsDef(FieldName: "Subjects");
2314 bool HasAtLeastOneValidSubject = false;
2315 for (const auto *Subject : SubjectObj->getValueAsListOfDefs(FieldName: "Subjects")) {
2316 if (!isSupportedPragmaClangAttributeSubject(Subject: *Subject))
2317 continue;
2318 if (!SubjectsToRules.contains(Val: Subject))
2319 return false;
2320 HasAtLeastOneValidSubject = true;
2321 }
2322 return HasAtLeastOneValidSubject;
2323}
2324
2325static std::string GenerateTestExpression(ArrayRef<const Record *> LangOpts) {
2326 std::string Test;
2327
2328 for (auto *E : LangOpts) {
2329 if (!Test.empty())
2330 Test += " || ";
2331
2332 const StringRef Code = E->getValueAsString(FieldName: "CustomCode");
2333 if (!Code.empty()) {
2334 Test += "(";
2335 Test += Code;
2336 Test += ")";
2337 if (!E->getValueAsString(FieldName: "Name").empty()) {
2338 PrintWarning(
2339 WarningLoc: E->getLoc(),
2340 Msg: "non-empty 'Name' field ignored because 'CustomCode' was supplied");
2341 }
2342 } else {
2343 Test += "LangOpts.";
2344 Test += E->getValueAsString(FieldName: "Name");
2345 }
2346 }
2347
2348 if (Test.empty())
2349 return "true";
2350
2351 return Test;
2352}
2353
2354void
2355PragmaClangAttributeSupport::generateStrictConformsTo(const Record &Attr,
2356 raw_ostream &OS) {
2357 if (!isAttributedSupported(Attribute: Attr) || Attr.isValueUnset(FieldName: "Subjects"))
2358 return;
2359 // Generate a function that constructs a set of matching rules that describe
2360 // to which declarations the attribute should apply to.
2361 OS << "void getPragmaAttributeMatchRules("
2362 << "llvm::SmallVectorImpl<std::pair<"
2363 << AttributeSubjectMatchRule::EnumName
2364 << ", bool>> &MatchRules, const LangOptions &LangOpts) const override {\n";
2365 const Record *SubjectObj = Attr.getValueAsDef(FieldName: "Subjects");
2366 for (const auto *Subject : SubjectObj->getValueAsListOfDefs(FieldName: "Subjects")) {
2367 if (!isSupportedPragmaClangAttributeSubject(Subject: *Subject))
2368 continue;
2369 auto It = SubjectsToRules.find(Val: Subject);
2370 assert(It != SubjectsToRules.end() &&
2371 "This attribute is unsupported by #pragma clang attribute");
2372 for (const auto &Rule : It->getSecond().getAggregateRuleSet()) {
2373 // The rule might be language specific, so only subtract it from the given
2374 // rules if the specific language options are specified.
2375 std::vector<const Record *> LangOpts = Rule.getLangOpts();
2376 OS << " MatchRules.push_back(std::make_pair(" << Rule.getEnumValue()
2377 << ", /*IsSupported=*/" << GenerateTestExpression(LangOpts)
2378 << "));\n";
2379 }
2380 }
2381 OS << "}\n\n";
2382}
2383
2384void PragmaClangAttributeSupport::generateParsingHelpers(raw_ostream &OS) {
2385 // Generate routines that check the names of sub-rules.
2386 OS << "std::optional<attr::SubjectMatchRule> "
2387 "defaultIsAttributeSubjectMatchSubRuleFor(StringRef, bool) {\n";
2388 OS << " return std::nullopt;\n";
2389 OS << "}\n\n";
2390
2391 MapVector<const Record *, std::vector<AttributeSubjectMatchRule>>
2392 SubMatchRules;
2393 for (const auto &Rule : Rules) {
2394 if (!Rule.isSubRule())
2395 continue;
2396 SubMatchRules[Rule.MetaSubject].push_back(x: Rule);
2397 }
2398
2399 for (const auto &SubMatchRule : SubMatchRules) {
2400 OS << "std::optional<attr::SubjectMatchRule> "
2401 "isAttributeSubjectMatchSubRuleFor_"
2402 << SubMatchRule.first->getValueAsString(FieldName: "Name")
2403 << "(StringRef Name, bool IsUnless) {\n";
2404 OS << " if (IsUnless)\n";
2405 OS << " return "
2406 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2407 for (const auto &Rule : SubMatchRule.second) {
2408 if (Rule.isNegatedSubRule())
2409 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2410 << ").\n";
2411 }
2412 OS << " Default(std::nullopt);\n";
2413 OS << " return "
2414 "llvm::StringSwitch<std::optional<attr::SubjectMatchRule>>(Name).\n";
2415 for (const auto &Rule : SubMatchRule.second) {
2416 if (!Rule.isNegatedSubRule())
2417 OS << " Case(\"" << Rule.getName() << "\", " << Rule.getEnumValue()
2418 << ").\n";
2419 }
2420 OS << " Default(std::nullopt);\n";
2421 OS << "}\n\n";
2422 }
2423
2424 // Generate the function that checks for the top-level rules.
2425 OS << "std::pair<std::optional<attr::SubjectMatchRule>, "
2426 "std::optional<attr::SubjectMatchRule> (*)(StringRef, "
2427 "bool)> isAttributeSubjectMatchRule(StringRef Name) {\n";
2428 OS << " return "
2429 "llvm::StringSwitch<std::pair<std::optional<attr::SubjectMatchRule>, "
2430 "std::optional<attr::SubjectMatchRule> (*) (StringRef, "
2431 "bool)>>(Name).\n";
2432 for (const auto &Rule : Rules) {
2433 if (Rule.isSubRule())
2434 continue;
2435 std::string SubRuleFunction;
2436 if (SubMatchRules.count(Key: Rule.MetaSubject))
2437 SubRuleFunction =
2438 ("isAttributeSubjectMatchSubRuleFor_" + Rule.getName()).str();
2439 else
2440 SubRuleFunction = "defaultIsAttributeSubjectMatchSubRuleFor";
2441 OS << " Case(\"" << Rule.getName() << "\", std::make_pair("
2442 << Rule.getEnumValue() << ", " << SubRuleFunction << ")).\n";
2443 }
2444 OS << " Default(std::make_pair(std::nullopt, "
2445 "defaultIsAttributeSubjectMatchSubRuleFor));\n";
2446 OS << "}\n\n";
2447
2448 // Generate the function that checks for the submatch rules.
2449 OS << "const char *validAttributeSubjectMatchSubRules("
2450 << AttributeSubjectMatchRule::EnumName << " Rule) {\n";
2451 OS << " switch (Rule) {\n";
2452 for (const auto &SubMatchRule : SubMatchRules) {
2453 OS << " case "
2454 << AttributeSubjectMatchRule(SubMatchRule.first, nullptr).getEnumValue()
2455 << ":\n";
2456 OS << " return \"'";
2457 bool IsFirst = true;
2458 for (const auto &Rule : SubMatchRule.second) {
2459 if (!IsFirst)
2460 OS << ", '";
2461 IsFirst = false;
2462 if (Rule.isNegatedSubRule())
2463 OS << "unless(";
2464 OS << Rule.getName();
2465 if (Rule.isNegatedSubRule())
2466 OS << ')';
2467 OS << "'";
2468 }
2469 OS << "\";\n";
2470 }
2471 OS << " default: return nullptr;\n";
2472 OS << " }\n";
2473 OS << "}\n\n";
2474}
2475
2476template <typename Fn> static void forEachSpelling(const Record &Attr, Fn &&F) {
2477 for (const FlattenedSpelling &S : GetFlattenedSpellings(Attr)) {
2478 F(S);
2479 }
2480}
2481
2482static std::map<StringRef, std::vector<const Record *>> NameToAttrsMap;
2483
2484/// Build a map from the attribute name to the Attrs that use that name. If more
2485/// than one Attr use a name, the arguments could be different so a more complex
2486/// check is needed in the generated switch.
2487static void generateNameToAttrsMap(const RecordKeeper &Records) {
2488 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2489 for (const FlattenedSpelling &S : GetFlattenedSpellings(Attr: *A)) {
2490 auto [It, Inserted] = NameToAttrsMap.try_emplace(k: S.name());
2491 if (Inserted || !is_contained(Range&: It->second, Element: A))
2492 It->second.emplace_back(args&: A);
2493 }
2494 }
2495}
2496
2497/// Generate the info needed to produce the case values in case more than one
2498/// attribute has the same name. Store the info in a map that can be processed
2499/// after all attributes are seen.
2500static void generateFlattenedSpellingInfo(const Record &Attr,
2501 std::map<StringRef, FSIVecTy> &Map,
2502 uint32_t ArgMask = 0) {
2503 std::string TargetTest;
2504 if (Attr.isSubClassOf(Name: "TargetSpecificAttr") &&
2505 !Attr.isValueUnset(FieldName: "ParseKind")) {
2506 const Record *T = Attr.getValueAsDef(FieldName: "Target");
2507 std::vector<StringRef> Arches = T->getValueAsListOfStrings(FieldName: "Arches");
2508 (void)GenerateTargetSpecificAttrChecks(R: T, Arches, Test&: TargetTest, FnName: nullptr);
2509 }
2510
2511 forEachSpelling(Attr, F: [&](const FlattenedSpelling &S) {
2512 Map[S.name()].emplace_back(args: S.variety(), args: S.nameSpace(), args&: TargetTest, args&: ArgMask);
2513 });
2514}
2515
2516static bool nameAppliesToOneAttribute(StringRef Name) {
2517 auto It = NameToAttrsMap.find(x: Name);
2518 assert(It != NameToAttrsMap.end());
2519 return It->second.size() == 1;
2520}
2521
2522static bool emitIfSimpleValue(StringRef Name, uint32_t ArgMask,
2523 raw_ostream &OS) {
2524 if (nameAppliesToOneAttribute(Name)) {
2525 OS << ".Case(\"" << Name << "\", ";
2526 if (ArgMask != 0)
2527 OS << ArgMask << ")\n";
2528 else
2529 OS << "true)\n";
2530 return true;
2531 }
2532 return false;
2533}
2534
2535static void emitSingleCondition(const FlattenedSpellingInfo &FSI,
2536 raw_ostream &OS) {
2537 OS << "(Syntax==AttributeCommonInfo::AS_" << FSI.Syntax << " && ";
2538 if (!FSI.Scope.empty())
2539 OS << "ScopeName && ScopeName->getName()==\"" << FSI.Scope << "\"";
2540 else
2541 OS << "!ScopeName";
2542 if (!FSI.TargetTest.empty())
2543 OS << " && " << FSI.TargetTest;
2544 OS << ")";
2545}
2546
2547static void emitStringSwitchCases(std::map<StringRef, FSIVecTy> &Map,
2548 raw_ostream &OS) {
2549 for (const auto &[Name, Vec] : Map) {
2550 if (emitIfSimpleValue(Name, ArgMask: Vec[0].ArgMask, OS))
2551 continue;
2552
2553 // Not simple, build expressions for each case.
2554 OS << ".Case(\"" << Name << "\", ";
2555 for (unsigned I = 0, E = Vec.size(); I < E; ++I) {
2556 emitSingleCondition(FSI: Vec[I], OS);
2557 uint32_t ArgMask = Vec[I].ArgMask;
2558 if (E == 1 && ArgMask == 0)
2559 continue;
2560
2561 // More than one or it's the Mask form. Create a conditional expression.
2562 uint32_t SuccessValue = ArgMask != 0 ? ArgMask : 1;
2563 OS << " ? " << SuccessValue << " : ";
2564 if (I == E - 1)
2565 OS << 0;
2566 }
2567 OS << ")\n";
2568 }
2569}
2570
2571static bool isTypeArgument(const Record *Arg) {
2572 return !Arg->getDirectSuperClasses().empty() &&
2573 Arg->getDirectSuperClasses().back().first->getName() == "TypeArgument";
2574}
2575
2576/// Emits the first-argument-is-type property for attributes.
2577static void emitClangAttrTypeArgList(const RecordKeeper &Records,
2578 raw_ostream &OS) {
2579 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n";
2580 std::map<StringRef, FSIVecTy> FSIMap;
2581 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2582 // Determine whether the first argument is a type.
2583 std::vector<const Record *> Args = Attr->getValueAsListOfDefs(FieldName: "Args");
2584 if (Args.empty())
2585 continue;
2586
2587 if (!isTypeArgument(Arg: Args[0]))
2588 continue;
2589 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap);
2590 }
2591 emitStringSwitchCases(Map&: FSIMap, OS);
2592 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n";
2593}
2594
2595/// Emits the parse-arguments-in-unevaluated-context property for
2596/// attributes.
2597static void emitClangAttrArgContextList(const RecordKeeper &Records,
2598 raw_ostream &OS) {
2599 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n";
2600 std::map<StringRef, FSIVecTy> FSIMap;
2601 ParsedAttrMap Attrs = getParsedAttrList(Records);
2602 for (const auto &I : Attrs) {
2603 const Record &Attr = *I.second;
2604
2605 if (!Attr.getValueAsBit(FieldName: "ParseArgumentsAsUnevaluated"))
2606 continue;
2607 generateFlattenedSpellingInfo(Attr, Map&: FSIMap);
2608 }
2609 emitStringSwitchCases(Map&: FSIMap, OS);
2610 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n";
2611}
2612
2613static bool isIdentifierArgument(const Record *Arg) {
2614 return !Arg->getDirectSuperClasses().empty() &&
2615 StringSwitch<bool>(
2616 Arg->getDirectSuperClasses().back().first->getName())
2617 .Case(S: "IdentifierArgument", Value: true)
2618 .Case(S: "EnumArgument", Value: true)
2619 .Case(S: "VariadicEnumArgument", Value: true)
2620 .Default(Value: false);
2621}
2622
2623static bool isVariadicIdentifierArgument(const Record *Arg) {
2624 return !Arg->getDirectSuperClasses().empty() &&
2625 StringSwitch<bool>(
2626 Arg->getDirectSuperClasses().back().first->getName())
2627 .Case(S: "VariadicIdentifierArgument", Value: true)
2628 .Case(S: "VariadicParamOrParamIdxArgument", Value: true)
2629 .Default(Value: false);
2630}
2631
2632static bool isVariadicExprArgument(const Record *Arg) {
2633 return !Arg->getDirectSuperClasses().empty() &&
2634 StringSwitch<bool>(
2635 Arg->getDirectSuperClasses().back().first->getName())
2636 .Case(S: "VariadicExprArgument", Value: true)
2637 .Default(Value: false);
2638}
2639
2640static bool isStringLiteralArgument(const Record *Arg) {
2641 if (Arg->getDirectSuperClasses().empty())
2642 return false;
2643 StringRef ArgKind = Arg->getDirectSuperClasses().back().first->getName();
2644 if (ArgKind == "EnumArgument")
2645 return Arg->getValueAsBit(FieldName: "IsString");
2646 return ArgKind == "StringArgument";
2647}
2648
2649static bool isVariadicStringLiteralArgument(const Record *Arg) {
2650 if (Arg->getDirectSuperClasses().empty())
2651 return false;
2652 StringRef ArgKind = Arg->getDirectSuperClasses().back().first->getName();
2653 if (ArgKind == "VariadicEnumArgument")
2654 return Arg->getValueAsBit(FieldName: "IsString");
2655 return ArgKind == "VariadicStringArgument";
2656}
2657
2658static void emitClangAttrVariadicIdentifierArgList(const RecordKeeper &Records,
2659 raw_ostream &OS) {
2660 OS << "#if defined(CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST)\n";
2661 std::map<StringRef, FSIVecTy> FSIMap;
2662 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2663 // Determine whether the first argument is a variadic identifier.
2664 std::vector<const Record *> Args = A->getValueAsListOfDefs(FieldName: "Args");
2665 if (Args.empty() || !isVariadicIdentifierArgument(Arg: Args[0]))
2666 continue;
2667 generateFlattenedSpellingInfo(Attr: *A, Map&: FSIMap);
2668 }
2669 emitStringSwitchCases(Map&: FSIMap, OS);
2670 OS << "#endif // CLANG_ATTR_VARIADIC_IDENTIFIER_ARG_LIST\n\n";
2671}
2672
2673// Emits the list of arguments that should be parsed as unevaluated string
2674// literals for each attribute.
2675static void
2676emitClangAttrUnevaluatedStringLiteralList(const RecordKeeper &Records,
2677 raw_ostream &OS) {
2678 OS << "#if defined(CLANG_ATTR_STRING_LITERAL_ARG_LIST)\n";
2679
2680 auto MakeMask = [](ArrayRef<const Record *> Args) {
2681 uint32_t Bits = 0;
2682 assert(Args.size() <= 32 && "unsupported number of arguments in attribute");
2683 for (uint32_t N = 0; N < Args.size(); ++N) {
2684 Bits |= (isStringLiteralArgument(Arg: Args[N]) << N);
2685 // If we have a variadic string argument, set all the remaining bits to 1
2686 if (isVariadicStringLiteralArgument(Arg: Args[N])) {
2687 Bits |= maskTrailingZeros<decltype(Bits)>(N);
2688 break;
2689 }
2690 }
2691 return Bits;
2692 };
2693
2694 std::map<StringRef, FSIVecTy> FSIMap;
2695 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2696 // Determine whether there are any string arguments.
2697 uint32_t ArgMask = MakeMask(Attr->getValueAsListOfDefs(FieldName: "Args"));
2698 if (!ArgMask)
2699 continue;
2700 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap, ArgMask);
2701 }
2702 emitStringSwitchCases(Map&: FSIMap, OS);
2703 OS << "#endif // CLANG_ATTR_STRING_LITERAL_ARG_LIST\n\n";
2704}
2705
2706// Emits the first-argument-is-identifier property for attributes.
2707static void emitClangAttrIdentifierArgList(const RecordKeeper &Records,
2708 raw_ostream &OS) {
2709 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n";
2710 std::map<StringRef, FSIVecTy> FSIMap;
2711 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2712 // Determine whether the first argument is an identifier.
2713 std::vector<const Record *> Args = Attr->getValueAsListOfDefs(FieldName: "Args");
2714 if (Args.empty() || !isIdentifierArgument(Arg: Args[0]))
2715 continue;
2716 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap);
2717 }
2718 emitStringSwitchCases(Map&: FSIMap, OS);
2719 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n";
2720}
2721
2722// Emits the list for attributes having StrictEnumParameters.
2723static void emitClangAttrStrictIdentifierArgList(const RecordKeeper &Records,
2724 raw_ostream &OS) {
2725 OS << "#if defined(CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST)\n";
2726 std::map<StringRef, FSIVecTy> FSIMap;
2727 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2728 if (!Attr->getValueAsBit(FieldName: "StrictEnumParameters"))
2729 continue;
2730 // Check that there is really an identifier argument.
2731 std::vector<const Record *> Args = Attr->getValueAsListOfDefs(FieldName: "Args");
2732 if (none_of(Range&: Args, P: [&](const Record *R) { return isIdentifierArgument(Arg: R); }))
2733 continue;
2734 generateFlattenedSpellingInfo(Attr: *Attr, Map&: FSIMap);
2735 }
2736 emitStringSwitchCases(Map&: FSIMap, OS);
2737 OS << "#endif // CLANG_ATTR_STRICT_IDENTIFIER_ARG_LIST\n\n";
2738}
2739
2740static bool keywordThisIsaIdentifierInArgument(const Record *Arg) {
2741 return !Arg->getDirectSuperClasses().empty() &&
2742 StringSwitch<bool>(
2743 Arg->getDirectSuperClasses().back().first->getName())
2744 .Case(S: "VariadicParamOrParamIdxArgument", Value: true)
2745 .Default(Value: false);
2746}
2747
2748static void emitClangAttrThisIsaIdentifierArgList(const RecordKeeper &Records,
2749 raw_ostream &OS) {
2750 OS << "#if defined(CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST)\n";
2751 std::map<StringRef, FSIVecTy> FSIMap;
2752 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2753 // Determine whether the first argument is a variadic identifier.
2754 std::vector<const Record *> Args = A->getValueAsListOfDefs(FieldName: "Args");
2755 if (Args.empty() || !keywordThisIsaIdentifierInArgument(Arg: Args[0]))
2756 continue;
2757 generateFlattenedSpellingInfo(Attr: *A, Map&: FSIMap);
2758 }
2759 emitStringSwitchCases(Map&: FSIMap, OS);
2760 OS << "#endif // CLANG_ATTR_THIS_ISA_IDENTIFIER_ARG_LIST\n\n";
2761}
2762
2763static void emitClangAttrAcceptsExprPack(const RecordKeeper &Records,
2764 raw_ostream &OS) {
2765 OS << "#if defined(CLANG_ATTR_ACCEPTS_EXPR_PACK)\n";
2766 ParsedAttrMap Attrs = getParsedAttrList(Records);
2767 std::map<StringRef, FSIVecTy> FSIMap;
2768 for (const auto &I : Attrs) {
2769 const Record &Attr = *I.second;
2770
2771 if (!Attr.getValueAsBit(FieldName: "AcceptsExprPack"))
2772 continue;
2773 generateFlattenedSpellingInfo(Attr, Map&: FSIMap);
2774 }
2775 emitStringSwitchCases(Map&: FSIMap, OS);
2776 OS << "#endif // CLANG_ATTR_ACCEPTS_EXPR_PACK\n\n";
2777}
2778
2779static bool isRegularKeywordAttribute(const FlattenedSpelling &S) {
2780 return (S.variety() == "Keyword" &&
2781 !S.getSpellingRecord().getValueAsBit(FieldName: "HasOwnParseRules"));
2782}
2783
2784static void emitFormInitializer(raw_ostream &OS,
2785 const FlattenedSpelling &Spelling,
2786 StringRef SpellingIndex) {
2787 bool IsAlignas =
2788 (Spelling.variety() == "Keyword" && Spelling.name() == "alignas");
2789 OS << "{AttributeCommonInfo::AS_" << Spelling.variety() << ", "
2790 << SpellingIndex << ", " << (IsAlignas ? "true" : "false")
2791 << " /*IsAlignas*/, "
2792 << (isRegularKeywordAttribute(S: Spelling) ? "true" : "false")
2793 << " /*IsRegularKeywordAttribute*/}";
2794}
2795
2796static void emitAttributes(const RecordKeeper &Records, raw_ostream &OS,
2797 bool Header) {
2798 ParsedAttrMap AttrMap = getParsedAttrList(Records);
2799
2800 // Helper to print the starting character of an attribute argument. If there
2801 // hasn't been an argument yet, it prints an opening parenthese; otherwise it
2802 // prints a comma.
2803 OS << "static inline void DelimitAttributeArgument("
2804 << "raw_ostream& OS, bool& IsFirst) {\n"
2805 << " if (IsFirst) {\n"
2806 << " IsFirst = false;\n"
2807 << " OS << \"(\";\n"
2808 << " } else\n"
2809 << " OS << \", \";\n"
2810 << "}\n";
2811
2812 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
2813 const Record &R = *Attr;
2814
2815 // FIXME: Currently, documentation is generated as-needed due to the fact
2816 // that there is no way to allow a generated project "reach into" the docs
2817 // directory (for instance, it may be an out-of-tree build). However, we want
2818 // to ensure that every attribute has a Documentation field, and produce an
2819 // error if it has been neglected. Otherwise, the on-demand generation which
2820 // happens server-side will fail. This code is ensuring that functionality,
2821 // even though this Emitter doesn't technically need the documentation.
2822 // When attribute documentation can be generated as part of the build
2823 // itself, this code can be removed.
2824 (void)R.getValueAsListOfDefs(FieldName: "Documentation");
2825
2826 if (!R.getValueAsBit(FieldName: "ASTNode"))
2827 continue;
2828
2829 std::vector<const Record *> Supers = R.getSuperClasses();
2830 assert(!Supers.empty() && "Forgot to specify a superclass for the attr");
2831 std::string SuperName;
2832 bool Inheritable = false;
2833 for (const Record *R : reverse(C&: Supers)) {
2834 if (R->getName() != "TargetSpecificAttr" &&
2835 R->getName() != "DeclOrTypeAttr" && SuperName.empty())
2836 SuperName = R->getName().str();
2837 if (R->getName() == "InheritableAttr")
2838 Inheritable = true;
2839 }
2840
2841 if (Header)
2842 OS << "class CLANG_ABI " << R.getName() << "Attr : public " << SuperName
2843 << " {\n";
2844 else
2845 OS << "\n// " << R.getName() << "Attr implementation\n\n";
2846
2847 std::vector<const Record *> ArgRecords = R.getValueAsListOfDefs(FieldName: "Args");
2848 std::vector<std::unique_ptr<Argument>> Args;
2849 Args.reserve(n: ArgRecords.size());
2850
2851 bool AttrAcceptsExprPack = Attr->getValueAsBit(FieldName: "AcceptsExprPack");
2852 if (AttrAcceptsExprPack) {
2853 for (size_t I = 0; I < ArgRecords.size(); ++I) {
2854 const Record *ArgR = ArgRecords[I];
2855 if (isIdentifierArgument(Arg: ArgR) || isVariadicIdentifierArgument(Arg: ArgR) ||
2856 isTypeArgument(Arg: ArgR))
2857 PrintFatalError(ErrorLoc: Attr->getLoc(),
2858 Msg: "Attributes accepting packs cannot also "
2859 "have identifier or type arguments.");
2860 // When trying to determine if value-dependent expressions can populate
2861 // the attribute without prior instantiation, the decision is made based
2862 // on the assumption that only the last argument is ever variadic.
2863 if (I < (ArgRecords.size() - 1) && isVariadicExprArgument(Arg: ArgR))
2864 PrintFatalError(ErrorLoc: Attr->getLoc(),
2865 Msg: "Attributes accepting packs can only have the last "
2866 "argument be variadic.");
2867 }
2868 }
2869
2870 bool HasOptArg = false;
2871 bool HasFakeArg = false;
2872 for (const auto *ArgRecord : ArgRecords) {
2873 Args.emplace_back(args: createArgument(Arg: *ArgRecord, Attr: R.getName()));
2874 if (Header) {
2875 Args.back()->writeDeclarations(OS);
2876 OS << "\n\n";
2877 }
2878
2879 // For these purposes, fake takes priority over optional.
2880 if (Args.back()->isFake()) {
2881 HasFakeArg = true;
2882 } else if (Args.back()->isOptional()) {
2883 HasOptArg = true;
2884 }
2885 }
2886
2887 std::unique_ptr<VariadicExprArgument> DelayedArgs = nullptr;
2888 if (AttrAcceptsExprPack) {
2889 DelayedArgs =
2890 std::make_unique<VariadicExprArgument>(args: "DelayedArgs", args: R.getName());
2891 if (Header) {
2892 DelayedArgs->writeDeclarations(OS);
2893 OS << "\n\n";
2894 }
2895 }
2896
2897 if (Header)
2898 OS << "public:\n";
2899
2900 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
2901
2902 // If there are zero or one spellings, all spelling-related functionality
2903 // can be elided. If all of the spellings share the same name, the spelling
2904 // functionality can also be elided.
2905 bool ElideSpelling = (Spellings.size() <= 1) ||
2906 SpellingNamesAreCommon(Spellings);
2907
2908 // This maps spelling index values to semantic Spelling enumerants.
2909 SemanticSpellingMap SemanticToSyntacticMap;
2910
2911 std::string SpellingEnum;
2912 if (Spellings.size() > 1)
2913 SpellingEnum = CreateSemanticSpellings(Spellings, Map&: SemanticToSyntacticMap);
2914 if (Header)
2915 OS << SpellingEnum;
2916
2917 const auto &ParsedAttrSpellingItr =
2918 find_if(Range&: AttrMap, P: [R](const std::pair<std::string, const Record *> &P) {
2919 return &R == P.second;
2920 });
2921
2922 // Emit CreateImplicit factory methods.
2923 auto emitCreate = [&](bool Implicit, bool DelayedArgsOnly, bool emitFake) {
2924 if (Header)
2925 OS << " static ";
2926 OS << R.getName() << "Attr *";
2927 if (!Header)
2928 OS << R.getName() << "Attr::";
2929 OS << "Create";
2930 if (Implicit)
2931 OS << "Implicit";
2932 if (DelayedArgsOnly)
2933 OS << "WithDelayedArgs";
2934 OS << "(";
2935 OS << "ASTContext &Ctx";
2936 if (!DelayedArgsOnly) {
2937 for (auto const &ai : Args) {
2938 if (ai->isFake() && !emitFake)
2939 continue;
2940 OS << ", ";
2941 ai->writeCtorParameters(OS);
2942 }
2943 } else {
2944 OS << ", ";
2945 DelayedArgs->writeCtorParameters(OS);
2946 }
2947 OS << ", const AttributeCommonInfo &CommonInfo";
2948 OS << ")";
2949 if (Header) {
2950 OS << ";\n";
2951 return;
2952 }
2953
2954 OS << " {\n";
2955 OS << " auto *A = new (Ctx) " << R.getName();
2956 OS << "Attr(Ctx, CommonInfo";
2957
2958 if (!DelayedArgsOnly) {
2959 for (auto const &ai : Args) {
2960 if (ai->isFake() && !emitFake)
2961 continue;
2962 OS << ", ";
2963 ai->writeImplicitCtorArgs(OS);
2964 }
2965 }
2966 OS << ");\n";
2967 if (Implicit) {
2968 OS << " A->setImplicit(true);\n";
2969 }
2970 if (Implicit || ElideSpelling) {
2971 OS << " if (!A->isAttributeSpellingListCalculated() && "
2972 "!A->getAttrName())\n";
2973 OS << " A->setAttributeSpellingListIndex(0);\n";
2974 }
2975 if (DelayedArgsOnly) {
2976 OS << " A->setDelayedArgs(Ctx, ";
2977 DelayedArgs->writeImplicitCtorArgs(OS);
2978 OS << ");\n";
2979 }
2980 OS << " return A;\n}\n\n";
2981 };
2982
2983 auto emitCreateNoCI = [&](bool Implicit, bool DelayedArgsOnly,
2984 bool emitFake) {
2985 if (Header)
2986 OS << " static ";
2987 OS << R.getName() << "Attr *";
2988 if (!Header)
2989 OS << R.getName() << "Attr::";
2990 OS << "Create";
2991 if (Implicit)
2992 OS << "Implicit";
2993 if (DelayedArgsOnly)
2994 OS << "WithDelayedArgs";
2995 OS << "(";
2996 OS << "ASTContext &Ctx";
2997 if (!DelayedArgsOnly) {
2998 for (auto const &ai : Args) {
2999 if (ai->isFake() && !emitFake)
3000 continue;
3001 OS << ", ";
3002 ai->writeCtorParameters(OS);
3003 }
3004 } else {
3005 OS << ", ";
3006 DelayedArgs->writeCtorParameters(OS);
3007 }
3008 OS << ", SourceRange Range";
3009 if (Header)
3010 OS << " = {}";
3011 if (Spellings.size() > 1) {
3012 OS << ", Spelling S";
3013 if (Header)
3014 OS << " = " << SemanticToSyntacticMap[0];
3015 }
3016 OS << ")";
3017 if (Header) {
3018 OS << ";\n";
3019 return;
3020 }
3021
3022 OS << " {\n";
3023 OS << " AttributeCommonInfo I(Range, ";
3024
3025 if (ParsedAttrSpellingItr != std::end(cont&: AttrMap))
3026 OS << "AT_" << ParsedAttrSpellingItr->first;
3027 else
3028 OS << "NoSemaHandlerAttribute";
3029
3030 if (Spellings.size() == 0) {
3031 OS << ", AttributeCommonInfo::Form::Implicit()";
3032 } else if (Spellings.size() == 1) {
3033 OS << ", ";
3034 emitFormInitializer(OS, Spelling: Spellings[0], SpellingIndex: "0");
3035 } else {
3036 OS << ", [&]() {\n";
3037 OS << " switch (S) {\n";
3038 std::set<std::string> Uniques;
3039 unsigned Idx = 0;
3040 for (auto I = Spellings.begin(), E = Spellings.end(); I != E;
3041 ++I, ++Idx) {
3042 const FlattenedSpelling &S = *I;
3043 const auto &Name = SemanticToSyntacticMap[Idx];
3044 if (Uniques.insert(x: Name).second) {
3045 OS << " case " << Name << ":\n";
3046 OS << " return AttributeCommonInfo::Form";
3047 emitFormInitializer(OS, Spelling: S, SpellingIndex: Name);
3048 OS << ";\n";
3049 }
3050 }
3051 OS << " default:\n";
3052 OS << " llvm_unreachable(\"Unknown attribute spelling!\");\n"
3053 << " return AttributeCommonInfo::Form";
3054 emitFormInitializer(OS, Spelling: Spellings[0], SpellingIndex: "0");
3055 OS << ";\n"
3056 << " }\n"
3057 << " }()";
3058 }
3059
3060 OS << ");\n";
3061 OS << " return Create";
3062 if (Implicit)
3063 OS << "Implicit";
3064 if (DelayedArgsOnly)
3065 OS << "WithDelayedArgs";
3066 OS << "(Ctx";
3067 if (!DelayedArgsOnly) {
3068 for (auto const &ai : Args) {
3069 if (ai->isFake() && !emitFake)
3070 continue;
3071 OS << ", ";
3072 ai->writeImplicitCtorArgs(OS);
3073 }
3074 } else {
3075 OS << ", ";
3076 DelayedArgs->writeImplicitCtorArgs(OS);
3077 }
3078 OS << ", I);\n";
3079 OS << "}\n\n";
3080 };
3081
3082 auto emitCreates = [&](bool DelayedArgsOnly, bool emitFake) {
3083 emitCreate(true, DelayedArgsOnly, emitFake);
3084 emitCreate(false, DelayedArgsOnly, emitFake);
3085 emitCreateNoCI(true, DelayedArgsOnly, emitFake);
3086 emitCreateNoCI(false, DelayedArgsOnly, emitFake);
3087 };
3088
3089 if (Header)
3090 OS << " // Factory methods\n";
3091
3092 // Emit a CreateImplicit that takes all the arguments.
3093 emitCreates(false, true);
3094
3095 // Emit a CreateImplicit that takes all the non-fake arguments.
3096 if (HasFakeArg)
3097 emitCreates(false, false);
3098
3099 // Emit a CreateWithDelayedArgs that takes only the dependent argument
3100 // expressions.
3101 if (DelayedArgs)
3102 emitCreates(true, false);
3103
3104 // Emit constructors.
3105 auto emitCtor = [&](bool emitOpt, bool emitFake, bool emitNoArgs) {
3106 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) {
3107 if (emitNoArgs)
3108 return false;
3109 if (arg->isFake())
3110 return emitFake;
3111 if (arg->isOptional())
3112 return emitOpt;
3113 return true;
3114 };
3115 if (Header)
3116 OS << " ";
3117 else
3118 OS << R.getName() << "Attr::";
3119 OS << R.getName()
3120 << "Attr(ASTContext &Ctx, const AttributeCommonInfo &CommonInfo";
3121 OS << '\n';
3122 for (auto const &ai : Args) {
3123 if (!shouldEmitArg(ai))
3124 continue;
3125 OS << " , ";
3126 ai->writeCtorParameters(OS);
3127 OS << "\n";
3128 }
3129
3130 OS << " )";
3131 if (Header) {
3132 OS << ";\n";
3133 return;
3134 }
3135 OS << "\n : " << SuperName << "(Ctx, CommonInfo, ";
3136 OS << "attr::" << R.getName() << ", ";
3137
3138 // Handle different late parsing modes.
3139 OS << "/*IsLateParsed=*/";
3140 switch (getLateAttrParseKind(Attr: &R)) {
3141 case LateAttrParseKind::Never:
3142 OS << "false";
3143 break;
3144 case LateAttrParseKind::ExperimentalExt:
3145 // Currently no clients need to know the distinction between `Standard`
3146 // and `ExperimentalExt` so treat `ExperimentalExt` just like
3147 // `Standard` for now.
3148 case LateAttrParseKind::Standard:
3149 // Note: This is misleading. `IsLateParsed` doesn't mean the
3150 // attribute was actually late parsed. Instead it means the attribute in
3151 // `Attr.td` is marked as being late parsed. Maybe it should be called
3152 // `IsLateParseable`?
3153 OS << "true";
3154 break;
3155 }
3156
3157 if (Inheritable) {
3158 OS << ", "
3159 << (R.getValueAsBit(FieldName: "InheritEvenIfAlreadyPresent") ? "true"
3160 : "false");
3161 }
3162 OS << ")\n";
3163
3164 for (auto const &ai : Args) {
3165 OS << " , ";
3166 if (!shouldEmitArg(ai)) {
3167 ai->writeCtorDefaultInitializers(OS);
3168 } else {
3169 ai->writeCtorInitializers(OS);
3170 }
3171 OS << "\n";
3172 }
3173 if (DelayedArgs) {
3174 OS << " , ";
3175 DelayedArgs->writeCtorDefaultInitializers(OS);
3176 OS << "\n";
3177 }
3178
3179 OS << " {\n";
3180
3181 for (auto const &ai : Args) {
3182 if (!shouldEmitArg(ai))
3183 continue;
3184 ai->writeCtorBody(OS);
3185 }
3186 OS << "}\n\n";
3187 };
3188
3189 if (Header)
3190 OS << "\n // Constructors\n";
3191
3192 // Emit a constructor that includes all the arguments.
3193 // This is necessary for cloning.
3194 emitCtor(true, true, false);
3195
3196 // Emit a constructor that takes all the non-fake arguments.
3197 if (HasFakeArg)
3198 emitCtor(true, false, false);
3199
3200 // Emit a constructor that takes all the non-fake, non-optional arguments.
3201 if (HasOptArg)
3202 emitCtor(false, false, false);
3203
3204 // Emit constructors that takes no arguments if none already exists.
3205 // This is used for delaying arguments.
3206 bool HasRequiredArgs =
3207 count_if(Range&: Args, P: [=](const std::unique_ptr<Argument> &arg) {
3208 return !arg->isFake() && !arg->isOptional();
3209 });
3210 if (DelayedArgs && HasRequiredArgs)
3211 emitCtor(false, false, true);
3212
3213 if (Header) {
3214 OS << '\n';
3215 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n";
3216 OS << " void printPretty(raw_ostream &OS,\n"
3217 << " const PrintingPolicy &Policy) const;\n";
3218 OS << " const char *getSpelling() const;\n";
3219 }
3220
3221 if (!ElideSpelling) {
3222 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list");
3223 if (Header)
3224 OS << " Spelling getSemanticSpelling() const;\n";
3225 else {
3226 OS << R.getName() << "Attr::Spelling " << R.getName()
3227 << "Attr::getSemanticSpelling() const {\n";
3228 WriteSemanticSpellingSwitch(VarName: "getAttributeSpellingListIndex()",
3229 Map: SemanticToSyntacticMap, OS);
3230 OS << "}\n";
3231 }
3232 }
3233
3234 if (Header)
3235 writeAttrAccessorDefinition(R, OS);
3236
3237 for (auto const &ai : Args) {
3238 if (Header) {
3239 ai->writeAccessors(OS);
3240 } else {
3241 ai->writeAccessorDefinitions(OS);
3242 }
3243 OS << "\n\n";
3244
3245 // Don't write conversion routines for fake arguments.
3246 if (ai->isFake()) continue;
3247
3248 if (ai->isEnumArg())
3249 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS,
3250 Header);
3251 else if (ai->isVariadicEnumArg())
3252 static_cast<const VariadicEnumArgument *>(ai.get())->writeConversion(
3253 OS, Header);
3254 }
3255
3256 std::string FnStr = "isEquivalent(const ";
3257 FnStr += R.getName();
3258 FnStr += "Attr &Other, StructuralEquivalenceContext &Context) const";
3259 if (Header) {
3260 OS << " bool " << FnStr << ";\n";
3261 } else {
3262 OS << "bool " << R.getName() << "Attr::" << FnStr << " {\n";
3263 std::string CustomFn = R.getValueAsString(FieldName: "comparisonFn").str();
3264 if (CustomFn.empty()) {
3265 if (!ElideSpelling)
3266 OS << " if (getSpelling() != Other.getSpelling()) return false;\n\n";
3267 for (const auto &ai : Args) {
3268 OS << " if (!" << ai->emitAttrArgEqualityCheck() << ")\n";
3269 OS << " return false;\n";
3270 }
3271 OS << " return true;\n";
3272 } else {
3273 OS << " return " + CustomFn + "(*this, Other, Context);\n";
3274 }
3275 OS << "}\n\n";
3276 }
3277
3278 StringRef ProfileSig = "Profile(llvm::FoldingSetNodeID &ID, "
3279 "const ASTContext &Ctx) const";
3280 if (Header) {
3281 OS << " void " << ProfileSig << ";\n";
3282 } else {
3283 OS << "void " << R.getName() << "Attr::" << ProfileSig << " {\n";
3284 std::string CustomFn = R.getValueAsString(FieldName: "profileFn").str();
3285 if (CustomFn.empty()) {
3286 for (const auto &ai : Args)
3287 OS << " " << ai->emitAttrArgProfileCall() << ";\n";
3288 } else {
3289 OS << " " << CustomFn << "(*this, ID, Ctx);\n";
3290 }
3291 OS << "}\n\n";
3292 }
3293
3294 if (Header) {
3295 if (DelayedArgs) {
3296 DelayedArgs->writeAccessors(OS);
3297 DelayedArgs->writeSetter(OS);
3298 }
3299
3300 OS << R.getValueAsString(FieldName: "AdditionalMembers");
3301 OS << "\n\n";
3302
3303 OS << " static bool classof(const Attr *A) { return A->getKind() == "
3304 << "attr::" << R.getName() << "; }\n";
3305
3306 OS << "};\n\n";
3307 } else {
3308 if (DelayedArgs)
3309 DelayedArgs->writeAccessorDefinitions(OS);
3310
3311 OS << R.getName() << "Attr *" << R.getName()
3312 << "Attr::clone(ASTContext &C) const {\n";
3313 OS << " auto *A = new (C) " << R.getName() << "Attr(C, *this";
3314 for (auto const &ai : Args) {
3315 OS << ", ";
3316 ai->writeCloneArgs(OS);
3317 }
3318 OS << ");\n";
3319 OS << " A->Inherited = Inherited;\n";
3320 OS << " A->IsPackExpansion = IsPackExpansion;\n";
3321 OS << " A->setImplicit(Implicit);\n";
3322 if (DelayedArgs) {
3323 OS << " A->setDelayedArgs(C, ";
3324 DelayedArgs->writeCloneArgs(OS);
3325 OS << ");\n";
3326 }
3327 OS << " return A;\n}\n\n";
3328
3329 writePrettyPrintFunction(R, Args, OS);
3330 writeGetSpellingFunction(R, OS);
3331 }
3332 }
3333}
3334// Emits the class definitions for attributes.
3335void clang::EmitClangAttrClass(const RecordKeeper &Records, raw_ostream &OS) {
3336 emitSourceFileHeader(Desc: "Attribute classes' definitions", OS, Record: Records);
3337
3338 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n";
3339 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n";
3340
3341 emitAttributes(Records, OS, Header: true);
3342
3343 OS << "#endif // LLVM_CLANG_ATTR_CLASSES_INC\n";
3344}
3345
3346static void emitEquivalenceFunction(const RecordKeeper &Records,
3347 raw_ostream &OS) {
3348 OS << "bool Attr::isEquivalent(const Attr &Other, "
3349 "StructuralEquivalenceContext &Context) const {\n";
3350 OS << "if (getKind() != Other.getKind()) return false;\n\n";
3351 OS << " switch (getKind()) {\n";
3352 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3353 const Record &R = *Attr;
3354 if (!R.getValueAsBit(FieldName: "ASTNode"))
3355 continue;
3356
3357 OS << " case attr::" << R.getName() << ":\n";
3358 OS << " return cast<" << R.getName() << "Attr>(this)->isEquivalent(cast<"
3359 << R.getName() << "Attr>(Other), Context);\n";
3360 }
3361 OS << " }\n";
3362 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
3363 OS << "}\n\n";
3364}
3365
3366static void emitProfileFunction(const RecordKeeper &Records, raw_ostream &OS) {
3367 OS << "void Attr::Profile(llvm::FoldingSetNodeID &ID, "
3368 "const ASTContext &Ctx) const {\n";
3369 OS << " switch (getKind()) {\n";
3370 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3371 const Record &R = *Attr;
3372 if (!R.getValueAsBit(FieldName: "ASTNode"))
3373 continue;
3374 OS << " case attr::" << R.getName() << ":\n";
3375 OS << " return cast<" << R.getName()
3376 << "Attr>(this)->Profile(ID, Ctx);\n";
3377 }
3378 OS << " }\n";
3379 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
3380 OS << "}\n\n";
3381}
3382
3383// Emits the class method definitions for attributes.
3384void clang::EmitClangAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
3385 emitSourceFileHeader(Desc: "Attribute classes' member function definitions", OS,
3386 Record: Records);
3387
3388 emitAttributes(Records, OS, Header: false);
3389
3390 // Instead of relying on virtual dispatch we just create a huge dispatch
3391 // switch. This is both smaller and faster than virtual functions.
3392 auto EmitFunc = [&](const char *Method) {
3393 OS << " switch (getKind()) {\n";
3394 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3395 const Record &R = *Attr;
3396 if (!R.getValueAsBit(FieldName: "ASTNode"))
3397 continue;
3398
3399 OS << " case attr::" << R.getName() << ":\n";
3400 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method
3401 << ";\n";
3402 }
3403 OS << " }\n";
3404 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n";
3405 OS << "}\n\n";
3406 };
3407
3408 OS << "const char *Attr::getSpelling() const {\n";
3409 EmitFunc("getSpelling()");
3410
3411 OS << "Attr *Attr::clone(ASTContext &C) const {\n";
3412 EmitFunc("clone(C)");
3413
3414 OS << "void Attr::printPretty(raw_ostream &OS, "
3415 "const PrintingPolicy &Policy) const {\n";
3416 EmitFunc("printPretty(OS, Policy)");
3417
3418 emitEquivalenceFunction(Records, OS);
3419 emitProfileFunction(Records, OS);
3420}
3421
3422static void emitAttrList(raw_ostream &OS, StringRef Class,
3423 ArrayRef<const Record *> AttrList) {
3424 for (auto Cur : AttrList) {
3425 OS << Class << "(" << Cur->getName() << ")\n";
3426 }
3427}
3428
3429// Determines if an attribute has a Pragma spelling.
3430static bool AttrHasPragmaSpelling(const Record *R) {
3431 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: *R);
3432 return any_of(Range&: Spellings, P: [](const FlattenedSpelling &S) {
3433 return S.variety() == "Pragma";
3434 });
3435}
3436
3437namespace {
3438
3439 struct AttrClassDescriptor {
3440 const char * const MacroName;
3441 const char * const TableGenName;
3442 };
3443
3444} // end anonymous namespace
3445
3446static const AttrClassDescriptor AttrClassDescriptors[] = {
3447 {.MacroName: "ATTR", .TableGenName: "Attr"},
3448 {.MacroName: "TYPE_ATTR", .TableGenName: "TypeAttr"},
3449 {.MacroName: "STMT_ATTR", .TableGenName: "StmtAttr"},
3450 {.MacroName: "DECL_OR_STMT_ATTR", .TableGenName: "DeclOrStmtAttr"},
3451 {.MacroName: "INHERITABLE_ATTR", .TableGenName: "InheritableAttr"},
3452 {.MacroName: "DECL_OR_TYPE_ATTR", .TableGenName: "DeclOrTypeAttr"},
3453 {.MacroName: "INHERITABLE_PARAM_ATTR", .TableGenName: "InheritableParamAttr"},
3454 {.MacroName: "INHERITABLE_PARAM_OR_STMT_ATTR", .TableGenName: "InheritableParamOrStmtAttr"},
3455 {.MacroName: "PARAMETER_ABI_ATTR", .TableGenName: "ParameterABIAttr"},
3456 {.MacroName: "HLSL_ANNOTATION_ATTR", .TableGenName: "HLSLAnnotationAttr"},
3457 {.MacroName: "HLSL_SEMANTIC_ATTR", .TableGenName: "HLSLSemanticBaseAttr"}};
3458
3459static void emitDefaultDefine(raw_ostream &OS, StringRef name,
3460 const char *superName) {
3461 OS << "#ifndef " << name << "\n";
3462 OS << "#define " << name << "(NAME) ";
3463 if (superName) OS << superName << "(NAME)";
3464 OS << "\n#endif\n\n";
3465}
3466
3467namespace {
3468
3469 /// A class of attributes.
3470 struct AttrClass {
3471 const AttrClassDescriptor &Descriptor;
3472 const Record *TheRecord;
3473 AttrClass *SuperClass = nullptr;
3474 std::vector<AttrClass*> SubClasses;
3475 std::vector<const Record *> Attrs;
3476
3477 AttrClass(const AttrClassDescriptor &Descriptor, const Record *R)
3478 : Descriptor(Descriptor), TheRecord(R) {}
3479
3480 void emitDefaultDefines(raw_ostream &OS) const {
3481 // Default the macro unless this is a root class (i.e. Attr).
3482 if (SuperClass) {
3483 emitDefaultDefine(OS, name: Descriptor.MacroName,
3484 superName: SuperClass->Descriptor.MacroName);
3485 }
3486 }
3487
3488 void emitUndefs(raw_ostream &OS) const {
3489 OS << "#undef " << Descriptor.MacroName << "\n";
3490 }
3491
3492 void emitAttrList(raw_ostream &OS) const {
3493 for (auto SubClass : SubClasses) {
3494 SubClass->emitAttrList(OS);
3495 }
3496
3497 ::emitAttrList(OS, Class: Descriptor.MacroName, AttrList: Attrs);
3498 }
3499
3500 void classifyAttrOnRoot(const Record *Attr) {
3501 bool result = classifyAttr(Attr);
3502 assert(result && "failed to classify on root"); (void) result;
3503 }
3504
3505 void emitAttrRange(raw_ostream &OS) const {
3506 OS << "ATTR_RANGE(" << Descriptor.TableGenName
3507 << ", " << getFirstAttr()->getName()
3508 << ", " << getLastAttr()->getName() << ")\n";
3509 }
3510
3511 private:
3512 bool classifyAttr(const Record *Attr) {
3513 // Check all the subclasses.
3514 for (auto SubClass : SubClasses) {
3515 if (SubClass->classifyAttr(Attr))
3516 return true;
3517 }
3518
3519 // It's not more specific than this class, but it might still belong here.
3520 if (Attr->isSubClassOf(R: TheRecord)) {
3521 Attrs.push_back(x: Attr);
3522 return true;
3523 }
3524
3525 return false;
3526 }
3527
3528 const Record *getFirstAttr() const {
3529 if (!SubClasses.empty())
3530 return SubClasses.front()->getFirstAttr();
3531 return Attrs.front();
3532 }
3533
3534 const Record *getLastAttr() const {
3535 if (!Attrs.empty())
3536 return Attrs.back();
3537 return SubClasses.back()->getLastAttr();
3538 }
3539 };
3540
3541 /// The entire hierarchy of attribute classes.
3542 class AttrClassHierarchy {
3543 std::vector<std::unique_ptr<AttrClass>> Classes;
3544
3545 public:
3546 AttrClassHierarchy(const RecordKeeper &Records) {
3547 // Find records for all the classes.
3548 for (auto &Descriptor : AttrClassDescriptors) {
3549 const Record *ClassRecord = Records.getClass(Name: Descriptor.TableGenName);
3550 AttrClass *Class = new AttrClass(Descriptor, ClassRecord);
3551 Classes.emplace_back(args&: Class);
3552 }
3553
3554 // Link up the hierarchy.
3555 for (auto &Class : Classes) {
3556 if (AttrClass *SuperClass = findSuperClass(R: Class->TheRecord)) {
3557 Class->SuperClass = SuperClass;
3558 SuperClass->SubClasses.push_back(x: Class.get());
3559 }
3560 }
3561
3562#ifndef NDEBUG
3563 for (auto i = Classes.begin(), e = Classes.end(); i != e; ++i) {
3564 assert((i == Classes.begin()) == ((*i)->SuperClass == nullptr) &&
3565 "only the first class should be a root class!");
3566 }
3567#endif
3568 }
3569
3570 void emitDefaultDefines(raw_ostream &OS) const {
3571 for (auto &Class : Classes) {
3572 Class->emitDefaultDefines(OS);
3573 }
3574 }
3575
3576 void emitUndefs(raw_ostream &OS) const {
3577 for (auto &Class : Classes) {
3578 Class->emitUndefs(OS);
3579 }
3580 }
3581
3582 void emitAttrLists(raw_ostream &OS) const {
3583 // Just start from the root class.
3584 Classes[0]->emitAttrList(OS);
3585 }
3586
3587 void emitAttrRanges(raw_ostream &OS) const {
3588 for (auto &Class : Classes)
3589 Class->emitAttrRange(OS);
3590 }
3591
3592 void classifyAttr(const Record *Attr) {
3593 // Add the attribute to the root class.
3594 Classes[0]->classifyAttrOnRoot(Attr);
3595 }
3596
3597 private:
3598 AttrClass *findClassByRecord(const Record *R) const {
3599 for (auto &Class : Classes) {
3600 if (Class->TheRecord == R)
3601 return Class.get();
3602 }
3603 return nullptr;
3604 }
3605
3606 AttrClass *findSuperClass(const Record *R) const {
3607 // TableGen flattens the superclass list, so we just need to walk it
3608 // in reverse.
3609 std::vector<const Record *> SuperClasses = R->getSuperClasses();
3610 for (const Record *R : reverse(C&: SuperClasses)) {
3611 if (AttrClass *SuperClass = findClassByRecord(R))
3612 return SuperClass;
3613 }
3614 return nullptr;
3615 }
3616 };
3617
3618} // end anonymous namespace
3619
3620namespace clang {
3621
3622// Emits the enumeration list for attributes.
3623void EmitClangAttrList(const RecordKeeper &Records, raw_ostream &OS) {
3624 emitSourceFileHeader(Desc: "List of all attributes that Clang recognizes", OS,
3625 Record: Records);
3626
3627 AttrClassHierarchy Hierarchy(Records);
3628
3629 // Add defaulting macro definitions.
3630 Hierarchy.emitDefaultDefines(OS);
3631 emitDefaultDefine(OS, name: "PRAGMA_SPELLING_ATTR", superName: nullptr);
3632
3633 std::vector<const Record *> PragmaAttrs;
3634 for (auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3635 if (!Attr->getValueAsBit(FieldName: "ASTNode"))
3636 continue;
3637
3638 // Add the attribute to the ad-hoc groups.
3639 if (AttrHasPragmaSpelling(R: Attr))
3640 PragmaAttrs.push_back(x: Attr);
3641
3642 // Place it in the hierarchy.
3643 Hierarchy.classifyAttr(Attr);
3644 }
3645
3646 // Emit the main attribute list.
3647 Hierarchy.emitAttrLists(OS);
3648
3649 // Emit the ad hoc groups.
3650 emitAttrList(OS, Class: "PRAGMA_SPELLING_ATTR", AttrList: PragmaAttrs);
3651
3652 // Emit the attribute ranges.
3653 OS << "#ifdef ATTR_RANGE\n";
3654 Hierarchy.emitAttrRanges(OS);
3655 OS << "#undef ATTR_RANGE\n";
3656 OS << "#endif\n";
3657
3658 Hierarchy.emitUndefs(OS);
3659 OS << "#undef PRAGMA_SPELLING_ATTR\n";
3660}
3661
3662// Emits the enumeration list for attributes.
3663void EmitClangAttrSubjectMatchRuleList(const RecordKeeper &Records,
3664 raw_ostream &OS) {
3665 emitSourceFileHeader(
3666 Desc: "List of all attribute subject matching rules that Clang recognizes", OS,
3667 Record: Records);
3668 PragmaClangAttributeSupport &PragmaAttributeSupport =
3669 getPragmaAttributeSupport(Records);
3670 emitDefaultDefine(OS, name: "ATTR_MATCH_RULE", superName: nullptr);
3671 PragmaAttributeSupport.emitMatchRuleList(OS);
3672 OS << "#undef ATTR_MATCH_RULE\n";
3673}
3674
3675// Emits the code to read an attribute from a precompiled header.
3676void EmitClangAttrPCHRead(const RecordKeeper &Records, raw_ostream &OS) {
3677 emitSourceFileHeader(Desc: "Attribute deserialization code", OS, Record: Records);
3678
3679 const Record *InhClass = Records.getClass(Name: "InheritableAttr");
3680 std::vector<const Record *> ArgRecords;
3681 std::vector<std::unique_ptr<Argument>> Args;
3682 std::unique_ptr<VariadicExprArgument> DelayedArgs;
3683
3684 OS << " switch (Kind) {\n";
3685 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3686 const Record &R = *Attr;
3687 if (!R.getValueAsBit(FieldName: "ASTNode"))
3688 continue;
3689
3690 OS << " case attr::" << R.getName() << ": {\n";
3691 if (R.isSubClassOf(R: InhClass))
3692 OS << " bool isInherited = Record.readInt();\n";
3693 OS << " bool isImplicit = Record.readInt();\n";
3694 OS << " bool isPackExpansion = Record.readInt();\n";
3695 DelayedArgs = nullptr;
3696 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack")) {
3697 DelayedArgs =
3698 std::make_unique<VariadicExprArgument>(args: "DelayedArgs", args: R.getName());
3699 DelayedArgs->writePCHReadDecls(OS);
3700 }
3701 ArgRecords = R.getValueAsListOfDefs(FieldName: "Args");
3702 Args.clear();
3703 for (const auto *Arg : ArgRecords) {
3704 Args.emplace_back(args: createArgument(Arg: *Arg, Attr: R.getName()));
3705 Args.back()->writePCHReadDecls(OS);
3706 }
3707 OS << " New = new (Context) " << R.getName() << "Attr(Context, Info";
3708 for (auto const &ri : Args) {
3709 OS << ", ";
3710 ri->writePCHReadArgs(OS);
3711 }
3712 OS << ");\n";
3713 if (R.isSubClassOf(R: InhClass))
3714 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n";
3715 OS << " New->setImplicit(isImplicit);\n";
3716 OS << " New->setPackExpansion(isPackExpansion);\n";
3717 if (DelayedArgs) {
3718 OS << " cast<" << R.getName()
3719 << "Attr>(New)->setDelayedArgs(Context, ";
3720 DelayedArgs->writePCHReadArgs(OS);
3721 OS << ");\n";
3722 }
3723
3724 if (Attr->getValueAsBit(FieldName: "HasCustomSerialization"))
3725 OS << " read" << R.getName() << "Attr(cast<" << R.getName()
3726 << "Attr>(New));\n";
3727
3728 OS << " break;\n";
3729 OS << " }\n";
3730 }
3731 OS << " }\n";
3732}
3733
3734// Emits the code to write an attribute to a precompiled header.
3735void EmitClangAttrPCHWrite(const RecordKeeper &Records, raw_ostream &OS) {
3736 emitSourceFileHeader(Desc: "Attribute serialization code", OS, Record: Records);
3737
3738 const Record *InhClass = Records.getClass(Name: "InheritableAttr");
3739 OS << " switch (A->getKind()) {\n";
3740 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3741 const Record &R = *Attr;
3742 if (!R.getValueAsBit(FieldName: "ASTNode"))
3743 continue;
3744 OS << " case attr::" << R.getName() << ": {\n";
3745 std::vector<const Record *> Args = R.getValueAsListOfDefs(FieldName: "Args");
3746 if (R.isSubClassOf(R: InhClass) || !Args.empty())
3747 OS << " const auto *SA = cast<" << R.getName()
3748 << "Attr>(A);\n";
3749 if (R.isSubClassOf(R: InhClass))
3750 OS << " Record.push_back(SA->isInherited());\n";
3751 OS << " Record.push_back(A->isImplicit());\n";
3752 OS << " Record.push_back(A->isPackExpansion());\n";
3753 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
3754 VariadicExprArgument("DelayedArgs", R.getName()).writePCHWrite(OS);
3755
3756 for (const auto *Arg : Args)
3757 createArgument(Arg: *Arg, Attr: R.getName())->writePCHWrite(OS);
3758
3759 if (Attr->getValueAsBit(FieldName: "HasCustomSerialization"))
3760 OS << " Record.Add" << R.getName() << "Attr(SA);\n";
3761
3762 OS << " break;\n";
3763 OS << " }\n";
3764 }
3765 OS << " }\n";
3766}
3767
3768} // namespace clang
3769
3770// Helper function for GenerateTargetSpecificAttrChecks that alters the 'Test'
3771// parameter with only a single check type, if applicable.
3772static bool GenerateTargetSpecificAttrCheck(const Record *R, std::string &Test,
3773 std::string *FnName,
3774 StringRef ListName,
3775 StringRef CheckAgainst,
3776 StringRef Scope) {
3777 if (!R->isValueUnset(FieldName: ListName)) {
3778 Test += " && (";
3779 std::vector<StringRef> Items = R->getValueAsListOfStrings(FieldName: ListName);
3780 for (auto I = Items.begin(), E = Items.end(); I != E; ++I) {
3781 StringRef Part = *I;
3782 Test += CheckAgainst;
3783 Test += " == ";
3784 Test += Scope;
3785 Test += Part;
3786 if (I + 1 != E)
3787 Test += " || ";
3788 if (FnName)
3789 *FnName += Part;
3790 }
3791 Test += ")";
3792 return true;
3793 }
3794 return false;
3795}
3796
3797// Generate a conditional expression to check if the current target satisfies
3798// the conditions for a TargetSpecificAttr record, and append the code for
3799// those checks to the Test string. If the FnName string pointer is non-null,
3800// append a unique suffix to distinguish this set of target checks from other
3801// TargetSpecificAttr records.
3802static bool GenerateTargetSpecificAttrChecks(const Record *R,
3803 std::vector<StringRef> &Arches,
3804 std::string &Test,
3805 std::string *FnName) {
3806 bool AnyTargetChecks = false;
3807
3808 // It is assumed that there will be an Triple object
3809 // named "T" and a TargetInfo object named "Target" within
3810 // scope that can be used to determine whether the attribute exists in
3811 // a given target.
3812 Test += "true";
3813 // If one or more architectures is specified, check those. Arches are handled
3814 // differently because GenerateTargetRequirements needs to combine the list
3815 // with ParseKind.
3816 if (!Arches.empty()) {
3817 AnyTargetChecks = true;
3818 Test += " && (";
3819 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) {
3820 StringRef Part = *I;
3821 Test += "T.getArch() == llvm::Triple::";
3822 Test += Part;
3823 if (I + 1 != E)
3824 Test += " || ";
3825 if (FnName)
3826 *FnName += Part;
3827 }
3828 Test += ")";
3829 }
3830
3831 // If the attribute is specific to particular OSes, check those.
3832 AnyTargetChecks |= GenerateTargetSpecificAttrCheck(
3833 R, Test, FnName, ListName: "OSes", CheckAgainst: "T.getOS()", Scope: "llvm::Triple::");
3834
3835 // If one or more object formats is specified, check those.
3836 AnyTargetChecks |=
3837 GenerateTargetSpecificAttrCheck(R, Test, FnName, ListName: "ObjectFormats",
3838 CheckAgainst: "T.getObjectFormat()", Scope: "llvm::Triple::");
3839
3840 // If custom code is specified, emit it.
3841 StringRef Code = R->getValueAsString(FieldName: "CustomCode");
3842 if (!Code.empty()) {
3843 AnyTargetChecks = true;
3844 Test += " && (";
3845 Test += Code;
3846 Test += ")";
3847 }
3848
3849 return AnyTargetChecks;
3850}
3851
3852static void GenerateHasAttrSpellingStringSwitch(
3853 ArrayRef<std::pair<const Record *, FlattenedSpelling>> Attrs,
3854 raw_ostream &OS, StringRef Variety, StringRef Scope = "") {
3855
3856 // It turns out that there are duplicate records for a given spelling. This
3857 // map combines matching test strings using '||'. For example, if there are
3858 // three conditions A, B, and C, the final result will be: A || B || C.
3859 llvm::StringMap<std::string> TestStringMap;
3860
3861 for (const auto &[Attr, Spelling] : Attrs) {
3862 // C++11-style attributes have specific version information associated with
3863 // them. If the attribute has no scope, the version information must not
3864 // have the default value (1), as that's incorrect. Instead, the unscoped
3865 // attribute version information should be taken from the SD-6 standing
3866 // document, which can be found at:
3867 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations
3868 //
3869 // C23-style attributes have the same kind of version information
3870 // associated with them. The unscoped attribute version information should
3871 // be taken from the specification of the attribute in the C Standard.
3872 //
3873 // Clang-specific attributes have the same kind of version information
3874 // associated with them. This version is typically the default value (1).
3875 // These version values are clang-specific and should typically be
3876 // incremented once the attribute changes its syntax and/or semantics in a
3877 // a way that is impactful to the end user.
3878 int Version = 1;
3879
3880 assert(Spelling.variety() == Variety);
3881 std::string Name = "";
3882 if (Spelling.nameSpace().empty() || Scope == Spelling.nameSpace()) {
3883 Name = Spelling.name();
3884 Version = static_cast<int>(
3885 Spelling.getSpellingRecord().getValueAsInt(FieldName: "Version"));
3886 // Verify that explicitly specified CXX11 and C23 spellings (i.e.
3887 // not inferred from Clang/GCC spellings) have a version that's
3888 // different from the default (1).
3889 bool RequiresValidVersion =
3890 (Variety == "CXX11" || Variety == "C23") &&
3891 Spelling.getSpellingRecord().getValueAsString(FieldName: "Variety") == Variety;
3892 if (RequiresValidVersion && Scope.empty() && Version == 1)
3893 PrintError(ErrorLoc: Spelling.getSpellingRecord().getLoc(),
3894 Msg: "Standard attributes must have "
3895 "valid version information.");
3896 }
3897
3898 std::string Test;
3899 if (Attr->isSubClassOf(Name: "TargetSpecificAttr")) {
3900 const Record *R = Attr->getValueAsDef(FieldName: "Target");
3901 std::vector<StringRef> Arches = R->getValueAsListOfStrings(FieldName: "Arches");
3902 GenerateTargetSpecificAttrChecks(R, Arches, Test, FnName: nullptr);
3903 } else if (!Attr->getValueAsListOfDefs(FieldName: "TargetSpecificSpellings").empty()) {
3904 // Add target checks if this spelling is target-specific.
3905 for (const auto &TargetSpelling :
3906 Attr->getValueAsListOfDefs(FieldName: "TargetSpecificSpellings")) {
3907 // Find spelling that matches current scope and name.
3908 for (const auto &Spelling : GetFlattenedSpellings(Attr: *TargetSpelling)) {
3909 if (Scope == Spelling.nameSpace() && Name == Spelling.name()) {
3910 const Record *Target = TargetSpelling->getValueAsDef(FieldName: "Target");
3911 std::vector<StringRef> Arches =
3912 Target->getValueAsListOfStrings(FieldName: "Arches");
3913 GenerateTargetSpecificAttrChecks(R: Target, Arches, Test,
3914 /*FnName=*/nullptr);
3915 break;
3916 }
3917 }
3918 }
3919 }
3920
3921 std::string TestStr =
3922 !Test.empty() ? '(' + Test + " ? " + itostr(X: Version) + " : 0" + ')'
3923 : '(' + itostr(X: Version) + ')';
3924
3925 if (Scope.empty() || Scope == Spelling.nameSpace()) {
3926 if (TestStringMap.contains(Key: Spelling.name()) &&
3927 TestStringMap[Spelling.name()] != TestStr)
3928 TestStringMap[Spelling.name()] += " || " + TestStr;
3929 else
3930 TestStringMap[Spelling.name()] = TestStr;
3931 }
3932 }
3933
3934 // Create the actual string switch statement after all the attributes have
3935 // been parsed.
3936 for (auto &Entry : TestStringMap) {
3937 OS << " .Case(\"" << Entry.getKey() << "\", " << Entry.getValue()
3938 << ")\n";
3939 }
3940
3941 OS << " .Default(0);\n";
3942}
3943
3944namespace clang {
3945
3946// Emits list of regular keyword attributes with info about their arguments.
3947void EmitClangRegularKeywordAttributeInfo(const RecordKeeper &Records,
3948 raw_ostream &OS) {
3949 emitSourceFileHeader(
3950 Desc: "A list of regular keyword attributes generated from the attribute"
3951 " definitions",
3952 OS);
3953 // Assume for now that the same token is not used in multiple regular
3954 // keyword attributes.
3955 for (auto *R : Records.getAllDerivedDefinitions(ClassName: "Attr"))
3956 for (const auto &S : GetFlattenedSpellings(Attr: *R)) {
3957 if (!isRegularKeywordAttribute(S))
3958 continue;
3959 std::vector<const Record *> Args = R->getValueAsListOfDefs(FieldName: "Args");
3960 bool HasArgs = any_of(
3961 Range&: Args, P: [](const Record *Arg) { return !Arg->getValueAsBit(FieldName: "Fake"); });
3962
3963 OS << "KEYWORD_ATTRIBUTE("
3964 << S.getSpellingRecord().getValueAsString(FieldName: "Name") << ", "
3965 << (HasArgs ? "true" : "false") << ", )\n";
3966 }
3967 OS << "#undef KEYWORD_ATTRIBUTE\n";
3968}
3969
3970void EmitCXX11AttributeInfo(const RecordKeeper &Records, raw_ostream &OS) {
3971 OS << "#if defined(CXX11_ATTR_ARGS_INFO)\n";
3972 for (auto *R : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
3973 for (const FlattenedSpelling &SI : GetFlattenedSpellings(Attr: *R)) {
3974 if (SI.variety() == "CXX11" && SI.nameSpace().empty()) {
3975 unsigned RequiredArgs = 0;
3976 unsigned OptionalArgs = 0;
3977 for (const auto *Arg : R->getValueAsListOfDefs(FieldName: "Args")) {
3978 if (Arg->getValueAsBit(FieldName: "Fake"))
3979 continue;
3980
3981 if (Arg->getValueAsBit(FieldName: "Optional"))
3982 OptionalArgs++;
3983 else
3984 RequiredArgs++;
3985 }
3986 OS << ".Case(\"" << SI.getSpellingRecord().getValueAsString(FieldName: "Name")
3987 << "\","
3988 << "AttributeCommonInfo::AttrArgsInfo::"
3989 << (RequiredArgs ? "Required"
3990 : OptionalArgs ? "Optional"
3991 : "None")
3992 << ")"
3993 << "\n";
3994 }
3995 }
3996 }
3997 OS << "#endif // CXX11_ATTR_ARGS_INFO\n";
3998}
3999
4000// Emits the list of spellings for attributes.
4001void EmitClangAttrHasAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
4002 emitSourceFileHeader(Desc: "Code to implement the __has_attribute logic", OS,
4003 Record: Records);
4004
4005 // Separate all of the attributes out into four group: generic, C++11, GNU,
4006 // and declspecs. Then generate a big switch statement for each of them.
4007 using PairTy = std::pair<const Record *, FlattenedSpelling>;
4008 std::vector<PairTy> Declspec, Microsoft, GNU, Pragma, HLSLAnnotation;
4009 std::map<StringRef, std::vector<PairTy>> CXX, C23;
4010
4011 // Walk over the list of all attributes, and split them out based on the
4012 // spelling variety.
4013 for (auto *R : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
4014 for (const FlattenedSpelling &SI : GetFlattenedSpellings(Attr: *R)) {
4015 StringRef Variety = SI.variety();
4016 if (Variety == "GNU")
4017 GNU.emplace_back(args&: R, args: SI);
4018 else if (Variety == "Declspec")
4019 Declspec.emplace_back(args&: R, args: SI);
4020 else if (Variety == "Microsoft")
4021 Microsoft.emplace_back(args&: R, args: SI);
4022 else if (Variety == "CXX11")
4023 CXX[SI.nameSpace()].emplace_back(args&: R, args: SI);
4024 else if (Variety == "C23")
4025 C23[SI.nameSpace()].emplace_back(args&: R, args: SI);
4026 else if (Variety == "Pragma")
4027 Pragma.emplace_back(args&: R, args: SI);
4028 else if (Variety == "HLSLAnnotation")
4029 HLSLAnnotation.emplace_back(args&: R, args: SI);
4030 }
4031 }
4032
4033 OS << "const llvm::Triple &T = Target.getTriple();\n";
4034 OS << "switch (Syntax) {\n";
4035 OS << "case AttributeCommonInfo::Syntax::AS_GNU:\n";
4036 OS << " return llvm::StringSwitch<int>(Name)\n";
4037 GenerateHasAttrSpellingStringSwitch(Attrs: GNU, OS, Variety: "GNU");
4038 OS << "case AttributeCommonInfo::Syntax::AS_Declspec:\n";
4039 OS << " return llvm::StringSwitch<int>(Name)\n";
4040 GenerateHasAttrSpellingStringSwitch(Attrs: Declspec, OS, Variety: "Declspec");
4041 OS << "case AttributeCommonInfo::Syntax::AS_Microsoft:\n";
4042 OS << " return llvm::StringSwitch<int>(Name)\n";
4043 GenerateHasAttrSpellingStringSwitch(Attrs: Microsoft, OS, Variety: "Microsoft");
4044 OS << "case AttributeCommonInfo::Syntax::AS_Pragma:\n";
4045 OS << " return llvm::StringSwitch<int>(Name)\n";
4046 GenerateHasAttrSpellingStringSwitch(Attrs: Pragma, OS, Variety: "Pragma");
4047 OS << "case AttributeCommonInfo::Syntax::AS_HLSLAnnotation:\n";
4048 OS << " return llvm::StringSwitch<int>(Name)\n";
4049 GenerateHasAttrSpellingStringSwitch(Attrs: HLSLAnnotation, OS, Variety: "HLSLAnnotation");
4050 auto fn = [&OS](StringRef Spelling,
4051 const std::map<StringRef, std::vector<PairTy>> &Map) {
4052 OS << "case AttributeCommonInfo::Syntax::AS_" << Spelling << ": {\n";
4053 // C++11-style attributes are further split out based on the Scope.
4054 ListSeparator LS(" else ");
4055 for (const auto &[Scope, List] : Map) {
4056 OS << LS;
4057 OS << "if (ScopeName == \"" << Scope << "\") {\n";
4058 OS << " return llvm::StringSwitch<int>(Name)\n";
4059 GenerateHasAttrSpellingStringSwitch(Attrs: List, OS, Variety: Spelling, Scope);
4060 OS << "}";
4061 }
4062 OS << "\n} break;\n";
4063 };
4064 fn("CXX11", CXX);
4065 fn("C23", C23);
4066 OS << "case AttributeCommonInfo::Syntax::AS_Keyword:\n";
4067 OS << "case AttributeCommonInfo::Syntax::AS_ContextSensitiveKeyword:\n";
4068 OS << " llvm_unreachable(\"hasAttribute not supported for keyword\");\n";
4069 OS << " return 0;\n";
4070 OS << "case AttributeCommonInfo::Syntax::AS_Implicit:\n";
4071 OS << " llvm_unreachable (\"hasAttribute not supported for "
4072 "AS_Implicit\");\n";
4073 OS << " return 0;\n";
4074
4075 OS << "}\n";
4076}
4077
4078void EmitClangAttrSpellingListIndex(const RecordKeeper &Records,
4079 raw_ostream &OS) {
4080 emitSourceFileHeader(Desc: "Code to translate different attribute spellings into "
4081 "internal identifiers",
4082 OS, Record: Records);
4083
4084 OS << " switch (getParsedKind()) {\n";
4085 OS << " case IgnoredAttribute:\n";
4086 OS << " case UnknownAttribute:\n";
4087 OS << " case NoSemaHandlerAttribute:\n";
4088 OS << " llvm_unreachable(\"Ignored/unknown shouldn't get here\");\n";
4089
4090 ParsedAttrMap Attrs = getParsedAttrList(Records);
4091 for (const auto &I : Attrs) {
4092 const Record &R = *I.second;
4093 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
4094 OS << " case AT_" << I.first << ": {\n";
4095
4096 // If there are none or one spelling to check, resort to the default
4097 // behavior of returning index as 0.
4098 if (Spellings.size() <= 1) {
4099 OS << " return 0;\n"
4100 << " break;\n"
4101 << " }\n";
4102 continue;
4103 }
4104
4105 std::vector<StringRef> Names;
4106 llvm::transform(Range&: Spellings, d_first: std::back_inserter(x&: Names),
4107 F: [](const FlattenedSpelling &FS) { return FS.name(); });
4108 llvm::sort(C&: Names);
4109 Names.erase(first: llvm::unique(R&: Names), last: Names.end());
4110
4111 for (const auto &[Idx, FS] : enumerate(First&: Spellings)) {
4112 OS << " if (";
4113 if (Names.size() > 1) {
4114 SmallVector<StringRef, 6> SameLenNames;
4115 StringRef FSName = FS.name();
4116 llvm::copy_if(
4117 Range&: Names, Out: std::back_inserter(x&: SameLenNames),
4118 P: [&](StringRef N) { return N.size() == FSName.size(); });
4119
4120 if (SameLenNames.size() == 1) {
4121 OS << "Name.size() == " << FS.name().size() << " && ";
4122 } else {
4123 // FIXME: We currently fall back to comparing entire strings if there
4124 // are 2 or more spelling names with the same length. This can be
4125 // optimized to check only for the the first differing character
4126 // between them instead.
4127 OS << "Name == \"" << FS.name() << "\""
4128 << " && ";
4129 }
4130 }
4131
4132 OS << "getSyntax() == AttributeCommonInfo::AS_" << FS.variety()
4133 << " && ComputedScope == ";
4134 if (FS.nameSpace() == "")
4135 OS << "AttributeCommonInfo::Scope::NONE";
4136 else
4137 OS << "AttributeCommonInfo::Scope::" + FS.nameSpace().upper();
4138
4139 OS << ")\n"
4140 << " return " << Idx << ";\n";
4141 }
4142
4143 OS << " break;\n"
4144 << " }\n";
4145 }
4146
4147 OS << " }\n"
4148 << " return 0;\n";
4149}
4150
4151// Emits code used by RecursiveASTVisitor to visit attributes
4152void EmitClangAttrASTVisitor(const RecordKeeper &Records, raw_ostream &OS) {
4153 emitSourceFileHeader(Desc: "Used by RecursiveASTVisitor to visit attributes.", OS,
4154 Record: Records);
4155 // Write method declarations for Traverse* methods.
4156 // We emit this here because we only generate methods for attributes that
4157 // are declared as ASTNodes.
4158 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n";
4159 ArrayRef<const Record *> Attrs = Records.getAllDerivedDefinitions(ClassName: "Attr");
4160 for (const auto *Attr : Attrs) {
4161 const Record &R = *Attr;
4162 if (!R.getValueAsBit(FieldName: "ASTNode"))
4163 continue;
4164 OS << " bool Traverse"
4165 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n";
4166 OS << " bool Visit"
4167 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
4168 << " return true; \n"
4169 << " }\n";
4170 }
4171 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n";
4172
4173 // Write individual Traverse* methods for each attribute class.
4174 for (const auto *Attr : Attrs) {
4175 const Record &R = *Attr;
4176 if (!R.getValueAsBit(FieldName: "ASTNode"))
4177 continue;
4178
4179 OS << "template <typename Derived>\n"
4180 << "bool VISITORCLASS<Derived>::Traverse"
4181 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n"
4182 << " if (!getDerived().VisitAttr(A))\n"
4183 << " return false;\n"
4184 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n"
4185 << " return false;\n";
4186
4187 for (const auto *Arg : R.getValueAsListOfDefs(FieldName: "Args"))
4188 createArgument(Arg: *Arg, Attr: R.getName())->writeASTVisitorTraversal(OS);
4189
4190 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
4191 VariadicExprArgument("DelayedArgs", R.getName())
4192 .writeASTVisitorTraversal(OS);
4193
4194 OS << " return true;\n";
4195 OS << "}\n\n";
4196 }
4197
4198 // Write generic Traverse routine
4199 OS << "template <typename Derived>\n"
4200 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n"
4201 << " if (!A)\n"
4202 << " return true;\n"
4203 << "\n"
4204 << " switch (A->getKind()) {\n";
4205
4206 for (const auto *Attr : Attrs) {
4207 const Record &R = *Attr;
4208 if (!R.getValueAsBit(FieldName: "ASTNode"))
4209 continue;
4210
4211 OS << " case attr::" << R.getName() << ":\n"
4212 << " return getDerived().Traverse" << R.getName() << "Attr("
4213 << "cast<" << R.getName() << "Attr>(A));\n";
4214 }
4215 OS << " }\n"; // end switch
4216 OS << " llvm_unreachable(\"bad attribute kind\");\n";
4217 OS << "}\n"; // end function
4218 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n";
4219}
4220
4221static void
4222EmitClangAttrTemplateInstantiateHelper(ArrayRef<const Record *> Attrs,
4223 raw_ostream &OS, bool AppliesToDecl) {
4224
4225 OS << " switch (At->getKind()) {\n";
4226 for (const auto *Attr : Attrs) {
4227 const Record &R = *Attr;
4228 if (!R.getValueAsBit(FieldName: "ASTNode"))
4229 continue;
4230 OS << " case attr::" << R.getName() << ": {\n";
4231 bool ShouldClone = R.getValueAsBit(FieldName: "Clone") &&
4232 (!AppliesToDecl ||
4233 R.getValueAsBit(FieldName: "MeaningfulToClassTemplateDefinition"));
4234
4235 if (!ShouldClone) {
4236 OS << " return nullptr;\n";
4237 OS << " }\n";
4238 continue;
4239 }
4240
4241 OS << " const auto *A = cast<"
4242 << R.getName() << "Attr>(At);\n";
4243 bool TDependent = R.getValueAsBit(FieldName: "TemplateDependent");
4244
4245 if (!TDependent) {
4246 OS << " return A->clone(C);\n";
4247 OS << " }\n";
4248 continue;
4249 }
4250
4251 std::vector<const Record *> ArgRecords = R.getValueAsListOfDefs(FieldName: "Args");
4252 std::vector<std::unique_ptr<Argument>> Args;
4253 Args.reserve(n: ArgRecords.size());
4254
4255 for (const auto *ArgRecord : ArgRecords)
4256 Args.emplace_back(args: createArgument(Arg: *ArgRecord, Attr: R.getName()));
4257
4258 for (auto const &ai : Args)
4259 ai->writeTemplateInstantiation(OS);
4260
4261 OS << " return new (C) " << R.getName() << "Attr(C, *A";
4262 for (auto const &ai : Args) {
4263 OS << ", ";
4264 ai->writeTemplateInstantiationArgs(OS);
4265 }
4266 OS << ");\n"
4267 << " }\n";
4268 }
4269 OS << " } // end switch\n"
4270 << " llvm_unreachable(\"Unknown attribute!\");\n"
4271 << " return nullptr;\n";
4272}
4273
4274// Emits code to instantiate dependent attributes on templates.
4275void EmitClangAttrTemplateInstantiate(const RecordKeeper &Records,
4276 raw_ostream &OS) {
4277 emitSourceFileHeader(Desc: "Template instantiation code for attributes", OS,
4278 Record: Records);
4279
4280 ArrayRef<const Record *> Attrs = Records.getAllDerivedDefinitions(ClassName: "Attr");
4281
4282 OS << "namespace clang {\n"
4283 << "namespace sema {\n\n"
4284 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, "
4285 << "Sema &S,\n"
4286 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4287 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/false);
4288 OS << "}\n\n"
4289 << "Attr *instantiateTemplateAttributeForDecl(const Attr *At,\n"
4290 << " ASTContext &C, Sema &S,\n"
4291 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n";
4292 EmitClangAttrTemplateInstantiateHelper(Attrs, OS, /*AppliesToDecl*/true);
4293 OS << "}\n\n"
4294 << "} // end namespace sema\n"
4295 << "} // end namespace clang\n";
4296}
4297
4298// Emits the list of parsed attributes.
4299void EmitClangAttrParsedAttrList(const RecordKeeper &Records, raw_ostream &OS) {
4300 emitSourceFileHeader(Desc: "List of all attributes that Clang recognizes", OS,
4301 Record: Records);
4302
4303 OS << "#ifndef PARSED_ATTR\n";
4304 OS << "#define PARSED_ATTR(NAME) NAME\n";
4305 OS << "#endif\n\n";
4306
4307 ParsedAttrMap Names = getParsedAttrList(Records);
4308 for (const auto &I : Names) {
4309 OS << "PARSED_ATTR(" << I.first << ")\n";
4310 }
4311}
4312
4313void EmitAttributeSpellingList(const RecordKeeper &Records, raw_ostream &OS) {
4314 emitSourceFileHeader(Desc: "List of attribute names", OS, Record: Records);
4315
4316 std::set<StringRef> AttrSpellingList;
4317 std::set<StringRef> AttrScopeSpellingList;
4318
4319 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
4320 for (const auto &S : GetFlattenedSpellings(Attr: *A)) {
4321 AttrSpellingList.insert(x: S.name());
4322 if (S.nameSpace().size())
4323 AttrScopeSpellingList.insert(x: S.nameSpace());
4324 }
4325 }
4326
4327 OS << "#ifndef ATTR_NAME" << "\n";
4328 OS << "#define ATTR_NAME(NAME) NAME" << "\n";
4329 OS << "#endif" << "\n" << "\n";
4330 for (const auto &AttrName : AttrSpellingList) {
4331 OS << "ATTR_NAME(\"" << AttrName << "\")\n";
4332 }
4333 OS << "\n";
4334 OS << "#undef ATTR_NAME" << "\n";
4335 OS << "\n";
4336
4337 OS << "#ifndef ATTR_SCOPE_NAME" << "\n";
4338 OS << "#define ATTR_SCOPE_NAME(SCOPE_NAME) SCOPE_NAME" << "\n";
4339 OS << "#endif" << "\n" << "\n";
4340 for (const auto &AttrScopeName : AttrScopeSpellingList) {
4341 OS << "ATTR_SCOPE_NAME(\"" << AttrScopeName << "\")\n";
4342 }
4343 OS << "\n";
4344 OS << "#undef ATTR_SCOPE_NAME" << "\n";
4345 OS << "\n";
4346}
4347
4348static bool isArgVariadic(const Record &R, StringRef AttrName) {
4349 return createArgument(Arg: R, Attr: AttrName)->isVariadic();
4350}
4351
4352static void emitArgInfo(const Record &R, raw_ostream &OS) {
4353 // This function will count the number of arguments specified for the
4354 // attribute and emit the number of required arguments followed by the
4355 // number of optional arguments.
4356 unsigned ArgCount = 0, OptCount = 0, ArgMemberCount = 0;
4357 bool HasVariadic = false;
4358 for (const auto *Arg : R.getValueAsListOfDefs(FieldName: "Args")) {
4359 // If the arg is fake, it's the user's job to supply it: general parsing
4360 // logic shouldn't need to know anything about it.
4361 if (Arg->getValueAsBit(FieldName: "Fake"))
4362 continue;
4363 Arg->getValueAsBit(FieldName: "Optional") ? ++OptCount : ++ArgCount;
4364 ++ArgMemberCount;
4365 if (!HasVariadic && isArgVariadic(R: *Arg, AttrName: R.getName()))
4366 HasVariadic = true;
4367 }
4368
4369 // If there is a variadic argument, we will set the optional argument count
4370 // to its largest value. Since it's currently a 4-bit number, we set it to 15.
4371 OS << " /*NumArgs=*/" << ArgCount << ",\n";
4372 OS << " /*OptArgs=*/" << (HasVariadic ? 15 : OptCount) << ",\n";
4373 OS << " /*NumArgMembers=*/" << ArgMemberCount << ",\n";
4374}
4375
4376static std::string GetDiagnosticSpelling(const Record &R) {
4377 StringRef Ret = R.getValueAsString(FieldName: "DiagSpelling");
4378 if (!Ret.empty())
4379 return Ret.str();
4380
4381 // If we couldn't find the DiagSpelling in this object, we can check to see
4382 // if the object is one that has a base, and if it is, loop up to the Base
4383 // member recursively.
4384 if (auto Base = R.getValueAsOptionalDef(BaseFieldName))
4385 return GetDiagnosticSpelling(R: *Base);
4386
4387 return "";
4388}
4389
4390static std::string CalculateDiagnostic(const Record &S) {
4391 // If the SubjectList object has a custom diagnostic associated with it,
4392 // return that directly.
4393 const StringRef CustomDiag = S.getValueAsString(FieldName: "CustomDiag");
4394 if (!CustomDiag.empty())
4395 return ("\"" + Twine(CustomDiag) + "\"").str();
4396
4397 std::vector<std::string> DiagList;
4398 for (const auto *Subject : S.getValueAsListOfDefs(FieldName: "Subjects")) {
4399 const Record &R = *Subject;
4400 // Get the diagnostic text from the Decl or Stmt node given.
4401 std::string V = GetDiagnosticSpelling(R);
4402 if (V.empty()) {
4403 PrintError(ErrorLoc: R.getLoc(),
4404 Msg: "Could not determine diagnostic spelling for the node: " +
4405 R.getName() + "; please add one to DeclNodes.td");
4406 } else {
4407 // The node may contain a list of elements itself, so split the elements
4408 // by a comma, and trim any whitespace.
4409 SmallVector<StringRef, 2> Frags;
4410 SplitString(Source: V, OutFragments&: Frags, Delimiters: ",");
4411 for (auto Str : Frags) {
4412 DiagList.push_back(x: Str.trim().str());
4413 }
4414 }
4415 }
4416
4417 if (DiagList.empty()) {
4418 PrintFatalError(ErrorLoc: S.getLoc(),
4419 Msg: "Could not deduce diagnostic argument for Attr subjects");
4420 return "";
4421 }
4422
4423 // FIXME: this is not particularly good for localization purposes and ideally
4424 // should be part of the diagnostics engine itself with some sort of list
4425 // specifier.
4426
4427 // A single member of the list can be returned directly.
4428 if (DiagList.size() == 1)
4429 return '"' + DiagList.front() + '"';
4430
4431 if (DiagList.size() == 2)
4432 return '"' + DiagList[0] + " and " + DiagList[1] + '"';
4433
4434 // If there are more than two in the list, we serialize the first N - 1
4435 // elements with a comma. This leaves the string in the state: foo, bar,
4436 // baz (but misses quux). We can then add ", and " for the last element
4437 // manually.
4438 std::string Diag = join(Begin: DiagList.begin(), End: DiagList.end() - 1, Separator: ", ");
4439 return '"' + Diag + ", and " + *(DiagList.end() - 1) + '"';
4440}
4441
4442static std::string GetSubjectWithSuffix(const Record *R) {
4443 const std::string B = R->getName().str();
4444 if (B == "DeclBase")
4445 return "Decl";
4446 return B + "Decl";
4447}
4448
4449static std::string functionNameForCustomAppertainsTo(const Record &Subject) {
4450 return "is" + Subject.getName().str();
4451}
4452
4453static void GenerateCustomAppertainsTo(const Record &Subject, raw_ostream &OS) {
4454 std::string FnName = functionNameForCustomAppertainsTo(Subject);
4455
4456 // If this code has already been generated, we don't need to do anything.
4457 static std::set<std::string> CustomSubjectSet;
4458 auto I = CustomSubjectSet.find(x: FnName);
4459 if (I != CustomSubjectSet.end())
4460 return;
4461
4462 // This only works with non-root Decls.
4463 const Record *Base = Subject.getValueAsDef(BaseFieldName);
4464
4465 // Not currently support custom subjects within custom subjects.
4466 if (Base->isSubClassOf(Name: "SubsetSubject")) {
4467 PrintFatalError(ErrorLoc: Subject.getLoc(),
4468 Msg: "SubsetSubjects within SubsetSubjects is not supported");
4469 return;
4470 }
4471
4472 OS << "static bool " << FnName << "(const Decl *D) {\n";
4473 OS << " if (const auto *S = dyn_cast<";
4474 OS << GetSubjectWithSuffix(R: Base);
4475 OS << ">(D))\n";
4476 OS << " return " << Subject.getValueAsString(FieldName: "CheckCode") << ";\n";
4477 OS << " return false;\n";
4478 OS << "}\n\n";
4479
4480 CustomSubjectSet.insert(x: FnName);
4481}
4482
4483static void GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) {
4484 // If the attribute does not contain a Subjects definition, then use the
4485 // default appertainsTo logic.
4486 if (Attr.isValueUnset(FieldName: "Subjects"))
4487 return;
4488
4489 const Record *SubjectObj = Attr.getValueAsDef(FieldName: "Subjects");
4490 std::vector<const Record *> Subjects =
4491 SubjectObj->getValueAsListOfDefs(FieldName: "Subjects");
4492
4493 // If the list of subjects is empty, it is assumed that the attribute
4494 // appertains to everything.
4495 if (Subjects.empty())
4496 return;
4497
4498 bool Warn = SubjectObj->getValueAsDef(FieldName: "Diag")->getValueAsBit(FieldName: "Warn");
4499
4500 // Split the subjects into declaration subjects and statement subjects.
4501 // FIXME: subset subjects are added to the declaration list until there are
4502 // enough statement attributes with custom subject needs to warrant
4503 // the implementation effort.
4504 std::vector<const Record *> DeclSubjects, StmtSubjects;
4505 copy_if(Range&: Subjects, Out: std::back_inserter(x&: DeclSubjects), P: [](const Record *R) {
4506 return R->isSubClassOf(Name: "SubsetSubject") || !R->isSubClassOf(Name: "StmtNode");
4507 });
4508 copy_if(Range&: Subjects, Out: std::back_inserter(x&: StmtSubjects),
4509 P: [](const Record *R) { return R->isSubClassOf(Name: "StmtNode"); });
4510
4511 // We should have sorted all of the subjects into two lists.
4512 // FIXME: this assertion will be wrong if we ever add type attribute subjects.
4513 assert(DeclSubjects.size() + StmtSubjects.size() == Subjects.size());
4514
4515 if (DeclSubjects.empty()) {
4516 // If there are no decl subjects but there are stmt subjects, diagnose
4517 // trying to apply a statement attribute to a declaration.
4518 if (!StmtSubjects.empty()) {
4519 OS << "bool diagAppertainsToDecl(Sema &S, const ParsedAttr &AL, ";
4520 OS << "const Decl *D) const override {\n";
4521 OS << " S.Diag(AL.getLoc(), diag::err_attribute_invalid_on_decl)\n";
4522 OS << " << AL << AL.isRegularKeywordAttribute() << "
4523 "D->getLocation();\n";
4524 OS << " return false;\n";
4525 OS << "}\n\n";
4526 }
4527 } else {
4528 // Otherwise, generate an appertainsTo check specific to this attribute
4529 // which checks all of the given subjects against the Decl passed in.
4530 OS << "bool diagAppertainsToDecl(Sema &S, ";
4531 OS << "const ParsedAttr &Attr, const Decl *D) const override {\n";
4532 OS << " if (";
4533 for (auto I = DeclSubjects.begin(), E = DeclSubjects.end(); I != E; ++I) {
4534 // If the subject has custom code associated with it, use the generated
4535 // function for it. The function cannot be inlined into this check (yet)
4536 // because it requires the subject to be of a specific type, and were that
4537 // information inlined here, it would not support an attribute with
4538 // multiple custom subjects.
4539 if ((*I)->isSubClassOf(Name: "SubsetSubject"))
4540 OS << "!" << functionNameForCustomAppertainsTo(Subject: **I) << "(D)";
4541 else
4542 OS << "!isa<" << GetSubjectWithSuffix(R: *I) << ">(D)";
4543
4544 if (I + 1 != E)
4545 OS << " && ";
4546 }
4547 OS << ") {\n";
4548 OS << " S.Diag(Attr.getLoc(), diag::";
4549 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4550 : "err_attribute_wrong_decl_type_str");
4551 OS << ")\n";
4552 OS << " << Attr << Attr.isRegularKeywordAttribute() << ";
4553 OS << CalculateDiagnostic(S: *SubjectObj) << ";\n";
4554 OS << " return false;\n";
4555 OS << " }\n";
4556 OS << " return true;\n";
4557 OS << "}\n\n";
4558 }
4559
4560 if (StmtSubjects.empty()) {
4561 // If there are no stmt subjects but there are decl subjects, diagnose
4562 // trying to apply a declaration attribute to a statement.
4563 if (!DeclSubjects.empty()) {
4564 OS << "bool diagAppertainsToStmt(Sema &S, const ParsedAttr &AL, ";
4565 OS << "const Stmt *St) const override {\n";
4566 OS << " S.Diag(AL.getLoc(), diag::err_decl_attribute_invalid_on_stmt)\n";
4567 OS << " << AL << AL.isRegularKeywordAttribute() << "
4568 "St->getBeginLoc();\n";
4569 OS << " return false;\n";
4570 OS << "}\n\n";
4571 }
4572 } else {
4573 // Now, do the same for statements.
4574 OS << "bool diagAppertainsToStmt(Sema &S, ";
4575 OS << "const ParsedAttr &Attr, const Stmt *St) const override {\n";
4576 OS << " if (";
4577 for (auto I = StmtSubjects.begin(), E = StmtSubjects.end(); I != E; ++I) {
4578 OS << "!isa<" << (*I)->getName() << ">(St)";
4579 if (I + 1 != E)
4580 OS << " && ";
4581 }
4582 OS << ") {\n";
4583 OS << " S.Diag(Attr.getLoc(), diag::";
4584 OS << (Warn ? "warn_attribute_wrong_decl_type_str"
4585 : "err_attribute_wrong_decl_type_str");
4586 OS << ")\n";
4587 OS << " << Attr << Attr.isRegularKeywordAttribute() << ";
4588 OS << CalculateDiagnostic(S: *SubjectObj) << ";\n";
4589 OS << " return false;\n";
4590 OS << " }\n";
4591 OS << " return true;\n";
4592 OS << "}\n\n";
4593 }
4594}
4595
4596// Generates the mutual exclusion checks. The checks for parsed attributes are
4597// written into OS and the checks for merging declaration attributes are
4598// written into MergeOS.
4599static void GenerateMutualExclusionsChecks(const Record &Attr,
4600 const RecordKeeper &Records,
4601 raw_ostream &OS,
4602 raw_ostream &MergeDeclOS,
4603 raw_ostream &MergeStmtOS) {
4604 // We don't do any of this magic for type attributes yet.
4605 if (Attr.isSubClassOf(Name: "TypeAttr"))
4606 return;
4607
4608 // This means the attribute is either a statement attribute, a decl
4609 // attribute, or both; find out which.
4610 bool CurAttrIsStmtAttr = Attr.isSubClassOf(Name: "StmtAttr") ||
4611 Attr.isSubClassOf(Name: "DeclOrStmtAttr") ||
4612 Attr.isSubClassOf(Name: "InheritableParamOrStmtAttr");
4613 bool CurAttrIsDeclAttr = !CurAttrIsStmtAttr ||
4614 Attr.isSubClassOf(Name: "DeclOrStmtAttr") ||
4615 Attr.isSubClassOf(Name: "InheritableParamOrStmtAttr");
4616
4617 std::vector<std::string> DeclAttrs, StmtAttrs;
4618
4619 // Find all of the definitions that inherit from MutualExclusions and include
4620 // the given attribute in the list of exclusions to generate the
4621 // diagMutualExclusion() check.
4622 for (const Record *Exclusion :
4623 Records.getAllDerivedDefinitions(ClassName: "MutualExclusions")) {
4624 std::vector<const Record *> MutuallyExclusiveAttrs =
4625 Exclusion->getValueAsListOfDefs(FieldName: "Exclusions");
4626 auto IsCurAttr = [Attr](const Record *R) {
4627 return R->getName() == Attr.getName();
4628 };
4629 if (any_of(Range&: MutuallyExclusiveAttrs, P: IsCurAttr)) {
4630 // This list of exclusions includes the attribute we're looking for, so
4631 // add the exclusive attributes to the proper list for checking.
4632 for (const Record *AttrToExclude : MutuallyExclusiveAttrs) {
4633 if (IsCurAttr(AttrToExclude))
4634 continue;
4635
4636 if (CurAttrIsStmtAttr)
4637 StmtAttrs.push_back(x: (AttrToExclude->getName() + "Attr").str());
4638 if (CurAttrIsDeclAttr)
4639 DeclAttrs.push_back(x: (AttrToExclude->getName() + "Attr").str());
4640 }
4641 }
4642 }
4643
4644 // If there are any decl or stmt attributes, silence -Woverloaded-virtual
4645 // warnings for them both.
4646 if (!DeclAttrs.empty() || !StmtAttrs.empty())
4647 OS << " using ParsedAttrInfo::diagMutualExclusion;\n\n";
4648
4649 // If we discovered any decl or stmt attributes to test for, generate the
4650 // predicates for them now.
4651 if (!DeclAttrs.empty()) {
4652 // Generate the ParsedAttrInfo subclass logic for declarations.
4653 OS << " bool diagMutualExclusion(Sema &S, const ParsedAttr &AL, "
4654 << "const Decl *D) const override {\n";
4655 for (const std::string &A : DeclAttrs) {
4656 OS << " if (const auto *A = D->getAttr<" << A << ">()) {\n";
4657 OS << " S.Diag(AL.getLoc(), diag::err_attributes_are_not_compatible)"
4658 << " << AL << A << (AL.isRegularKeywordAttribute() ||"
4659 << " A->isRegularKeywordAttribute());\n";
4660 OS << " S.Diag(A->getLocation(), diag::note_conflicting_attribute);";
4661 OS << " \nreturn false;\n";
4662 OS << " }\n";
4663 }
4664 OS << " return true;\n";
4665 OS << " }\n\n";
4666
4667 // Also generate the declaration attribute merging logic if the current
4668 // attribute is one that can be inheritted on a declaration. It is assumed
4669 // this code will be executed in the context of a function with parameters:
4670 // Sema &S, Decl *D, Attr *A and that returns a bool (false on diagnostic,
4671 // true on success).
4672 if (Attr.isSubClassOf(Name: "InheritableAttr")) {
4673 MergeDeclOS << " if (const auto *Second = dyn_cast<"
4674 << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4675 for (const std::string &A : DeclAttrs) {
4676 MergeDeclOS << " if (const auto *First = D->getAttr<" << A
4677 << ">()) {\n";
4678 MergeDeclOS << " S.Diag(First->getLocation(), "
4679 << "diag::err_attributes_are_not_compatible) << First << "
4680 << "Second << (First->isRegularKeywordAttribute() || "
4681 << "Second->isRegularKeywordAttribute());\n";
4682 MergeDeclOS << " S.Diag(Second->getLocation(), "
4683 << "diag::note_conflicting_attribute);\n";
4684 MergeDeclOS << " return false;\n";
4685 MergeDeclOS << " }\n";
4686 }
4687 MergeDeclOS << " return true;\n";
4688 MergeDeclOS << " }\n";
4689 }
4690 }
4691
4692 // Statement attributes are a bit different from declarations. With
4693 // declarations, each attribute is added to the declaration as it is
4694 // processed, and so you can look on the Decl * itself to see if there is a
4695 // conflicting attribute. Statement attributes are processed as a group
4696 // because AttributedStmt needs to tail-allocate all of the attribute nodes
4697 // at once. This means we cannot check whether the statement already contains
4698 // an attribute to check for the conflict. Instead, we need to check whether
4699 // the given list of semantic attributes contain any conflicts. It is assumed
4700 // this code will be executed in the context of a function with parameters:
4701 // Sema &S, const SmallVectorImpl<const Attr *> &C. The code will be within a
4702 // loop which loops over the container C with a loop variable named A to
4703 // represent the current attribute to check for conflicts.
4704 //
4705 // FIXME: it would be nice not to walk over the list of potential attributes
4706 // to apply to the statement more than once, but statements typically don't
4707 // have long lists of attributes on them, so re-walking the list should not
4708 // be an expensive operation.
4709 if (!StmtAttrs.empty()) {
4710 MergeStmtOS << " if (const auto *Second = dyn_cast<"
4711 << (Attr.getName() + "Attr").str() << ">(A)) {\n";
4712 MergeStmtOS << " auto Iter = llvm::find_if(C, [](const Attr *Check) "
4713 << "{ return isa<";
4714 interleave(
4715 c: StmtAttrs, each_fn: [&](StringRef Name) { MergeStmtOS << Name; },
4716 between_fn: [&] { MergeStmtOS << ", "; });
4717 MergeStmtOS << ">(Check); });\n";
4718 MergeStmtOS << " if (Iter != C.end()) {\n";
4719 MergeStmtOS << " S.Diag((*Iter)->getLocation(), "
4720 << "diag::err_attributes_are_not_compatible) << *Iter << "
4721 << "Second << ((*Iter)->isRegularKeywordAttribute() || "
4722 << "Second->isRegularKeywordAttribute());\n";
4723 MergeStmtOS << " S.Diag(Second->getLocation(), "
4724 << "diag::note_conflicting_attribute);\n";
4725 MergeStmtOS << " return false;\n";
4726 MergeStmtOS << " }\n";
4727 MergeStmtOS << " }\n";
4728 }
4729}
4730
4731static void
4732emitAttributeMatchRules(PragmaClangAttributeSupport &PragmaAttributeSupport,
4733 raw_ostream &OS) {
4734 OS << "static bool checkAttributeMatchRuleAppliesTo(const Decl *D, "
4735 << AttributeSubjectMatchRule::EnumName << " rule) {\n";
4736 OS << " switch (rule) {\n";
4737 for (const auto &Rule : PragmaAttributeSupport.Rules) {
4738 if (Rule.isAbstractRule()) {
4739 OS << " case " << Rule.getEnumValue() << ":\n";
4740 OS << " assert(false && \"Abstract matcher rule isn't allowed\");\n";
4741 OS << " return false;\n";
4742 continue;
4743 }
4744 std::vector<const Record *> Subjects = Rule.getSubjects();
4745 assert(!Subjects.empty() && "Missing subjects");
4746 OS << " case " << Rule.getEnumValue() << ":\n";
4747 OS << " return ";
4748 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) {
4749 // If the subject has custom code associated with it, use the function
4750 // that was generated for GenerateAppertainsTo to check if the declaration
4751 // is valid.
4752 if ((*I)->isSubClassOf(Name: "SubsetSubject"))
4753 OS << functionNameForCustomAppertainsTo(Subject: **I) << "(D)";
4754 else
4755 OS << "isa<" << GetSubjectWithSuffix(R: *I) << ">(D)";
4756
4757 if (I + 1 != E)
4758 OS << " || ";
4759 }
4760 OS << ";\n";
4761 }
4762 OS << " }\n";
4763 OS << " llvm_unreachable(\"Invalid match rule\");\nreturn false;\n";
4764 OS << "}\n\n";
4765}
4766
4767static void GenerateLangOptRequirements(const Record &R,
4768 raw_ostream &OS) {
4769 // If the attribute has an empty or unset list of language requirements,
4770 // use the default handler.
4771 std::vector<const Record *> LangOpts = R.getValueAsListOfDefs(FieldName: "LangOpts");
4772 if (LangOpts.empty())
4773 return;
4774
4775 OS << "bool acceptsLangOpts(const LangOptions &LangOpts) const override {\n";
4776 OS << " return " << GenerateTestExpression(LangOpts) << ";\n";
4777 OS << "}\n\n";
4778}
4779
4780static void GenerateTargetRequirements(const Record &Attr,
4781 const ParsedAttrMap &Dupes,
4782 raw_ostream &OS) {
4783 // If the attribute is not a target specific attribute, use the default
4784 // target handler.
4785 if (!Attr.isSubClassOf(Name: "TargetSpecificAttr"))
4786 return;
4787
4788 // Get the list of architectures to be tested for.
4789 const Record *R = Attr.getValueAsDef(FieldName: "Target");
4790 std::vector<StringRef> Arches = R->getValueAsListOfStrings(FieldName: "Arches");
4791
4792 // If there are other attributes which share the same parsed attribute kind,
4793 // such as target-specific attributes with a shared spelling, collapse the
4794 // duplicate architectures. This is required because a shared target-specific
4795 // attribute has only one ParsedAttr::Kind enumeration value, but it
4796 // applies to multiple target architectures. In order for the attribute to be
4797 // considered valid, all of its architectures need to be included.
4798 if (!Attr.isValueUnset(FieldName: "ParseKind")) {
4799 const StringRef APK = Attr.getValueAsString(FieldName: "ParseKind");
4800 for (const auto &I : Dupes) {
4801 if (I.first == APK) {
4802 std::vector<StringRef> DA =
4803 I.second->getValueAsDef(FieldName: "Target")->getValueAsListOfStrings(
4804 FieldName: "Arches");
4805 llvm::append_range(C&: Arches, R&: DA);
4806 }
4807 }
4808 }
4809
4810 std::string FnName = "isTarget";
4811 std::string Test;
4812 bool UsesT = GenerateTargetSpecificAttrChecks(R, Arches, Test, FnName: &FnName);
4813
4814 OS << "bool existsInTarget(const TargetInfo &Target) const override {\n";
4815 if (UsesT)
4816 OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4817 OS << " return " << Test << ";\n";
4818 OS << "}\n\n";
4819}
4820
4821static void
4822GenerateSpellingTargetRequirements(const Record &Attr,
4823 ArrayRef<const Record *> TargetSpellings,
4824 raw_ostream &OS) {
4825 // If there are no target specific spellings, use the default target handler.
4826 if (TargetSpellings.empty())
4827 return;
4828
4829 std::string Test;
4830 bool UsesT = false;
4831 const std::vector<FlattenedSpelling> SpellingList =
4832 GetFlattenedSpellings(Attr);
4833 for (unsigned TargetIndex = 0; TargetIndex < TargetSpellings.size();
4834 ++TargetIndex) {
4835 const auto &TargetSpelling = TargetSpellings[TargetIndex];
4836 std::vector<FlattenedSpelling> Spellings =
4837 GetFlattenedSpellings(Attr: *TargetSpelling);
4838
4839 Test += "((SpellingListIndex == ";
4840 for (unsigned Index = 0; Index < Spellings.size(); ++Index) {
4841 Test += itostr(X: getSpellingListIndex(SpellingList, Spelling: Spellings[Index]));
4842 if (Index != Spellings.size() - 1)
4843 Test += " ||\n SpellingListIndex == ";
4844 else
4845 Test += ") && ";
4846 }
4847
4848 const Record *Target = TargetSpelling->getValueAsDef(FieldName: "Target");
4849 std::vector<StringRef> Arches = Target->getValueAsListOfStrings(FieldName: "Arches");
4850 std::string FnName = "isTargetSpelling";
4851 UsesT |= GenerateTargetSpecificAttrChecks(R: Target, Arches, Test, FnName: &FnName);
4852 Test += ")";
4853 if (TargetIndex != TargetSpellings.size() - 1)
4854 Test += " || ";
4855 }
4856
4857 OS << "bool spellingExistsInTarget(const TargetInfo &Target,\n";
4858 OS << " const unsigned SpellingListIndex) const "
4859 "override {\n";
4860 if (UsesT)
4861 OS << " const llvm::Triple &T = Target.getTriple(); (void)T;\n";
4862 OS << " return " << Test << ";\n", OS << "}\n\n";
4863}
4864
4865static void GenerateSpellingIndexToSemanticSpelling(const Record &Attr,
4866 raw_ostream &OS) {
4867 // If the attribute does not have a semantic form, we can bail out early.
4868 if (!Attr.getValueAsBit(FieldName: "ASTNode"))
4869 return;
4870
4871 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
4872
4873 // If there are zero or one spellings, or all of the spellings share the same
4874 // name, we can also bail out early.
4875 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings))
4876 return;
4877
4878 // Generate the enumeration we will use for the mapping.
4879 SemanticSpellingMap SemanticToSyntacticMap;
4880 std::string Enum = CreateSemanticSpellings(Spellings, Map&: SemanticToSyntacticMap);
4881
4882 OS << "unsigned spellingIndexToSemanticSpelling(";
4883 OS << "const ParsedAttr &Attr) const override {\n";
4884 OS << Enum;
4885 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n";
4886 WriteSemanticSpellingSwitch(VarName: "Idx", Map: SemanticToSyntacticMap, OS);
4887 OS << "}\n\n";
4888}
4889
4890static void GenerateHandleDeclAttribute(const Record &Attr, raw_ostream &OS) {
4891 // Only generate if Attr can be handled simply.
4892 if (!Attr.getValueAsBit(FieldName: "SimpleHandler"))
4893 return;
4894
4895 // Generate a function which just converts from ParsedAttr to the Attr type.
4896 OS << "AttrHandling handleDeclAttribute(Sema &S, Decl *D,";
4897 OS << "const ParsedAttr &Attr) const override {\n";
4898 OS << " D->addAttr(::new (S.Context) " << Attr.getName();
4899 OS << "Attr(S.Context, Attr));\n";
4900 OS << " return AttributeApplied;\n";
4901 OS << "}\n\n";
4902}
4903
4904static bool isParamExpr(const Record *Arg) {
4905 return !Arg->getDirectSuperClasses().empty() &&
4906 StringSwitch<bool>(
4907 Arg->getDirectSuperClasses().back().first->getName())
4908 .Case(S: "ExprArgument", Value: true)
4909 .Case(S: "VariadicExprArgument", Value: true)
4910 .Default(Value: false);
4911}
4912
4913static void GenerateIsParamExpr(const Record &Attr, raw_ostream &OS) {
4914 OS << "bool isParamExpr(size_t N) const override {\n";
4915 OS << " return ";
4916 auto Args = Attr.getValueAsListOfDefs(FieldName: "Args");
4917 for (size_t I = 0; I < Args.size(); ++I)
4918 if (isParamExpr(Arg: Args[I]))
4919 OS << "(N == " << I << ") || ";
4920 OS << "false;\n";
4921 OS << "}\n\n";
4922}
4923
4924static void GenerateHandleAttrWithDelayedArgs(const RecordKeeper &Records,
4925 raw_ostream &OS) {
4926 OS << "static void handleAttrWithDelayedArgs(Sema &S, Decl *D, ";
4927 OS << "const ParsedAttr &Attr) {\n";
4928 OS << " SmallVector<Expr *, 4> ArgExprs;\n";
4929 OS << " ArgExprs.reserve(Attr.getNumArgs());\n";
4930 OS << " for (unsigned I = 0; I < Attr.getNumArgs(); ++I) {\n";
4931 OS << " assert(!Attr.isArgIdent(I));\n";
4932 OS << " ArgExprs.push_back(Attr.getArgAsExpr(I));\n";
4933 OS << " }\n";
4934 OS << " clang::Attr *CreatedAttr = nullptr;\n";
4935 OS << " switch (Attr.getKind()) {\n";
4936 OS << " default:\n";
4937 OS << " llvm_unreachable(\"Attribute cannot hold delayed arguments.\");\n";
4938 ParsedAttrMap Attrs = getParsedAttrList(Records);
4939 for (const auto &I : Attrs) {
4940 const Record &R = *I.second;
4941 if (!R.getValueAsBit(FieldName: "AcceptsExprPack"))
4942 continue;
4943 OS << " case ParsedAttr::AT_" << I.first << ": {\n";
4944 OS << " CreatedAttr = " << R.getName() << "Attr::CreateWithDelayedArgs";
4945 OS << "(S.Context, ArgExprs.data(), ArgExprs.size(), Attr);\n";
4946 OS << " break;\n";
4947 OS << " }\n";
4948 }
4949 OS << " }\n";
4950 OS << " D->addAttr(CreatedAttr);\n";
4951 OS << "}\n\n";
4952}
4953
4954static bool IsKnownToGCC(const Record &Attr) {
4955 // Look at the spellings for this subject; if there are any spellings which
4956 // claim to be known to GCC, the attribute is known to GCC.
4957 return any_of(Range: GetFlattenedSpellings(Attr),
4958 P: [](const FlattenedSpelling &S) { return S.knownToGCC(); });
4959}
4960
4961/// Emits the parsed attribute helpers
4962void EmitClangAttrParsedAttrImpl(const RecordKeeper &Records, raw_ostream &OS) {
4963 emitSourceFileHeader(Desc: "Parsed attribute helpers", OS, Record: Records);
4964
4965 OS << "#if !defined(WANT_DECL_MERGE_LOGIC) && "
4966 << "!defined(WANT_STMT_MERGE_LOGIC)\n";
4967 PragmaClangAttributeSupport &PragmaAttributeSupport =
4968 getPragmaAttributeSupport(Records);
4969
4970 // Get the list of parsed attributes, and accept the optional list of
4971 // duplicates due to the ParseKind.
4972 ParsedAttrMap Dupes;
4973 ParsedAttrMap Attrs = getParsedAttrList(Records, Dupes: &Dupes);
4974
4975 // Generate all of the custom appertainsTo functions that the attributes
4976 // will be using.
4977 for (const auto &I : Attrs) {
4978 const Record &Attr = *I.second;
4979 if (Attr.isValueUnset(FieldName: "Subjects"))
4980 continue;
4981 const Record *SubjectObj = Attr.getValueAsDef(FieldName: "Subjects");
4982 for (const Record *Subject : SubjectObj->getValueAsListOfDefs(FieldName: "Subjects"))
4983 if (Subject->isSubClassOf(Name: "SubsetSubject"))
4984 GenerateCustomAppertainsTo(Subject: *Subject, OS);
4985 }
4986
4987 // This stream is used to collect all of the declaration attribute merging
4988 // logic for performing mutual exclusion checks. This gets emitted at the
4989 // end of the file in a helper function of its own.
4990 std::string DeclMergeChecks, StmtMergeChecks;
4991 raw_string_ostream MergeDeclOS(DeclMergeChecks), MergeStmtOS(StmtMergeChecks);
4992
4993 // Generate a ParsedAttrInfo struct for each of the attributes.
4994 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) {
4995 // TODO: If the attribute's kind appears in the list of duplicates, that is
4996 // because it is a target-specific attribute that appears multiple times.
4997 // It would be beneficial to test whether the duplicates are "similar
4998 // enough" to each other to not cause problems. For instance, check that
4999 // the spellings are identical, and custom parsing rules match, etc.
5000
5001 // We need to generate struct instances based off ParsedAttrInfo from
5002 // ParsedAttr.cpp.
5003 const std::string &AttrName = I->first;
5004 const Record &Attr = *I->second;
5005 auto Spellings = GetFlattenedSpellings(Attr);
5006 if (!Spellings.empty()) {
5007 OS << "static constexpr ParsedAttrInfo::Spelling " << I->first
5008 << "Spellings[] = {\n";
5009 for (const auto &S : Spellings) {
5010 StringRef RawSpelling = S.name();
5011 std::string Spelling;
5012 if (!S.nameSpace().empty())
5013 Spelling += S.nameSpace().str() + "::";
5014 if (S.variety() == "GNU")
5015 Spelling += NormalizeGNUAttrSpelling(AttrSpelling: RawSpelling);
5016 else
5017 Spelling += RawSpelling;
5018 OS << " {AttributeCommonInfo::AS_" << S.variety();
5019 OS << ", \"" << Spelling << "\"},\n";
5020 }
5021 OS << "};\n";
5022 }
5023
5024 std::vector<std::string> ArgNames;
5025 for (const auto *Arg : Attr.getValueAsListOfDefs(FieldName: "Args")) {
5026 bool UnusedUnset;
5027 if (Arg->getValueAsBitOrUnset(FieldName: "Fake", Unset&: UnusedUnset))
5028 continue;
5029 ArgNames.push_back(x: Arg->getValueAsString(FieldName: "Name").str());
5030 for (const Record *Class : Arg->getSuperClasses()) {
5031 if (Class->getName().starts_with(Prefix: "Variadic")) {
5032 ArgNames.back().append(s: "...");
5033 break;
5034 }
5035 }
5036 }
5037 if (!ArgNames.empty()) {
5038 OS << "static constexpr const char *" << I->first << "ArgNames[] = {\n";
5039 for (const auto &N : ArgNames)
5040 OS << '"' << N << "\",";
5041 OS << "};\n";
5042 }
5043
5044 OS << "struct ParsedAttrInfo" << I->first
5045 << " final : public ParsedAttrInfo {\n";
5046 OS << " constexpr ParsedAttrInfo" << I->first << "() : ParsedAttrInfo(\n";
5047 OS << " /*AttrKind=*/ParsedAttr::AT_" << AttrName << ",\n";
5048 emitArgInfo(R: Attr, OS);
5049 OS << " /*HasCustomParsing=*/";
5050 OS << Attr.getValueAsBit(FieldName: "HasCustomParsing") << ",\n";
5051 OS << " /*AcceptsExprPack=*/";
5052 OS << Attr.getValueAsBit(FieldName: "AcceptsExprPack") << ",\n";
5053 OS << " /*IsTargetSpecific=*/";
5054 OS << Attr.isSubClassOf(Name: "TargetSpecificAttr") << ",\n";
5055 OS << " /*IsType=*/";
5056 OS << (Attr.isSubClassOf(Name: "TypeAttr") || Attr.isSubClassOf(Name: "DeclOrTypeAttr"))
5057 << ",\n";
5058 OS << " /*IsStmt=*/";
5059 OS << (Attr.isSubClassOf(Name: "StmtAttr") || Attr.isSubClassOf(Name: "DeclOrStmtAttr"))
5060 << ",\n";
5061 OS << " /*IsKnownToGCC=*/";
5062 OS << IsKnownToGCC(Attr) << ",\n";
5063 OS << " /*IsSupportedByPragmaAttribute=*/";
5064 OS << PragmaAttributeSupport.isAttributedSupported(Attribute: *I->second) << ",\n";
5065 if (!Spellings.empty())
5066 OS << " /*Spellings=*/" << I->first << "Spellings,\n";
5067 else
5068 OS << " /*Spellings=*/{},\n";
5069 if (!ArgNames.empty())
5070 OS << " /*ArgNames=*/" << I->first << "ArgNames";
5071 else
5072 OS << " /*ArgNames=*/{}";
5073 OS << ") {}\n";
5074 GenerateAppertainsTo(Attr, OS);
5075 GenerateMutualExclusionsChecks(Attr, Records, OS, MergeDeclOS, MergeStmtOS);
5076 GenerateLangOptRequirements(R: Attr, OS);
5077 GenerateTargetRequirements(Attr, Dupes, OS);
5078 GenerateSpellingTargetRequirements(
5079 Attr, TargetSpellings: Attr.getValueAsListOfDefs(FieldName: "TargetSpecificSpellings"), OS);
5080 GenerateSpellingIndexToSemanticSpelling(Attr, OS);
5081 PragmaAttributeSupport.generateStrictConformsTo(Attr: *I->second, OS);
5082 GenerateHandleDeclAttribute(Attr, OS);
5083 GenerateIsParamExpr(Attr, OS);
5084 OS << "static const ParsedAttrInfo" << I->first << " Instance;\n";
5085 OS << "};\n";
5086 OS << "const ParsedAttrInfo" << I->first << " ParsedAttrInfo" << I->first
5087 << "::Instance;\n";
5088 }
5089
5090 OS << "static const ParsedAttrInfo *AttrInfoMap[] = {\n";
5091 for (const auto &Attr : Attrs)
5092 OS << "&ParsedAttrInfo" << Attr.first << "::Instance,\n";
5093 OS << "};\n\n";
5094
5095 // Generate function for handling attributes with delayed arguments
5096 GenerateHandleAttrWithDelayedArgs(Records, OS);
5097
5098 // Generate the attribute match rules.
5099 emitAttributeMatchRules(PragmaAttributeSupport, OS);
5100
5101 OS << "#elif defined(WANT_DECL_MERGE_LOGIC)\n\n";
5102
5103 // Write out the declaration merging check logic.
5104 OS << "static bool DiagnoseMutualExclusions(Sema &S, const NamedDecl *D, "
5105 << "const Attr *A) {\n";
5106 OS << DeclMergeChecks;
5107 OS << " return true;\n";
5108 OS << "}\n\n";
5109
5110 OS << "#elif defined(WANT_STMT_MERGE_LOGIC)\n\n";
5111
5112 // Write out the statement merging check logic.
5113 OS << "static bool DiagnoseMutualExclusions(Sema &S, "
5114 << "const SmallVectorImpl<const Attr *> &C) {\n";
5115 OS << " for (const Attr *A : C) {\n";
5116 OS << StmtMergeChecks;
5117 OS << " }\n";
5118 OS << " return true;\n";
5119 OS << "}\n\n";
5120
5121 OS << "#endif\n";
5122}
5123
5124// Emits the kind list of parsed attributes
5125void EmitClangAttrParsedAttrKinds(const RecordKeeper &Records,
5126 raw_ostream &OS) {
5127 emitSourceFileHeader(Desc: "Attribute name matcher", OS, Record: Records);
5128
5129 std::vector<StringMatcher::StringPair> GNU, Declspec, Microsoft, CXX11,
5130 Keywords, Pragma, C23, HLSLAnnotation;
5131 std::set<StringRef> Seen;
5132 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5133 const Record &Attr = *A;
5134
5135 bool SemaHandler = Attr.getValueAsBit(FieldName: "SemaHandler");
5136 bool Ignored = Attr.getValueAsBit(FieldName: "Ignored");
5137 if (SemaHandler || Ignored) {
5138 // Attribute spellings can be shared between target-specific attributes,
5139 // and can be shared between syntaxes for the same attribute. For
5140 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM-
5141 // specific attribute, or MSP430-specific attribute. Additionally, an
5142 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport">
5143 // for the same semantic attribute. Ultimately, we need to map each of
5144 // these to a single AttributeCommonInfo::Kind value, but the
5145 // StringMatcher class cannot handle duplicate match strings. So we
5146 // generate a list of string to match based on the syntax, and emit
5147 // multiple string matchers depending on the syntax used.
5148 std::string AttrName;
5149 if (Attr.isSubClassOf(Name: "TargetSpecificAttr") &&
5150 !Attr.isValueUnset(FieldName: "ParseKind")) {
5151 StringRef ParseKind = Attr.getValueAsString(FieldName: "ParseKind");
5152 if (!Seen.insert(x: ParseKind).second)
5153 continue;
5154 AttrName = ParseKind.str();
5155 } else {
5156 AttrName = NormalizeAttrName(AttrName: Attr.getName()).str();
5157 }
5158
5159 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr);
5160 for (const auto &S : Spellings) {
5161 StringRef RawSpelling = S.name();
5162 std::vector<StringMatcher::StringPair> *Matches = nullptr;
5163 std::string Spelling;
5164 StringRef Variety = S.variety();
5165 if (Variety == "CXX11") {
5166 Matches = &CXX11;
5167 if (!S.nameSpace().empty())
5168 Spelling += S.nameSpace().str() + "::";
5169 } else if (Variety == "C23") {
5170 Matches = &C23;
5171 if (!S.nameSpace().empty())
5172 Spelling += S.nameSpace().str() + "::";
5173 } else if (Variety == "GNU") {
5174 Matches = &GNU;
5175 } else if (Variety == "Declspec") {
5176 Matches = &Declspec;
5177 } else if (Variety == "Microsoft") {
5178 Matches = &Microsoft;
5179 } else if (Variety == "Keyword") {
5180 Matches = &Keywords;
5181 } else if (Variety == "Pragma") {
5182 Matches = &Pragma;
5183 } else if (Variety == "HLSLAnnotation") {
5184 Matches = &HLSLAnnotation;
5185 if (RawSpelling.compare(RHS: RawSpelling.lower()) != 0)
5186 PrintError(ErrorLoc: S.getSpellingRecord().getLoc(),
5187 Msg: "HLSLAnnotation Attribute must be lower case.");
5188 }
5189
5190 assert(Matches && "Unsupported spelling variety found");
5191
5192 if (Variety == "GNU")
5193 Spelling += NormalizeGNUAttrSpelling(AttrSpelling: RawSpelling);
5194 else
5195 Spelling += RawSpelling;
5196
5197 if (SemaHandler)
5198 Matches->push_back(x: StringMatcher::StringPair(
5199 Spelling, "return AttributeCommonInfo::AT_" + AttrName + ";"));
5200 else
5201 Matches->push_back(x: StringMatcher::StringPair(
5202 Spelling, "return AttributeCommonInfo::IgnoredAttribute;"));
5203 }
5204 }
5205 }
5206
5207 OS << "static AttributeCommonInfo::Kind getAttrKind(StringRef Name, ";
5208 OS << "AttributeCommonInfo::Syntax Syntax) {\n";
5209 OS << " if (AttributeCommonInfo::AS_GNU == Syntax) {\n";
5210 StringMatcher("Name", GNU, OS).Emit();
5211 OS << " } else if (AttributeCommonInfo::AS_Declspec == Syntax) {\n";
5212 StringMatcher("Name", Declspec, OS).Emit();
5213 OS << " } else if (AttributeCommonInfo::AS_Microsoft == Syntax) {\n";
5214 StringMatcher("Name", Microsoft, OS).Emit();
5215 OS << " } else if (AttributeCommonInfo::AS_CXX11 == Syntax) {\n";
5216 StringMatcher("Name", CXX11, OS).Emit();
5217 OS << " } else if (AttributeCommonInfo::AS_C23 == Syntax) {\n";
5218 StringMatcher("Name", C23, OS).Emit();
5219 OS << " } else if (AttributeCommonInfo::AS_Keyword == Syntax || ";
5220 OS << "AttributeCommonInfo::AS_ContextSensitiveKeyword == Syntax) {\n";
5221 StringMatcher("Name", Keywords, OS).Emit();
5222 OS << " } else if (AttributeCommonInfo::AS_Pragma == Syntax) {\n";
5223 StringMatcher("Name", Pragma, OS).Emit();
5224 OS << " } else if (AttributeCommonInfo::AS_HLSLAnnotation == Syntax) {\n";
5225 StringMatcher("Name", HLSLAnnotation, OS).Emit();
5226 OS << " }\n";
5227 OS << " return AttributeCommonInfo::UnknownAttribute;\n"
5228 << "}\n";
5229}
5230
5231// Emits Sema calls for type dependent attributes
5232void EmitClangAttrIsTypeDependent(const RecordKeeper &Records,
5233 raw_ostream &OS) {
5234 emitSourceFileHeader(Desc: "Attribute is type dependent", OS, Record: Records);
5235
5236 OS << "void checkAttrIsTypeDependent(Decl *D, const Attr *A) {\n";
5237 OS << " switch (A->getKind()) {\n";
5238 OS << " default:\n";
5239 OS << " break;\n";
5240 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5241 if (A->getValueAsBit(FieldName: "IsTypeDependent")) {
5242 OS << " case attr::" << A->getName() << ":\n";
5243 OS << " ActOn" << A->getName() << "Attr(D, A);\n";
5244 OS << " break;\n";
5245 }
5246 }
5247 OS << " }\n";
5248 OS << "}\n";
5249}
5250
5251// Emits the code to dump an attribute.
5252void EmitClangAttrTextNodeDump(const RecordKeeper &Records, raw_ostream &OS) {
5253 emitSourceFileHeader(Desc: "Attribute text node dumper", OS, Record: Records);
5254
5255 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5256 const Record &R = *Attr;
5257 if (!R.getValueAsBit(FieldName: "ASTNode"))
5258 continue;
5259
5260 // If the attribute has a semantically-meaningful name (which is determined
5261 // by whether there is a Spelling enumeration for it), then write out the
5262 // spelling used for the attribute.
5263
5264 std::string FunctionContent;
5265 raw_string_ostream SS(FunctionContent);
5266
5267 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: R);
5268 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings))
5269 SS << " OS << \" \" << A->getSpelling();\n";
5270
5271 std::vector<const Record *> Args = R.getValueAsListOfDefs(FieldName: "Args");
5272 for (const auto *Arg : Args)
5273 createArgument(Arg: *Arg, Attr: R.getName())->writeDump(OS&: SS);
5274
5275 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
5276 VariadicExprArgument("DelayedArgs", R.getName()).writeDump(OS);
5277
5278 if (SS.tell()) {
5279 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
5280 << "Attr *A) {\n";
5281 if (!Args.empty())
5282 OS << " const auto *SA = cast<" << R.getName()
5283 << "Attr>(A); (void)SA;\n";
5284 OS << FunctionContent;
5285 OS << " }\n";
5286 }
5287 }
5288}
5289
5290void EmitClangAttrNodeTraverse(const RecordKeeper &Records, raw_ostream &OS) {
5291 emitSourceFileHeader(Desc: "Attribute text node traverser", OS, Record: Records);
5292
5293 for (const auto *Attr : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5294 const Record &R = *Attr;
5295 if (!R.getValueAsBit(FieldName: "ASTNode"))
5296 continue;
5297
5298 std::string FunctionContent;
5299 raw_string_ostream SS(FunctionContent);
5300
5301 std::vector<const Record *> Args = R.getValueAsListOfDefs(FieldName: "Args");
5302 for (const auto *Arg : Args)
5303 createArgument(Arg: *Arg, Attr: R.getName())->writeDumpChildren(OS&: SS);
5304 if (Attr->getValueAsBit(FieldName: "AcceptsExprPack"))
5305 VariadicExprArgument("DelayedArgs", R.getName()).writeDumpChildren(OS&: SS);
5306 if (SS.tell()) {
5307 OS << " void Visit" << R.getName() << "Attr(const " << R.getName()
5308 << "Attr *A) {\n";
5309 if (!Args.empty())
5310 OS << " const auto *SA = cast<" << R.getName()
5311 << "Attr>(A); (void)SA;\n";
5312 OS << FunctionContent;
5313 OS << " }\n";
5314 }
5315 }
5316}
5317
5318void EmitClangAttrParserStringSwitches(const RecordKeeper &Records,
5319 raw_ostream &OS) {
5320 generateNameToAttrsMap(Records);
5321 emitSourceFileHeader(Desc: "Parser-related llvm::StringSwitch cases", OS, Record: Records);
5322 emitClangAttrArgContextList(Records, OS);
5323 emitClangAttrIdentifierArgList(Records, OS);
5324 emitClangAttrUnevaluatedStringLiteralList(Records, OS);
5325 emitClangAttrVariadicIdentifierArgList(Records, OS);
5326 emitClangAttrThisIsaIdentifierArgList(Records, OS);
5327 emitClangAttrAcceptsExprPack(Records, OS);
5328 emitClangAttrTypeArgList(Records, OS);
5329 emitClangAttrLateParsedList(Records, OS);
5330 emitClangAttrLateParsedExperimentalList(Records, OS);
5331 emitClangAttrParseArgsInFunctionScopeList(Records, OS);
5332 emitClangAttrStrictIdentifierArgList(Records, OS);
5333}
5334
5335void EmitClangAttrSubjectMatchRulesParserStringSwitches(
5336 const RecordKeeper &Records, raw_ostream &OS) {
5337 getPragmaAttributeSupport(Records).generateParsingHelpers(OS);
5338}
5339
5340void EmitClangAttrDocTable(const RecordKeeper &Records, raw_ostream &OS) {
5341 emitSourceFileHeader(Desc: "Clang attribute documentation", OS, Record: Records);
5342
5343 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5344 if (!A->getValueAsBit(FieldName: "ASTNode"))
5345 continue;
5346 std::vector<const Record *> Docs = A->getValueAsListOfDefs(FieldName: "Documentation");
5347 assert(!Docs.empty());
5348 // Only look at the first documentation if there are several.
5349 // (Currently there's only one such attr, revisit if this becomes common).
5350 StringRef Text =
5351 Docs.front()->getValueAsOptionalString(FieldName: "Content").value_or(u: "");
5352 OS << "\nstatic const char AttrDoc_" << A->getName() << "[] = "
5353 << "R\"reST(" << Text.trim() << ")reST\";\n";
5354 }
5355}
5356
5357enum class SpellingKind : size_t {
5358 GNU,
5359 CXX11,
5360 C23,
5361 Declspec,
5362 Microsoft,
5363 Keyword,
5364 Pragma,
5365 HLSLAnnotation,
5366 NumSpellingKinds
5367};
5368static const size_t NumSpellingKinds = (size_t)SpellingKind::NumSpellingKinds;
5369
5370class SpellingList {
5371 std::array<std::vector<std::string>, NumSpellingKinds> Spellings;
5372
5373public:
5374 ArrayRef<std::string> operator[](SpellingKind K) const {
5375 return Spellings[(size_t)K];
5376 }
5377
5378 void add(const Record &Attr, const FlattenedSpelling &Spelling) {
5379 SpellingKind Kind =
5380 StringSwitch<SpellingKind>(Spelling.variety())
5381 .Case(S: "GNU", Value: SpellingKind::GNU)
5382 .Case(S: "CXX11", Value: SpellingKind::CXX11)
5383 .Case(S: "C23", Value: SpellingKind::C23)
5384 .Case(S: "Declspec", Value: SpellingKind::Declspec)
5385 .Case(S: "Microsoft", Value: SpellingKind::Microsoft)
5386 .Case(S: "Keyword", Value: SpellingKind::Keyword)
5387 .Case(S: "Pragma", Value: SpellingKind::Pragma)
5388 .Case(S: "HLSLAnnotation", Value: SpellingKind::HLSLAnnotation);
5389 std::string Name;
5390 StringRef NameSpace = Spelling.nameSpace();
5391 if (!NameSpace.empty()) {
5392 Name = NameSpace;
5393 switch (Kind) {
5394 case SpellingKind::CXX11:
5395 case SpellingKind::C23:
5396 Name += "::";
5397 break;
5398 case SpellingKind::Pragma:
5399 Name = " ";
5400 break;
5401 default:
5402 PrintFatalError(ErrorLoc: Attr.getLoc(), Msg: "Unexpected namespace in spelling");
5403 }
5404 }
5405 Name += Spelling.name();
5406
5407 Spellings[(size_t)Kind].push_back(x: Name);
5408 }
5409
5410 void merge(const SpellingList &Other) {
5411 for (size_t Kind = 0; Kind < NumSpellingKinds; ++Kind) {
5412 Spellings[Kind].insert(position: Spellings[Kind].end(),
5413 first: Other.Spellings[Kind].begin(),
5414 last: Other.Spellings[Kind].end());
5415 }
5416 }
5417
5418 bool hasSpelling() const {
5419 return llvm::any_of(Range: Spellings, P: [](const auto &L) { return !L.empty(); });
5420 }
5421};
5422
5423class DocumentationData {
5424public:
5425 const Record *Documentation;
5426 const Record *Attribute;
5427 std::string Heading;
5428 SpellingList SupportedSpellings;
5429
5430 DocumentationData(const Record &Documentation, const Record &Attribute,
5431 std::pair<std::string, SpellingList> HeadingAndSpellings)
5432 : Documentation(&Documentation), Attribute(&Attribute),
5433 Heading(std::move(HeadingAndSpellings.first)),
5434 SupportedSpellings(std::move(HeadingAndSpellings.second)) {}
5435};
5436
5437static void WriteCategoryHeader(const Record *DocCategory,
5438 raw_ostream &OS) {
5439 const StringRef Name = DocCategory->getValueAsString(FieldName: "Name");
5440 OS << Name << "\n" << std::string(Name.size(), '=') << "\n";
5441
5442 // If there is content, print that as well.
5443 const StringRef ContentStr = DocCategory->getValueAsString(FieldName: "Content");
5444 // Trim leading and trailing newlines and spaces.
5445 OS << ContentStr.trim();
5446
5447 OS << "\n\n";
5448}
5449
5450static std::pair<std::string, SpellingList>
5451GetAttributeHeadingAndSpellings(const Record &Documentation,
5452 const Record &Attribute,
5453 StringRef Cat) {
5454 // FIXME: there is no way to have a per-spelling category for the attribute
5455 // documentation. This may not be a limiting factor since the spellings
5456 // should generally be consistently applied across the category.
5457
5458 if (Cat == "HLSL Semantics") {
5459 if (!Attribute.getName().starts_with(Prefix: "HLSL"))
5460 PrintFatalError(ErrorLoc: Attribute.getLoc(),
5461 Msg: "HLSL semantic attribute name must start with HLSL");
5462
5463 assert(Attribute.getName().size() > 4);
5464 std::string Name = Attribute.getName().substr(Start: 4).str();
5465 return std::make_pair(x: std::move(Name), y: SpellingList());
5466 }
5467
5468 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr: Attribute);
5469 if (Spellings.empty())
5470 PrintFatalError(ErrorLoc: Attribute.getLoc(),
5471 Msg: "Attribute has no supported spellings; cannot be "
5472 "documented");
5473
5474 // Determine the heading to be used for this attribute.
5475 std::string Heading = Documentation.getValueAsString(FieldName: "Heading").str();
5476 if (Heading.empty()) {
5477 // If there's only one spelling, we can simply use that.
5478 if (Spellings.size() == 1)
5479 Heading = Spellings.begin()->name();
5480 else {
5481 std::set<std::string> Uniques;
5482 for (const FlattenedSpelling &FS : Spellings) {
5483 std::string Spelling =
5484 NormalizeNameForSpellingComparison(Name: FS.name()).str();
5485 Uniques.insert(x: Spelling);
5486 }
5487 // If the semantic map has only one spelling, that is sufficient for our
5488 // needs.
5489 if (Uniques.size() == 1)
5490 Heading = *Uniques.begin();
5491 // If it's in the undocumented category, just construct a header by
5492 // concatenating all the spellings. Might not be great, but better than
5493 // nothing.
5494 else if (Cat == "Undocumented")
5495 Heading = join(Begin: Uniques.begin(), End: Uniques.end(), Separator: ", ");
5496 }
5497 }
5498
5499 // If the heading is still empty, it is an error.
5500 if (Heading.empty())
5501 PrintFatalError(ErrorLoc: Attribute.getLoc(),
5502 Msg: "This attribute requires a heading to be specified");
5503
5504 SpellingList SupportedSpellings;
5505 for (const auto &I : Spellings)
5506 SupportedSpellings.add(Attr: Attribute, Spelling: I);
5507
5508 return std::make_pair(x: std::move(Heading), y: std::move(SupportedSpellings));
5509}
5510
5511static void WriteDocumentation(const RecordKeeper &Records,
5512 const DocumentationData &Doc, raw_ostream &OS) {
5513 if (StringRef Label = Doc.Documentation->getValueAsString(FieldName: "Label");
5514 !Label.empty())
5515 OS << ".. _" << Label << ":\n\n";
5516 OS << Doc.Heading << "\n" << std::string(Doc.Heading.length(), '-') << "\n";
5517
5518 if (Doc.SupportedSpellings.hasSpelling()) {
5519 // List what spelling syntaxes the attribute supports.
5520 // Note: "#pragma clang attribute" is handled outside the spelling kinds
5521 // loop so it must be last.
5522 OS << ".. csv-table:: Supported Syntaxes\n";
5523 OS << " :header: \"GNU\", \"C++11\", \"C23\", \"``__declspec``\",";
5524 OS << " \"Keyword\", \"``#pragma``\", \"HLSL Annotation\", \"``#pragma "
5525 "clang ";
5526 OS << "attribute``\"\n\n \"";
5527 for (size_t Kind = 0; Kind != NumSpellingKinds; ++Kind) {
5528 SpellingKind K = (SpellingKind)Kind;
5529 // TODO: List Microsoft (IDL-style attribute) spellings once we fully
5530 // support them.
5531 if (K == SpellingKind::Microsoft)
5532 continue;
5533
5534 bool PrintedAny = false;
5535 for (StringRef Spelling : Doc.SupportedSpellings[K]) {
5536 if (PrintedAny)
5537 OS << " |br| ";
5538 OS << "``" << Spelling << "``";
5539 PrintedAny = true;
5540 }
5541
5542 OS << "\",\"";
5543 }
5544
5545 if (getPragmaAttributeSupport(Records).isAttributedSupported(
5546 Attribute: *Doc.Attribute))
5547 OS << "Yes";
5548 OS << "\"\n\n";
5549 }
5550
5551 // If the attribute is deprecated, print a message about it, and possibly
5552 // provide a replacement attribute.
5553 if (!Doc.Documentation->isValueUnset(FieldName: "Deprecated")) {
5554 OS << "This attribute has been deprecated, and may be removed in a future "
5555 << "version of Clang.";
5556 const Record &Deprecated = *Doc.Documentation->getValueAsDef(FieldName: "Deprecated");
5557 const StringRef Replacement = Deprecated.getValueAsString(FieldName: "Replacement");
5558 if (!Replacement.empty())
5559 OS << " This attribute has been superseded by ``" << Replacement
5560 << "``.";
5561 OS << "\n\n";
5562 }
5563
5564 const StringRef ContentStr = Doc.Documentation->getValueAsString(FieldName: "Content");
5565 // Trim leading and trailing newlines and spaces.
5566 OS << ContentStr.trim();
5567
5568 OS << "\n\n\n";
5569}
5570
5571void GetListOfUndocumentedAttributes(
5572 const RecordKeeper &Records,
5573 std::vector<const Record *> &UndocumentedAttrs) {
5574 const Record *Documentation = Records.getDef(Name: "GlobalDocumentation");
5575 if (!Documentation) {
5576 PrintFatalError(Msg: "The Documentation top-level definition is missing.");
5577 return;
5578 }
5579
5580 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5581 const Record &Attr = *A;
5582 std::vector<const Record *> Docs =
5583 Attr.getValueAsListOfDefs(FieldName: "Documentation");
5584 for (const auto *D : Docs) {
5585 const Record &Doc = *D;
5586 const Record *Category = Doc.getValueAsDef(FieldName: "Category");
5587 if (Category->getValueAsString(FieldName: "Name") == "Undocumented")
5588 UndocumentedAttrs.push_back(x: A);
5589 }
5590 }
5591}
5592
5593void EmitClangUndocumentedAttrList(const llvm::RecordKeeper &Records,
5594 llvm::raw_ostream &OS) {
5595 // Emit a newline separated list of attributes whose Documentation is set to
5596 // Undocumented.
5597 std::vector<const Record *> UndocumentedAttrs;
5598 GetListOfUndocumentedAttributes(Records, UndocumentedAttrs);
5599
5600 // Print a small header; this helps catch the situation where someone adds an
5601 // attribute without documentation but it is alphabetically before the first
5602 // attribute in the test file.
5603 OS << "Undocumented attributes:\n";
5604
5605 for (const auto *A : UndocumentedAttrs) {
5606 OS << A->getName() << "\n";
5607 }
5608
5609 // Also print the count; this helps catch attributes after the last one in
5610 // the test file.
5611 OS << "Total: " << UndocumentedAttrs.size() << "\n";
5612}
5613
5614void EmitClangAttrDocs(const RecordKeeper &Records, raw_ostream &OS) {
5615 // Get the documentation introduction paragraph.
5616 const Record *Documentation = Records.getDef(Name: "GlobalDocumentation");
5617 if (!Documentation) {
5618 PrintFatalError(Msg: "The Documentation top-level definition is missing, "
5619 "no documentation will be generated.");
5620 return;
5621 }
5622
5623 OS << Documentation->getValueAsString(FieldName: "Intro") << "\n";
5624
5625 // Gather the Documentation lists from each of the attributes, based on the
5626 // category provided.
5627 struct CategoryLess {
5628 bool operator()(const Record *L, const Record *R) const {
5629 return L->getValueAsString(FieldName: "Name") < R->getValueAsString(FieldName: "Name");
5630 }
5631 };
5632
5633 std::map<const Record *, std::map<uint32_t, DocumentationData>, CategoryLess>
5634 MergedDocs;
5635
5636 std::vector<DocumentationData> UndocumentedDocs;
5637 const Record *UndocumentedCategory = nullptr;
5638
5639 // Collect documentation data, grouping by category and heading.
5640 for (const auto *A : Records.getAllDerivedDefinitions(ClassName: "Attr")) {
5641 const Record &Attr = *A;
5642 std::vector<const Record *> Docs =
5643 Attr.getValueAsListOfDefs(FieldName: "Documentation");
5644
5645 for (const auto *D : Docs) {
5646 const Record &Doc = *D;
5647 const Record *Category = Doc.getValueAsDef(FieldName: "Category");
5648 // If the category is "InternalOnly", then there cannot be any other
5649 // documentation categories (otherwise, the attribute would be
5650 // emitted into the docs).
5651 StringRef Cat = Category->getValueAsString(FieldName: "Name");
5652 if (Cat == "InternalOnly" && Docs.size() > 1)
5653 PrintFatalError(ErrorLoc: Doc.getLoc(),
5654 Msg: "Attribute is \"InternalOnly\", but has multiple "
5655 "documentation categories");
5656
5657 if (Cat == "InternalOnly")
5658 continue;
5659
5660 // Track the Undocumented category Record for later grouping
5661 if (Cat == "Undocumented" && !UndocumentedCategory)
5662 UndocumentedCategory = Category;
5663
5664 // Generate Heading and Spellings.
5665 auto HeadingAndSpellings =
5666 GetAttributeHeadingAndSpellings(Documentation: Doc, Attribute: Attr, Cat);
5667
5668 // Handle Undocumented category separately - no content merging
5669 if (Cat == "Undocumented" && UndocumentedCategory) {
5670 UndocumentedDocs.push_back(
5671 x: DocumentationData(Doc, Attr, std::move(HeadingAndSpellings)));
5672 continue;
5673 }
5674
5675 auto &CategoryDocs = MergedDocs[Category];
5676
5677 std::string key = Doc.getValueAsString(FieldName: "Content").str();
5678 uint32_t keyHash = llvm::hash_value(arg: key);
5679
5680 // If the content already exists, merge the documentation.
5681 auto It = CategoryDocs.find(x: keyHash);
5682 if (It != CategoryDocs.end()) {
5683 // Merge heading
5684 if (It->second.Heading != HeadingAndSpellings.first)
5685 It->second.Heading += ", " + HeadingAndSpellings.first;
5686 // Merge spellings
5687 It->second.SupportedSpellings.merge(Other: HeadingAndSpellings.second);
5688 // Merge content
5689 It->second.Documentation = &Doc; // Update reference
5690 } else {
5691 // Create new entry for unique content
5692 CategoryDocs.emplace(args&: keyHash,
5693 args: DocumentationData(Doc, Attr, HeadingAndSpellings));
5694 }
5695 }
5696 }
5697
5698 std::map<const Record *, std::vector<DocumentationData>, CategoryLess>
5699 SplitDocs;
5700
5701 for (auto &CategoryPair : MergedDocs) {
5702
5703 std::vector<DocumentationData> MD;
5704 for (auto &DocPair : CategoryPair.second)
5705 MD.push_back(x: std::move(DocPair.second));
5706
5707 SplitDocs.emplace(args: CategoryPair.first, args&: MD);
5708 }
5709
5710 // Append Undocumented category entries
5711 if (!UndocumentedDocs.empty() && UndocumentedCategory) {
5712 SplitDocs.emplace(args&: UndocumentedCategory, args&: UndocumentedDocs);
5713 }
5714
5715 // Having split the attributes out based on what documentation goes where,
5716 // we can begin to generate sections of documentation.
5717 for (auto &I : SplitDocs) {
5718 WriteCategoryHeader(DocCategory: I.first, OS);
5719
5720 sort(C&: I.second,
5721 Comp: [](const DocumentationData &D1, const DocumentationData &D2) {
5722 return D1.Heading < D2.Heading;
5723 });
5724
5725 // Walk over each of the attributes in the category and write out their
5726 // documentation.
5727 for (const auto &Doc : I.second)
5728 WriteDocumentation(Records, Doc, OS);
5729 }
5730}
5731
5732void EmitTestPragmaAttributeSupportedAttributes(const RecordKeeper &Records,
5733 raw_ostream &OS) {
5734 PragmaClangAttributeSupport Support = getPragmaAttributeSupport(Records);
5735 ParsedAttrMap Attrs = getParsedAttrList(Records);
5736 OS << "#pragma clang attribute supports the following attributes:\n";
5737 for (const auto &I : Attrs) {
5738 if (!Support.isAttributedSupported(Attribute: *I.second))
5739 continue;
5740 OS << I.first;
5741 if (I.second->isValueUnset(FieldName: "Subjects")) {
5742 OS << " ()\n";
5743 continue;
5744 }
5745 const Record *SubjectObj = I.second->getValueAsDef(FieldName: "Subjects");
5746 OS << " (";
5747 ListSeparator LS;
5748 for (const auto &Subject :
5749 enumerate(First: SubjectObj->getValueAsListOfDefs(FieldName: "Subjects"))) {
5750 if (!isSupportedPragmaClangAttributeSubject(Subject: *Subject.value()))
5751 continue;
5752 OS << LS;
5753 PragmaClangAttributeSupport::RuleOrAggregateRuleSet &RuleSet =
5754 Support.SubjectsToRules.find(Val: Subject.value())->getSecond();
5755 if (RuleSet.isRule()) {
5756 OS << RuleSet.getRule().getEnumValueName();
5757 continue;
5758 }
5759 OS << "(";
5760 for (const auto &Rule : enumerate(First: RuleSet.getAggregateRuleSet())) {
5761 if (Rule.index())
5762 OS << ", ";
5763 OS << Rule.value().getEnumValueName();
5764 }
5765 OS << ")";
5766 }
5767 OS << ")\n";
5768 }
5769 OS << "End of supported attributes.\n";
5770}
5771
5772} // end namespace clang
5773