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