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