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