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