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