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/SmallString.h" 15 #include "llvm/ADT/STLExtras.h" 16 #include "llvm/ADT/SmallSet.h" 17 #include "llvm/ADT/StringExtras.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/TableGen/Error.h" 20 #include "llvm/TableGen/Record.h" 21 #include "llvm/TableGen/StringMatcher.h" 22 #include "llvm/TableGen/TableGenBackend.h" 23 #include <algorithm> 24 #include <cctype> 25 #include <memory> 26 #include <set> 27 #include <sstream> 28 29 using namespace llvm; 30 31 namespace { 32 class FlattenedSpelling { 33 std::string V, N, NS; 34 bool K; 35 36 public: 37 FlattenedSpelling(const std::string &Variety, const std::string &Name, 38 const std::string &Namespace, bool KnownToGCC) : 39 V(Variety), N(Name), NS(Namespace), K(KnownToGCC) {} 40 explicit FlattenedSpelling(const Record &Spelling) : 41 V(Spelling.getValueAsString("Variety")), 42 N(Spelling.getValueAsString("Name")) { 43 44 assert(V != "GCC" && "Given a GCC spelling, which means this hasn't been" 45 "flattened!"); 46 if (V == "CXX11" || V == "Pragma") 47 NS = Spelling.getValueAsString("Namespace"); 48 bool Unset; 49 K = Spelling.getValueAsBitOrUnset("KnownToGCC", Unset); 50 } 51 52 const std::string &variety() const { return V; } 53 const std::string &name() const { return N; } 54 const std::string &nameSpace() const { return NS; } 55 bool knownToGCC() const { return K; } 56 }; 57 } // end anonymous namespace 58 59 static std::vector<FlattenedSpelling> 60 GetFlattenedSpellings(const Record &Attr) { 61 std::vector<Record *> Spellings = Attr.getValueAsListOfDefs("Spellings"); 62 std::vector<FlattenedSpelling> Ret; 63 64 for (const auto &Spelling : Spellings) { 65 if (Spelling->getValueAsString("Variety") == "GCC") { 66 // Gin up two new spelling objects to add into the list. 67 Ret.emplace_back("GNU", Spelling->getValueAsString("Name"), "", true); 68 Ret.emplace_back("CXX11", Spelling->getValueAsString("Name"), "gnu", 69 true); 70 } else 71 Ret.push_back(FlattenedSpelling(*Spelling)); 72 } 73 74 return Ret; 75 } 76 77 static std::string ReadPCHRecord(StringRef type) { 78 return StringSwitch<std::string>(type) 79 .EndsWith("Decl *", "GetLocalDeclAs<" 80 + std::string(type, 0, type.size()-1) + ">(F, Record[Idx++])") 81 .Case("TypeSourceInfo *", "GetTypeSourceInfo(F, Record, Idx)") 82 .Case("Expr *", "ReadExpr(F)") 83 .Case("IdentifierInfo *", "GetIdentifierInfo(F, Record, Idx)") 84 .Case("std::string", "ReadString(Record, Idx)") 85 .Default("Record[Idx++]"); 86 } 87 88 // Assumes that the way to get the value is SA->getname() 89 static std::string WritePCHRecord(StringRef type, StringRef name) { 90 return StringSwitch<std::string>(type) 91 .EndsWith("Decl *", "AddDeclRef(" + std::string(name) + 92 ", Record);\n") 93 .Case("TypeSourceInfo *", 94 "AddTypeSourceInfo(" + std::string(name) + ", Record);\n") 95 .Case("Expr *", "AddStmt(" + std::string(name) + ");\n") 96 .Case("IdentifierInfo *", 97 "AddIdentifierRef(" + std::string(name) + ", Record);\n") 98 .Case("std::string", "AddString(" + std::string(name) + ", Record);\n") 99 .Default("Record.push_back(" + std::string(name) + ");\n"); 100 } 101 102 // Normalize attribute name by removing leading and trailing 103 // underscores. For example, __foo, foo__, __foo__ would 104 // become foo. 105 static StringRef NormalizeAttrName(StringRef AttrName) { 106 if (AttrName.startswith("__")) 107 AttrName = AttrName.substr(2, AttrName.size()); 108 109 if (AttrName.endswith("__")) 110 AttrName = AttrName.substr(0, AttrName.size() - 2); 111 112 return AttrName; 113 } 114 115 // Normalize the name by removing any and all leading and trailing underscores. 116 // This is different from NormalizeAttrName in that it also handles names like 117 // _pascal and __pascal. 118 static StringRef NormalizeNameForSpellingComparison(StringRef Name) { 119 return Name.trim("_"); 120 } 121 122 // Normalize attribute spelling only if the spelling has both leading 123 // and trailing underscores. For example, __ms_struct__ will be 124 // normalized to "ms_struct"; __cdecl will remain intact. 125 static StringRef NormalizeAttrSpelling(StringRef AttrSpelling) { 126 if (AttrSpelling.startswith("__") && AttrSpelling.endswith("__")) { 127 AttrSpelling = AttrSpelling.substr(2, AttrSpelling.size() - 4); 128 } 129 130 return AttrSpelling; 131 } 132 133 typedef std::vector<std::pair<std::string, const Record *>> ParsedAttrMap; 134 135 static ParsedAttrMap getParsedAttrList(const RecordKeeper &Records, 136 ParsedAttrMap *Dupes = nullptr) { 137 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 138 std::set<std::string> Seen; 139 ParsedAttrMap R; 140 for (const auto *Attr : Attrs) { 141 if (Attr->getValueAsBit("SemaHandler")) { 142 std::string AN; 143 if (Attr->isSubClassOf("TargetSpecificAttr") && 144 !Attr->isValueUnset("ParseKind")) { 145 AN = Attr->getValueAsString("ParseKind"); 146 147 // If this attribute has already been handled, it does not need to be 148 // handled again. 149 if (Seen.find(AN) != Seen.end()) { 150 if (Dupes) 151 Dupes->push_back(std::make_pair(AN, Attr)); 152 continue; 153 } 154 Seen.insert(AN); 155 } else 156 AN = NormalizeAttrName(Attr->getName()).str(); 157 158 R.push_back(std::make_pair(AN, Attr)); 159 } 160 } 161 return R; 162 } 163 164 namespace { 165 class Argument { 166 std::string lowerName, upperName; 167 StringRef attrName; 168 bool isOpt; 169 bool Fake; 170 171 public: 172 Argument(const Record &Arg, StringRef Attr) 173 : lowerName(Arg.getValueAsString("Name")), upperName(lowerName), 174 attrName(Attr), isOpt(false), Fake(false) { 175 if (!lowerName.empty()) { 176 lowerName[0] = std::tolower(lowerName[0]); 177 upperName[0] = std::toupper(upperName[0]); 178 } 179 } 180 virtual ~Argument() = default; 181 182 StringRef getLowerName() const { return lowerName; } 183 StringRef getUpperName() const { return upperName; } 184 StringRef getAttrName() const { return attrName; } 185 186 bool isOptional() const { return isOpt; } 187 void setOptional(bool set) { isOpt = set; } 188 189 bool isFake() const { return Fake; } 190 void setFake(bool fake) { Fake = fake; } 191 192 // These functions print the argument contents formatted in different ways. 193 virtual void writeAccessors(raw_ostream &OS) const = 0; 194 virtual void writeAccessorDefinitions(raw_ostream &OS) const {} 195 virtual void writeASTVisitorTraversal(raw_ostream &OS) const {} 196 virtual void writeCloneArgs(raw_ostream &OS) const = 0; 197 virtual void writeTemplateInstantiationArgs(raw_ostream &OS) const = 0; 198 virtual void writeTemplateInstantiation(raw_ostream &OS) const {} 199 virtual void writeCtorBody(raw_ostream &OS) const {} 200 virtual void writeCtorInitializers(raw_ostream &OS) const = 0; 201 virtual void writeCtorDefaultInitializers(raw_ostream &OS) const = 0; 202 virtual void writeCtorParameters(raw_ostream &OS) const = 0; 203 virtual void writeDeclarations(raw_ostream &OS) const = 0; 204 virtual void writePCHReadArgs(raw_ostream &OS) const = 0; 205 virtual void writePCHReadDecls(raw_ostream &OS) const = 0; 206 virtual void writePCHWrite(raw_ostream &OS) const = 0; 207 virtual void writeValue(raw_ostream &OS) const = 0; 208 virtual void writeDump(raw_ostream &OS) const = 0; 209 virtual void writeDumpChildren(raw_ostream &OS) const {} 210 virtual void writeHasChildren(raw_ostream &OS) const { OS << "false"; } 211 212 virtual bool isEnumArg() const { return false; } 213 virtual bool isVariadicEnumArg() const { return false; } 214 virtual bool isVariadic() const { return false; } 215 216 virtual void writeImplicitCtorArgs(raw_ostream &OS) const { 217 OS << getUpperName(); 218 } 219 }; 220 221 class SimpleArgument : public Argument { 222 std::string type; 223 224 public: 225 SimpleArgument(const Record &Arg, StringRef Attr, std::string T) 226 : Argument(Arg, Attr), type(T) 227 {} 228 229 std::string getType() const { return type; } 230 231 void writeAccessors(raw_ostream &OS) const override { 232 OS << " " << type << " get" << getUpperName() << "() const {\n"; 233 OS << " return " << getLowerName() << ";\n"; 234 OS << " }"; 235 } 236 void writeCloneArgs(raw_ostream &OS) const override { 237 OS << getLowerName(); 238 } 239 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 240 OS << "A->get" << getUpperName() << "()"; 241 } 242 void writeCtorInitializers(raw_ostream &OS) const override { 243 OS << getLowerName() << "(" << getUpperName() << ")"; 244 } 245 void writeCtorDefaultInitializers(raw_ostream &OS) const override { 246 OS << getLowerName() << "()"; 247 } 248 void writeCtorParameters(raw_ostream &OS) const override { 249 OS << type << " " << getUpperName(); 250 } 251 void writeDeclarations(raw_ostream &OS) const override { 252 OS << type << " " << getLowerName() << ";"; 253 } 254 void writePCHReadDecls(raw_ostream &OS) const override { 255 std::string read = ReadPCHRecord(type); 256 OS << " " << type << " " << getLowerName() << " = " << read << ";\n"; 257 } 258 void writePCHReadArgs(raw_ostream &OS) const override { 259 OS << getLowerName(); 260 } 261 void writePCHWrite(raw_ostream &OS) const override { 262 OS << " " << WritePCHRecord(type, "SA->get" + 263 std::string(getUpperName()) + "()"); 264 } 265 void writeValue(raw_ostream &OS) const override { 266 if (type == "FunctionDecl *") { 267 OS << "\" << get" << getUpperName() 268 << "()->getNameInfo().getAsString() << \""; 269 } else if (type == "IdentifierInfo *") { 270 OS << "\" << get" << getUpperName() << "()->getName() << \""; 271 } else if (type == "TypeSourceInfo *") { 272 OS << "\" << get" << getUpperName() << "().getAsString() << \""; 273 } else { 274 OS << "\" << get" << getUpperName() << "() << \""; 275 } 276 } 277 void writeDump(raw_ostream &OS) const override { 278 if (type == "FunctionDecl *") { 279 OS << " OS << \" \";\n"; 280 OS << " dumpBareDeclRef(SA->get" << getUpperName() << "());\n"; 281 } else if (type == "IdentifierInfo *") { 282 OS << " OS << \" \" << SA->get" << getUpperName() 283 << "()->getName();\n"; 284 } else if (type == "TypeSourceInfo *") { 285 OS << " OS << \" \" << SA->get" << getUpperName() 286 << "().getAsString();\n"; 287 } else if (type == "bool") { 288 OS << " if (SA->get" << getUpperName() << "()) OS << \" " 289 << getUpperName() << "\";\n"; 290 } else if (type == "int" || type == "unsigned") { 291 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n"; 292 } else { 293 llvm_unreachable("Unknown SimpleArgument type!"); 294 } 295 } 296 }; 297 298 class DefaultSimpleArgument : public SimpleArgument { 299 int64_t Default; 300 301 public: 302 DefaultSimpleArgument(const Record &Arg, StringRef Attr, 303 std::string T, int64_t Default) 304 : SimpleArgument(Arg, Attr, T), Default(Default) {} 305 306 void writeAccessors(raw_ostream &OS) const override { 307 SimpleArgument::writeAccessors(OS); 308 309 OS << "\n\n static const " << getType() << " Default" << getUpperName() 310 << " = " << Default << ";"; 311 } 312 }; 313 314 class StringArgument : public Argument { 315 public: 316 StringArgument(const Record &Arg, StringRef Attr) 317 : Argument(Arg, Attr) 318 {} 319 320 void writeAccessors(raw_ostream &OS) const override { 321 OS << " llvm::StringRef get" << getUpperName() << "() const {\n"; 322 OS << " return llvm::StringRef(" << getLowerName() << ", " 323 << getLowerName() << "Length);\n"; 324 OS << " }\n"; 325 OS << " unsigned get" << getUpperName() << "Length() const {\n"; 326 OS << " return " << getLowerName() << "Length;\n"; 327 OS << " }\n"; 328 OS << " void set" << getUpperName() 329 << "(ASTContext &C, llvm::StringRef S) {\n"; 330 OS << " " << getLowerName() << "Length = S.size();\n"; 331 OS << " this->" << getLowerName() << " = new (C, 1) char [" 332 << getLowerName() << "Length];\n"; 333 OS << " if (!S.empty())\n"; 334 OS << " std::memcpy(this->" << getLowerName() << ", S.data(), " 335 << getLowerName() << "Length);\n"; 336 OS << " }"; 337 } 338 void writeCloneArgs(raw_ostream &OS) const override { 339 OS << "get" << getUpperName() << "()"; 340 } 341 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 342 OS << "A->get" << getUpperName() << "()"; 343 } 344 void writeCtorBody(raw_ostream &OS) const override { 345 OS << " if (!" << getUpperName() << ".empty())\n"; 346 OS << " std::memcpy(" << getLowerName() << ", " << getUpperName() 347 << ".data(), " << getLowerName() << "Length);"; 348 } 349 void writeCtorInitializers(raw_ostream &OS) const override { 350 OS << getLowerName() << "Length(" << getUpperName() << ".size())," 351 << getLowerName() << "(new (Ctx, 1) char[" << getLowerName() 352 << "Length])"; 353 } 354 void writeCtorDefaultInitializers(raw_ostream &OS) const override { 355 OS << getLowerName() << "Length(0)," << getLowerName() << "(nullptr)"; 356 } 357 void writeCtorParameters(raw_ostream &OS) const override { 358 OS << "llvm::StringRef " << getUpperName(); 359 } 360 void writeDeclarations(raw_ostream &OS) const override { 361 OS << "unsigned " << getLowerName() << "Length;\n"; 362 OS << "char *" << getLowerName() << ";"; 363 } 364 void writePCHReadDecls(raw_ostream &OS) const override { 365 OS << " std::string " << getLowerName() 366 << "= ReadString(Record, Idx);\n"; 367 } 368 void writePCHReadArgs(raw_ostream &OS) const override { 369 OS << getLowerName(); 370 } 371 void writePCHWrite(raw_ostream &OS) const override { 372 OS << " AddString(SA->get" << getUpperName() << "(), Record);\n"; 373 } 374 void writeValue(raw_ostream &OS) const override { 375 OS << "\\\"\" << get" << getUpperName() << "() << \"\\\""; 376 } 377 void writeDump(raw_ostream &OS) const override { 378 OS << " OS << \" \\\"\" << SA->get" << getUpperName() 379 << "() << \"\\\"\";\n"; 380 } 381 }; 382 383 class AlignedArgument : public Argument { 384 public: 385 AlignedArgument(const Record &Arg, StringRef Attr) 386 : Argument(Arg, Attr) 387 {} 388 389 void writeAccessors(raw_ostream &OS) const override { 390 OS << " bool is" << getUpperName() << "Dependent() const;\n"; 391 392 OS << " unsigned get" << getUpperName() << "(ASTContext &Ctx) const;\n"; 393 394 OS << " bool is" << getUpperName() << "Expr() const {\n"; 395 OS << " return is" << getLowerName() << "Expr;\n"; 396 OS << " }\n"; 397 398 OS << " Expr *get" << getUpperName() << "Expr() const {\n"; 399 OS << " assert(is" << getLowerName() << "Expr);\n"; 400 OS << " return " << getLowerName() << "Expr;\n"; 401 OS << " }\n"; 402 403 OS << " TypeSourceInfo *get" << getUpperName() << "Type() const {\n"; 404 OS << " assert(!is" << getLowerName() << "Expr);\n"; 405 OS << " return " << getLowerName() << "Type;\n"; 406 OS << " }"; 407 } 408 void writeAccessorDefinitions(raw_ostream &OS) const override { 409 OS << "bool " << getAttrName() << "Attr::is" << getUpperName() 410 << "Dependent() const {\n"; 411 OS << " if (is" << getLowerName() << "Expr)\n"; 412 OS << " return " << getLowerName() << "Expr && (" << getLowerName() 413 << "Expr->isValueDependent() || " << getLowerName() 414 << "Expr->isTypeDependent());\n"; 415 OS << " else\n"; 416 OS << " return " << getLowerName() 417 << "Type->getType()->isDependentType();\n"; 418 OS << "}\n"; 419 420 // FIXME: Do not do the calculation here 421 // FIXME: Handle types correctly 422 // A null pointer means maximum alignment 423 OS << "unsigned " << getAttrName() << "Attr::get" << getUpperName() 424 << "(ASTContext &Ctx) const {\n"; 425 OS << " assert(!is" << getUpperName() << "Dependent());\n"; 426 OS << " if (is" << getLowerName() << "Expr)\n"; 427 OS << " return " << getLowerName() << "Expr ? " << getLowerName() 428 << "Expr->EvaluateKnownConstInt(Ctx).getZExtValue()" 429 << " * Ctx.getCharWidth() : " 430 << "Ctx.getTargetDefaultAlignForAttributeAligned();\n"; 431 OS << " else\n"; 432 OS << " return 0; // FIXME\n"; 433 OS << "}\n"; 434 } 435 void writeCloneArgs(raw_ostream &OS) const override { 436 OS << "is" << getLowerName() << "Expr, is" << getLowerName() 437 << "Expr ? static_cast<void*>(" << getLowerName() 438 << "Expr) : " << getLowerName() 439 << "Type"; 440 } 441 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 442 // FIXME: move the definition in Sema::InstantiateAttrs to here. 443 // In the meantime, aligned attributes are cloned. 444 } 445 void writeCtorBody(raw_ostream &OS) const override { 446 OS << " if (is" << getLowerName() << "Expr)\n"; 447 OS << " " << getLowerName() << "Expr = reinterpret_cast<Expr *>(" 448 << getUpperName() << ");\n"; 449 OS << " else\n"; 450 OS << " " << getLowerName() 451 << "Type = reinterpret_cast<TypeSourceInfo *>(" << getUpperName() 452 << ");"; 453 } 454 void writeCtorInitializers(raw_ostream &OS) const override { 455 OS << "is" << getLowerName() << "Expr(Is" << getUpperName() << "Expr)"; 456 } 457 void writeCtorDefaultInitializers(raw_ostream &OS) const override { 458 OS << "is" << getLowerName() << "Expr(false)"; 459 } 460 void writeCtorParameters(raw_ostream &OS) const override { 461 OS << "bool Is" << getUpperName() << "Expr, void *" << getUpperName(); 462 } 463 void writeImplicitCtorArgs(raw_ostream &OS) const override { 464 OS << "Is" << getUpperName() << "Expr, " << getUpperName(); 465 } 466 void writeDeclarations(raw_ostream &OS) const override { 467 OS << "bool is" << getLowerName() << "Expr;\n"; 468 OS << "union {\n"; 469 OS << "Expr *" << getLowerName() << "Expr;\n"; 470 OS << "TypeSourceInfo *" << getLowerName() << "Type;\n"; 471 OS << "};"; 472 } 473 void writePCHReadArgs(raw_ostream &OS) const override { 474 OS << "is" << getLowerName() << "Expr, " << getLowerName() << "Ptr"; 475 } 476 void writePCHReadDecls(raw_ostream &OS) const override { 477 OS << " bool is" << getLowerName() << "Expr = Record[Idx++];\n"; 478 OS << " void *" << getLowerName() << "Ptr;\n"; 479 OS << " if (is" << getLowerName() << "Expr)\n"; 480 OS << " " << getLowerName() << "Ptr = ReadExpr(F);\n"; 481 OS << " else\n"; 482 OS << " " << getLowerName() 483 << "Ptr = GetTypeSourceInfo(F, Record, Idx);\n"; 484 } 485 void writePCHWrite(raw_ostream &OS) const override { 486 OS << " Record.push_back(SA->is" << getUpperName() << "Expr());\n"; 487 OS << " if (SA->is" << getUpperName() << "Expr())\n"; 488 OS << " AddStmt(SA->get" << getUpperName() << "Expr());\n"; 489 OS << " else\n"; 490 OS << " AddTypeSourceInfo(SA->get" << getUpperName() 491 << "Type(), Record);\n"; 492 } 493 void writeValue(raw_ostream &OS) const override { 494 OS << "\";\n"; 495 // The aligned attribute argument expression is optional. 496 OS << " if (is" << getLowerName() << "Expr && " 497 << getLowerName() << "Expr)\n"; 498 OS << " " << getLowerName() << "Expr->printPretty(OS, nullptr, Policy);\n"; 499 OS << " OS << \""; 500 } 501 void writeDump(raw_ostream &OS) const override { 502 } 503 void writeDumpChildren(raw_ostream &OS) const override { 504 OS << " if (SA->is" << getUpperName() << "Expr())\n"; 505 OS << " dumpStmt(SA->get" << getUpperName() << "Expr());\n"; 506 OS << " else\n"; 507 OS << " dumpType(SA->get" << getUpperName() 508 << "Type()->getType());\n"; 509 } 510 void writeHasChildren(raw_ostream &OS) const override { 511 OS << "SA->is" << getUpperName() << "Expr()"; 512 } 513 }; 514 515 class VariadicArgument : public Argument { 516 std::string Type, ArgName, ArgSizeName, RangeName; 517 518 protected: 519 // Assumed to receive a parameter: raw_ostream OS. 520 virtual void writeValueImpl(raw_ostream &OS) const { 521 OS << " OS << Val;\n"; 522 } 523 524 public: 525 VariadicArgument(const Record &Arg, StringRef Attr, std::string T) 526 : Argument(Arg, Attr), Type(T), ArgName(getLowerName().str() + "_"), 527 ArgSizeName(ArgName + "Size"), RangeName(getLowerName()) {} 528 529 std::string getType() const { return Type; } 530 bool isVariadic() const override { return true; } 531 532 void writeAccessors(raw_ostream &OS) const override { 533 std::string IteratorType = getLowerName().str() + "_iterator"; 534 std::string BeginFn = getLowerName().str() + "_begin()"; 535 std::string EndFn = getLowerName().str() + "_end()"; 536 537 OS << " typedef " << Type << "* " << IteratorType << ";\n"; 538 OS << " " << IteratorType << " " << BeginFn << " const {" 539 << " return " << ArgName << "; }\n"; 540 OS << " " << IteratorType << " " << EndFn << " const {" 541 << " return " << ArgName << " + " << ArgSizeName << "; }\n"; 542 OS << " unsigned " << getLowerName() << "_size() const {" 543 << " return " << ArgSizeName << "; }\n"; 544 OS << " llvm::iterator_range<" << IteratorType << "> " << RangeName 545 << "() const { return llvm::make_range(" << BeginFn << ", " << EndFn 546 << "); }\n"; 547 } 548 void writeCloneArgs(raw_ostream &OS) const override { 549 OS << ArgName << ", " << ArgSizeName; 550 } 551 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 552 // This isn't elegant, but we have to go through public methods... 553 OS << "A->" << getLowerName() << "_begin(), " 554 << "A->" << getLowerName() << "_size()"; 555 } 556 void writeCtorBody(raw_ostream &OS) const override { 557 OS << " std::copy(" << getUpperName() << ", " << getUpperName() 558 << " + " << ArgSizeName << ", " << ArgName << ");"; 559 } 560 void writeCtorInitializers(raw_ostream &OS) const override { 561 OS << ArgSizeName << "(" << getUpperName() << "Size), " 562 << ArgName << "(new (Ctx, 16) " << getType() << "[" 563 << ArgSizeName << "])"; 564 } 565 void writeCtorDefaultInitializers(raw_ostream &OS) const override { 566 OS << ArgSizeName << "(0), " << ArgName << "(nullptr)"; 567 } 568 void writeCtorParameters(raw_ostream &OS) const override { 569 OS << getType() << " *" << getUpperName() << ", unsigned " 570 << getUpperName() << "Size"; 571 } 572 void writeImplicitCtorArgs(raw_ostream &OS) const override { 573 OS << getUpperName() << ", " << getUpperName() << "Size"; 574 } 575 void writeDeclarations(raw_ostream &OS) const override { 576 OS << " unsigned " << ArgSizeName << ";\n"; 577 OS << " " << getType() << " *" << ArgName << ";"; 578 } 579 void writePCHReadDecls(raw_ostream &OS) const override { 580 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n"; 581 OS << " SmallVector<" << Type << ", 4> " << getLowerName() 582 << ";\n"; 583 OS << " " << getLowerName() << ".reserve(" << getLowerName() 584 << "Size);\n"; 585 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n"; 586 587 std::string read = ReadPCHRecord(Type); 588 OS << " " << getLowerName() << ".push_back(" << read << ");\n"; 589 } 590 void writePCHReadArgs(raw_ostream &OS) const override { 591 OS << getLowerName() << ".data(), " << getLowerName() << "Size"; 592 } 593 void writePCHWrite(raw_ostream &OS) const override { 594 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n"; 595 OS << " for (auto &Val : SA->" << RangeName << "())\n"; 596 OS << " " << WritePCHRecord(Type, "Val"); 597 } 598 void writeValue(raw_ostream &OS) const override { 599 OS << "\";\n"; 600 OS << " bool isFirst = true;\n" 601 << " for (const auto &Val : " << RangeName << "()) {\n" 602 << " if (isFirst) isFirst = false;\n" 603 << " else OS << \", \";\n"; 604 writeValueImpl(OS); 605 OS << " }\n"; 606 OS << " OS << \""; 607 } 608 void writeDump(raw_ostream &OS) const override { 609 OS << " for (const auto &Val : SA->" << RangeName << "())\n"; 610 OS << " OS << \" \" << Val;\n"; 611 } 612 }; 613 614 // Unique the enums, but maintain the original declaration ordering. 615 std::vector<std::string> 616 uniqueEnumsInOrder(const std::vector<std::string> &enums) { 617 std::vector<std::string> uniques; 618 std::set<std::string> unique_set(enums.begin(), enums.end()); 619 for (const auto &i : enums) { 620 std::set<std::string>::iterator set_i = unique_set.find(i); 621 if (set_i != unique_set.end()) { 622 uniques.push_back(i); 623 unique_set.erase(set_i); 624 } 625 } 626 return uniques; 627 } 628 629 class EnumArgument : public Argument { 630 std::string type; 631 std::vector<std::string> values, enums, uniques; 632 public: 633 EnumArgument(const Record &Arg, StringRef Attr) 634 : Argument(Arg, Attr), type(Arg.getValueAsString("Type")), 635 values(Arg.getValueAsListOfStrings("Values")), 636 enums(Arg.getValueAsListOfStrings("Enums")), 637 uniques(uniqueEnumsInOrder(enums)) 638 { 639 // FIXME: Emit a proper error 640 assert(!uniques.empty()); 641 } 642 643 bool isEnumArg() const override { return true; } 644 645 void writeAccessors(raw_ostream &OS) const override { 646 OS << " " << type << " get" << getUpperName() << "() const {\n"; 647 OS << " return " << getLowerName() << ";\n"; 648 OS << " }"; 649 } 650 void writeCloneArgs(raw_ostream &OS) const override { 651 OS << getLowerName(); 652 } 653 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 654 OS << "A->get" << getUpperName() << "()"; 655 } 656 void writeCtorInitializers(raw_ostream &OS) const override { 657 OS << getLowerName() << "(" << getUpperName() << ")"; 658 } 659 void writeCtorDefaultInitializers(raw_ostream &OS) const override { 660 OS << getLowerName() << "(" << type << "(0))"; 661 } 662 void writeCtorParameters(raw_ostream &OS) const override { 663 OS << type << " " << getUpperName(); 664 } 665 void writeDeclarations(raw_ostream &OS) const override { 666 std::vector<std::string>::const_iterator i = uniques.begin(), 667 e = uniques.end(); 668 // The last one needs to not have a comma. 669 --e; 670 671 OS << "public:\n"; 672 OS << " enum " << type << " {\n"; 673 for (; i != e; ++i) 674 OS << " " << *i << ",\n"; 675 OS << " " << *e << "\n"; 676 OS << " };\n"; 677 OS << "private:\n"; 678 OS << " " << type << " " << getLowerName() << ";"; 679 } 680 void writePCHReadDecls(raw_ostream &OS) const override { 681 OS << " " << getAttrName() << "Attr::" << type << " " << getLowerName() 682 << "(static_cast<" << getAttrName() << "Attr::" << type 683 << ">(Record[Idx++]));\n"; 684 } 685 void writePCHReadArgs(raw_ostream &OS) const override { 686 OS << getLowerName(); 687 } 688 void writePCHWrite(raw_ostream &OS) const override { 689 OS << "Record.push_back(SA->get" << getUpperName() << "());\n"; 690 } 691 void writeValue(raw_ostream &OS) const override { 692 // FIXME: this isn't 100% correct -- some enum arguments require printing 693 // as a string literal, while others require printing as an identifier. 694 // Tablegen currently does not distinguish between the two forms. 695 OS << "\\\"\" << " << getAttrName() << "Attr::Convert" << type << "ToStr(get" 696 << getUpperName() << "()) << \"\\\""; 697 } 698 void writeDump(raw_ostream &OS) const override { 699 OS << " switch(SA->get" << getUpperName() << "()) {\n"; 700 for (const auto &I : uniques) { 701 OS << " case " << getAttrName() << "Attr::" << I << ":\n"; 702 OS << " OS << \" " << I << "\";\n"; 703 OS << " break;\n"; 704 } 705 OS << " }\n"; 706 } 707 708 void writeConversion(raw_ostream &OS) const { 709 OS << " static bool ConvertStrTo" << type << "(StringRef Val, "; 710 OS << type << " &Out) {\n"; 711 OS << " Optional<" << type << "> R = llvm::StringSwitch<Optional<"; 712 OS << type << ">>(Val)\n"; 713 for (size_t I = 0; I < enums.size(); ++I) { 714 OS << " .Case(\"" << values[I] << "\", "; 715 OS << getAttrName() << "Attr::" << enums[I] << ")\n"; 716 } 717 OS << " .Default(Optional<" << type << ">());\n"; 718 OS << " if (R) {\n"; 719 OS << " Out = *R;\n return true;\n }\n"; 720 OS << " return false;\n"; 721 OS << " }\n\n"; 722 723 // Mapping from enumeration values back to enumeration strings isn't 724 // trivial because some enumeration values have multiple named 725 // enumerators, such as type_visibility(internal) and 726 // type_visibility(hidden) both mapping to TypeVisibilityAttr::Hidden. 727 OS << " static const char *Convert" << type << "ToStr(" 728 << type << " Val) {\n" 729 << " switch(Val) {\n"; 730 std::set<std::string> Uniques; 731 for (size_t I = 0; I < enums.size(); ++I) { 732 if (Uniques.insert(enums[I]).second) 733 OS << " case " << getAttrName() << "Attr::" << enums[I] 734 << ": return \"" << values[I] << "\";\n"; 735 } 736 OS << " }\n" 737 << " llvm_unreachable(\"No enumerator with that value\");\n" 738 << " }\n"; 739 } 740 }; 741 742 class VariadicEnumArgument: public VariadicArgument { 743 std::string type, QualifiedTypeName; 744 std::vector<std::string> values, enums, uniques; 745 746 protected: 747 void writeValueImpl(raw_ostream &OS) const override { 748 // FIXME: this isn't 100% correct -- some enum arguments require printing 749 // as a string literal, while others require printing as an identifier. 750 // Tablegen currently does not distinguish between the two forms. 751 OS << " OS << \"\\\"\" << " << getAttrName() << "Attr::Convert" << type 752 << "ToStr(Val)" << "<< \"\\\"\";\n"; 753 } 754 755 public: 756 VariadicEnumArgument(const Record &Arg, StringRef Attr) 757 : VariadicArgument(Arg, Attr, Arg.getValueAsString("Type")), 758 type(Arg.getValueAsString("Type")), 759 values(Arg.getValueAsListOfStrings("Values")), 760 enums(Arg.getValueAsListOfStrings("Enums")), 761 uniques(uniqueEnumsInOrder(enums)) 762 { 763 QualifiedTypeName = getAttrName().str() + "Attr::" + type; 764 765 // FIXME: Emit a proper error 766 assert(!uniques.empty()); 767 } 768 769 bool isVariadicEnumArg() const override { return true; } 770 771 void writeDeclarations(raw_ostream &OS) const override { 772 std::vector<std::string>::const_iterator i = uniques.begin(), 773 e = uniques.end(); 774 // The last one needs to not have a comma. 775 --e; 776 777 OS << "public:\n"; 778 OS << " enum " << type << " {\n"; 779 for (; i != e; ++i) 780 OS << " " << *i << ",\n"; 781 OS << " " << *e << "\n"; 782 OS << " };\n"; 783 OS << "private:\n"; 784 785 VariadicArgument::writeDeclarations(OS); 786 } 787 void writeDump(raw_ostream &OS) const override { 788 OS << " for (" << getAttrName() << "Attr::" << getLowerName() 789 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->" 790 << getLowerName() << "_end(); I != E; ++I) {\n"; 791 OS << " switch(*I) {\n"; 792 for (const auto &UI : uniques) { 793 OS << " case " << getAttrName() << "Attr::" << UI << ":\n"; 794 OS << " OS << \" " << UI << "\";\n"; 795 OS << " break;\n"; 796 } 797 OS << " }\n"; 798 OS << " }\n"; 799 } 800 void writePCHReadDecls(raw_ostream &OS) const override { 801 OS << " unsigned " << getLowerName() << "Size = Record[Idx++];\n"; 802 OS << " SmallVector<" << QualifiedTypeName << ", 4> " << getLowerName() 803 << ";\n"; 804 OS << " " << getLowerName() << ".reserve(" << getLowerName() 805 << "Size);\n"; 806 OS << " for (unsigned i = " << getLowerName() << "Size; i; --i)\n"; 807 OS << " " << getLowerName() << ".push_back(" << "static_cast<" 808 << QualifiedTypeName << ">(Record[Idx++]));\n"; 809 } 810 void writePCHWrite(raw_ostream &OS) const override { 811 OS << " Record.push_back(SA->" << getLowerName() << "_size());\n"; 812 OS << " for (" << getAttrName() << "Attr::" << getLowerName() 813 << "_iterator i = SA->" << getLowerName() << "_begin(), e = SA->" 814 << getLowerName() << "_end(); i != e; ++i)\n"; 815 OS << " " << WritePCHRecord(QualifiedTypeName, "(*i)"); 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 OS << " static const char *Convert" << type << "ToStr(" 833 << type << " Val) {\n" 834 << " switch(Val) {\n"; 835 std::set<std::string> Uniques; 836 for (size_t I = 0; I < enums.size(); ++I) { 837 if (Uniques.insert(enums[I]).second) 838 OS << " case " << getAttrName() << "Attr::" << enums[I] 839 << ": return \"" << values[I] << "\";\n"; 840 } 841 OS << " }\n" 842 << " llvm_unreachable(\"No enumerator with that value\");\n" 843 << " }\n"; 844 } 845 }; 846 847 class VersionArgument : public Argument { 848 public: 849 VersionArgument(const Record &Arg, StringRef Attr) 850 : Argument(Arg, Attr) 851 {} 852 853 void writeAccessors(raw_ostream &OS) const override { 854 OS << " VersionTuple get" << getUpperName() << "() const {\n"; 855 OS << " return " << getLowerName() << ";\n"; 856 OS << " }\n"; 857 OS << " void set" << getUpperName() 858 << "(ASTContext &C, VersionTuple V) {\n"; 859 OS << " " << getLowerName() << " = V;\n"; 860 OS << " }"; 861 } 862 void writeCloneArgs(raw_ostream &OS) const override { 863 OS << "get" << getUpperName() << "()"; 864 } 865 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 866 OS << "A->get" << getUpperName() << "()"; 867 } 868 void writeCtorInitializers(raw_ostream &OS) const override { 869 OS << getLowerName() << "(" << getUpperName() << ")"; 870 } 871 void writeCtorDefaultInitializers(raw_ostream &OS) const override { 872 OS << getLowerName() << "()"; 873 } 874 void writeCtorParameters(raw_ostream &OS) const override { 875 OS << "VersionTuple " << getUpperName(); 876 } 877 void writeDeclarations(raw_ostream &OS) const override { 878 OS << "VersionTuple " << getLowerName() << ";\n"; 879 } 880 void writePCHReadDecls(raw_ostream &OS) const override { 881 OS << " VersionTuple " << getLowerName() 882 << "= ReadVersionTuple(Record, Idx);\n"; 883 } 884 void writePCHReadArgs(raw_ostream &OS) const override { 885 OS << getLowerName(); 886 } 887 void writePCHWrite(raw_ostream &OS) const override { 888 OS << " AddVersionTuple(SA->get" << getUpperName() << "(), Record);\n"; 889 } 890 void writeValue(raw_ostream &OS) const override { 891 OS << getLowerName() << "=\" << get" << getUpperName() << "() << \""; 892 } 893 void writeDump(raw_ostream &OS) const override { 894 OS << " OS << \" \" << SA->get" << getUpperName() << "();\n"; 895 } 896 }; 897 898 class ExprArgument : public SimpleArgument { 899 public: 900 ExprArgument(const Record &Arg, StringRef Attr) 901 : SimpleArgument(Arg, Attr, "Expr *") 902 {} 903 904 void writeASTVisitorTraversal(raw_ostream &OS) const override { 905 OS << " if (!" 906 << "getDerived().TraverseStmt(A->get" << getUpperName() << "()))\n"; 907 OS << " return false;\n"; 908 } 909 910 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 911 OS << "tempInst" << getUpperName(); 912 } 913 914 void writeTemplateInstantiation(raw_ostream &OS) const override { 915 OS << " " << getType() << " tempInst" << getUpperName() << ";\n"; 916 OS << " {\n"; 917 OS << " EnterExpressionEvaluationContext " 918 << "Unevaluated(S, Sema::Unevaluated);\n"; 919 OS << " ExprResult " << "Result = S.SubstExpr(" 920 << "A->get" << getUpperName() << "(), TemplateArgs);\n"; 921 OS << " tempInst" << getUpperName() << " = " 922 << "Result.getAs<Expr>();\n"; 923 OS << " }\n"; 924 } 925 926 void writeDump(raw_ostream &OS) const override {} 927 928 void writeDumpChildren(raw_ostream &OS) const override { 929 OS << " dumpStmt(SA->get" << getUpperName() << "());\n"; 930 } 931 void writeHasChildren(raw_ostream &OS) const override { OS << "true"; } 932 }; 933 934 class VariadicExprArgument : public VariadicArgument { 935 public: 936 VariadicExprArgument(const Record &Arg, StringRef Attr) 937 : VariadicArgument(Arg, Attr, "Expr *") 938 {} 939 940 void writeASTVisitorTraversal(raw_ostream &OS) const override { 941 OS << " {\n"; 942 OS << " " << getType() << " *I = A->" << getLowerName() 943 << "_begin();\n"; 944 OS << " " << getType() << " *E = A->" << getLowerName() 945 << "_end();\n"; 946 OS << " for (; I != E; ++I) {\n"; 947 OS << " if (!getDerived().TraverseStmt(*I))\n"; 948 OS << " return false;\n"; 949 OS << " }\n"; 950 OS << " }\n"; 951 } 952 953 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 954 OS << "tempInst" << getUpperName() << ", " 955 << "A->" << getLowerName() << "_size()"; 956 } 957 958 void writeTemplateInstantiation(raw_ostream &OS) const override { 959 OS << " " << getType() << " *tempInst" << getUpperName() 960 << " = new (C, 16) " << getType() 961 << "[A->" << getLowerName() << "_size()];\n"; 962 OS << " {\n"; 963 OS << " EnterExpressionEvaluationContext " 964 << "Unevaluated(S, Sema::Unevaluated);\n"; 965 OS << " " << getType() << " *TI = tempInst" << getUpperName() 966 << ";\n"; 967 OS << " " << getType() << " *I = A->" << getLowerName() 968 << "_begin();\n"; 969 OS << " " << getType() << " *E = A->" << getLowerName() 970 << "_end();\n"; 971 OS << " for (; I != E; ++I, ++TI) {\n"; 972 OS << " ExprResult Result = S.SubstExpr(*I, TemplateArgs);\n"; 973 OS << " *TI = Result.getAs<Expr>();\n"; 974 OS << " }\n"; 975 OS << " }\n"; 976 } 977 978 void writeDump(raw_ostream &OS) const override {} 979 980 void writeDumpChildren(raw_ostream &OS) const override { 981 OS << " for (" << getAttrName() << "Attr::" << getLowerName() 982 << "_iterator I = SA->" << getLowerName() << "_begin(), E = SA->" 983 << getLowerName() << "_end(); I != E; ++I)\n"; 984 OS << " dumpStmt(*I);\n"; 985 } 986 987 void writeHasChildren(raw_ostream &OS) const override { 988 OS << "SA->" << getLowerName() << "_begin() != " 989 << "SA->" << getLowerName() << "_end()"; 990 } 991 }; 992 993 class VariadicStringArgument : public VariadicArgument { 994 public: 995 VariadicStringArgument(const Record &Arg, StringRef Attr) 996 : VariadicArgument(Arg, Attr, "std::string") 997 {} 998 void writeValueImpl(raw_ostream &OS) const override { 999 OS << " OS << \"\\\"\" << Val << \"\\\"\";\n"; 1000 } 1001 }; 1002 1003 class TypeArgument : public SimpleArgument { 1004 public: 1005 TypeArgument(const Record &Arg, StringRef Attr) 1006 : SimpleArgument(Arg, Attr, "TypeSourceInfo *") 1007 {} 1008 1009 void writeAccessors(raw_ostream &OS) const override { 1010 OS << " QualType get" << getUpperName() << "() const {\n"; 1011 OS << " return " << getLowerName() << "->getType();\n"; 1012 OS << " }"; 1013 OS << " " << getType() << " get" << getUpperName() << "Loc() const {\n"; 1014 OS << " return " << getLowerName() << ";\n"; 1015 OS << " }"; 1016 } 1017 void writeTemplateInstantiationArgs(raw_ostream &OS) const override { 1018 OS << "A->get" << getUpperName() << "Loc()"; 1019 } 1020 void writePCHWrite(raw_ostream &OS) const override { 1021 OS << " " << WritePCHRecord( 1022 getType(), "SA->get" + std::string(getUpperName()) + "Loc()"); 1023 } 1024 }; 1025 } // end anonymous namespace 1026 1027 static std::unique_ptr<Argument> 1028 createArgument(const Record &Arg, StringRef Attr, 1029 const Record *Search = nullptr) { 1030 if (!Search) 1031 Search = &Arg; 1032 1033 std::unique_ptr<Argument> Ptr; 1034 llvm::StringRef ArgName = Search->getName(); 1035 1036 if (ArgName == "AlignedArgument") 1037 Ptr = llvm::make_unique<AlignedArgument>(Arg, Attr); 1038 else if (ArgName == "EnumArgument") 1039 Ptr = llvm::make_unique<EnumArgument>(Arg, Attr); 1040 else if (ArgName == "ExprArgument") 1041 Ptr = llvm::make_unique<ExprArgument>(Arg, Attr); 1042 else if (ArgName == "FunctionArgument") 1043 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "FunctionDecl *"); 1044 else if (ArgName == "IdentifierArgument") 1045 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "IdentifierInfo *"); 1046 else if (ArgName == "DefaultBoolArgument") 1047 Ptr = llvm::make_unique<DefaultSimpleArgument>( 1048 Arg, Attr, "bool", Arg.getValueAsBit("Default")); 1049 else if (ArgName == "BoolArgument") 1050 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "bool"); 1051 else if (ArgName == "DefaultIntArgument") 1052 Ptr = llvm::make_unique<DefaultSimpleArgument>( 1053 Arg, Attr, "int", Arg.getValueAsInt("Default")); 1054 else if (ArgName == "IntArgument") 1055 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "int"); 1056 else if (ArgName == "StringArgument") 1057 Ptr = llvm::make_unique<StringArgument>(Arg, Attr); 1058 else if (ArgName == "TypeArgument") 1059 Ptr = llvm::make_unique<TypeArgument>(Arg, Attr); 1060 else if (ArgName == "UnsignedArgument") 1061 Ptr = llvm::make_unique<SimpleArgument>(Arg, Attr, "unsigned"); 1062 else if (ArgName == "VariadicUnsignedArgument") 1063 Ptr = llvm::make_unique<VariadicArgument>(Arg, Attr, "unsigned"); 1064 else if (ArgName == "VariadicStringArgument") 1065 Ptr = llvm::make_unique<VariadicStringArgument>(Arg, Attr); 1066 else if (ArgName == "VariadicEnumArgument") 1067 Ptr = llvm::make_unique<VariadicEnumArgument>(Arg, Attr); 1068 else if (ArgName == "VariadicExprArgument") 1069 Ptr = llvm::make_unique<VariadicExprArgument>(Arg, Attr); 1070 else if (ArgName == "VersionArgument") 1071 Ptr = llvm::make_unique<VersionArgument>(Arg, Attr); 1072 1073 if (!Ptr) { 1074 // Search in reverse order so that the most-derived type is handled first. 1075 ArrayRef<Record*> Bases = Search->getSuperClasses(); 1076 for (const auto *Base : llvm::make_range(Bases.rbegin(), Bases.rend())) { 1077 if ((Ptr = createArgument(Arg, Attr, Base))) 1078 break; 1079 } 1080 } 1081 1082 if (Ptr && Arg.getValueAsBit("Optional")) 1083 Ptr->setOptional(true); 1084 1085 if (Ptr && Arg.getValueAsBit("Fake")) 1086 Ptr->setFake(true); 1087 1088 return Ptr; 1089 } 1090 1091 static void writeAvailabilityValue(raw_ostream &OS) { 1092 OS << "\" << getPlatform()->getName();\n" 1093 << " if (!getIntroduced().empty()) OS << \", introduced=\" << getIntroduced();\n" 1094 << " if (!getDeprecated().empty()) OS << \", deprecated=\" << getDeprecated();\n" 1095 << " if (!getObsoleted().empty()) OS << \", obsoleted=\" << getObsoleted();\n" 1096 << " if (getUnavailable()) OS << \", unavailable\";\n" 1097 << " OS << \""; 1098 } 1099 1100 static void writeGetSpellingFunction(Record &R, raw_ostream &OS) { 1101 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R); 1102 1103 OS << "const char *" << R.getName() << "Attr::getSpelling() const {\n"; 1104 if (Spellings.empty()) { 1105 OS << " return \"(No spelling)\";\n}\n\n"; 1106 return; 1107 } 1108 1109 OS << " switch (SpellingListIndex) {\n" 1110 " default:\n" 1111 " llvm_unreachable(\"Unknown attribute spelling!\");\n" 1112 " return \"(No spelling)\";\n"; 1113 1114 for (unsigned I = 0; I < Spellings.size(); ++I) 1115 OS << " case " << I << ":\n" 1116 " return \"" << Spellings[I].name() << "\";\n"; 1117 // End of the switch statement. 1118 OS << " }\n"; 1119 // End of the getSpelling function. 1120 OS << "}\n\n"; 1121 } 1122 1123 static void 1124 writePrettyPrintFunction(Record &R, 1125 const std::vector<std::unique_ptr<Argument>> &Args, 1126 raw_ostream &OS) { 1127 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R); 1128 1129 OS << "void " << R.getName() << "Attr::printPretty(" 1130 << "raw_ostream &OS, const PrintingPolicy &Policy) const {\n"; 1131 1132 if (Spellings.empty()) { 1133 OS << "}\n\n"; 1134 return; 1135 } 1136 1137 OS << 1138 " switch (SpellingListIndex) {\n" 1139 " default:\n" 1140 " llvm_unreachable(\"Unknown attribute spelling!\");\n" 1141 " break;\n"; 1142 1143 for (unsigned I = 0; I < Spellings.size(); ++ I) { 1144 llvm::SmallString<16> Prefix; 1145 llvm::SmallString<8> Suffix; 1146 // The actual spelling of the name and namespace (if applicable) 1147 // of an attribute without considering prefix and suffix. 1148 llvm::SmallString<64> Spelling; 1149 std::string Name = Spellings[I].name(); 1150 std::string Variety = Spellings[I].variety(); 1151 1152 if (Variety == "GNU") { 1153 Prefix = " __attribute__(("; 1154 Suffix = "))"; 1155 } else if (Variety == "CXX11") { 1156 Prefix = " [["; 1157 Suffix = "]]"; 1158 std::string Namespace = Spellings[I].nameSpace(); 1159 if (!Namespace.empty()) { 1160 Spelling += Namespace; 1161 Spelling += "::"; 1162 } 1163 } else if (Variety == "Declspec") { 1164 Prefix = " __declspec("; 1165 Suffix = ")"; 1166 } else if (Variety == "Keyword") { 1167 Prefix = " "; 1168 Suffix = ""; 1169 } else if (Variety == "Pragma") { 1170 Prefix = "#pragma "; 1171 Suffix = "\n"; 1172 std::string Namespace = Spellings[I].nameSpace(); 1173 if (!Namespace.empty()) { 1174 Spelling += Namespace; 1175 Spelling += " "; 1176 } 1177 } else { 1178 llvm_unreachable("Unknown attribute syntax variety!"); 1179 } 1180 1181 Spelling += Name; 1182 1183 OS << 1184 " case " << I << " : {\n" 1185 " OS << \"" << Prefix << Spelling; 1186 1187 if (Variety == "Pragma") { 1188 OS << " \";\n"; 1189 OS << " printPrettyPragma(OS, Policy);\n"; 1190 OS << " OS << \"\\n\";"; 1191 OS << " break;\n"; 1192 OS << " }\n"; 1193 continue; 1194 } 1195 1196 // Fake arguments aren't part of the parsed form and should not be 1197 // pretty-printed. 1198 bool hasNonFakeArgs = false; 1199 for (const auto &arg : Args) { 1200 if (arg->isFake()) continue; 1201 hasNonFakeArgs = true; 1202 } 1203 1204 // FIXME: always printing the parenthesis isn't the correct behavior for 1205 // attributes which have optional arguments that were not provided. For 1206 // instance: __attribute__((aligned)) will be pretty printed as 1207 // __attribute__((aligned())). The logic should check whether there is only 1208 // a single argument, and if it is optional, whether it has been provided. 1209 if (hasNonFakeArgs) 1210 OS << "("; 1211 if (Spelling == "availability") { 1212 writeAvailabilityValue(OS); 1213 } else { 1214 unsigned index = 0; 1215 for (const auto &arg : Args) { 1216 if (arg->isFake()) continue; 1217 if (index++) OS << ", "; 1218 arg->writeValue(OS); 1219 } 1220 } 1221 1222 if (hasNonFakeArgs) 1223 OS << ")"; 1224 OS << Suffix + "\";\n"; 1225 1226 OS << 1227 " break;\n" 1228 " }\n"; 1229 } 1230 1231 // End of the switch statement. 1232 OS << "}\n"; 1233 // End of the print function. 1234 OS << "}\n\n"; 1235 } 1236 1237 /// \brief Return the index of a spelling in a spelling list. 1238 static unsigned 1239 getSpellingListIndex(const std::vector<FlattenedSpelling> &SpellingList, 1240 const FlattenedSpelling &Spelling) { 1241 assert(!SpellingList.empty() && "Spelling list is empty!"); 1242 1243 for (unsigned Index = 0; Index < SpellingList.size(); ++Index) { 1244 const FlattenedSpelling &S = SpellingList[Index]; 1245 if (S.variety() != Spelling.variety()) 1246 continue; 1247 if (S.nameSpace() != Spelling.nameSpace()) 1248 continue; 1249 if (S.name() != Spelling.name()) 1250 continue; 1251 1252 return Index; 1253 } 1254 1255 llvm_unreachable("Unknown spelling!"); 1256 } 1257 1258 static void writeAttrAccessorDefinition(const Record &R, raw_ostream &OS) { 1259 std::vector<Record*> Accessors = R.getValueAsListOfDefs("Accessors"); 1260 for (const auto *Accessor : Accessors) { 1261 std::string Name = Accessor->getValueAsString("Name"); 1262 std::vector<FlattenedSpelling> Spellings = 1263 GetFlattenedSpellings(*Accessor); 1264 std::vector<FlattenedSpelling> SpellingList = GetFlattenedSpellings(R); 1265 assert(!SpellingList.empty() && 1266 "Attribute with empty spelling list can't have accessors!"); 1267 1268 OS << " bool " << Name << "() const { return SpellingListIndex == "; 1269 for (unsigned Index = 0; Index < Spellings.size(); ++Index) { 1270 OS << getSpellingListIndex(SpellingList, Spellings[Index]); 1271 if (Index != Spellings.size() -1) 1272 OS << " ||\n SpellingListIndex == "; 1273 else 1274 OS << "; }\n"; 1275 } 1276 } 1277 } 1278 1279 static bool 1280 SpellingNamesAreCommon(const std::vector<FlattenedSpelling>& Spellings) { 1281 assert(!Spellings.empty() && "An empty list of spellings was provided"); 1282 std::string FirstName = NormalizeNameForSpellingComparison( 1283 Spellings.front().name()); 1284 for (const auto &Spelling : 1285 llvm::make_range(std::next(Spellings.begin()), Spellings.end())) { 1286 std::string Name = NormalizeNameForSpellingComparison(Spelling.name()); 1287 if (Name != FirstName) 1288 return false; 1289 } 1290 return true; 1291 } 1292 1293 typedef std::map<unsigned, std::string> SemanticSpellingMap; 1294 static std::string 1295 CreateSemanticSpellings(const std::vector<FlattenedSpelling> &Spellings, 1296 SemanticSpellingMap &Map) { 1297 // The enumerants are automatically generated based on the variety, 1298 // namespace (if present) and name for each attribute spelling. However, 1299 // care is taken to avoid trampling on the reserved namespace due to 1300 // underscores. 1301 std::string Ret(" enum Spelling {\n"); 1302 std::set<std::string> Uniques; 1303 unsigned Idx = 0; 1304 for (auto I = Spellings.begin(), E = Spellings.end(); I != E; ++I, ++Idx) { 1305 const FlattenedSpelling &S = *I; 1306 std::string Variety = S.variety(); 1307 std::string Spelling = S.name(); 1308 std::string Namespace = S.nameSpace(); 1309 std::string EnumName = ""; 1310 1311 EnumName += (Variety + "_"); 1312 if (!Namespace.empty()) 1313 EnumName += (NormalizeNameForSpellingComparison(Namespace).str() + 1314 "_"); 1315 EnumName += NormalizeNameForSpellingComparison(Spelling); 1316 1317 // Even if the name is not unique, this spelling index corresponds to a 1318 // particular enumerant name that we've calculated. 1319 Map[Idx] = EnumName; 1320 1321 // Since we have been stripping underscores to avoid trampling on the 1322 // reserved namespace, we may have inadvertently created duplicate 1323 // enumerant names. These duplicates are not considered part of the 1324 // semantic spelling, and can be elided. 1325 if (Uniques.find(EnumName) != Uniques.end()) 1326 continue; 1327 1328 Uniques.insert(EnumName); 1329 if (I != Spellings.begin()) 1330 Ret += ",\n"; 1331 // Duplicate spellings are not considered part of the semantic spelling 1332 // enumeration, but the spelling index and semantic spelling values are 1333 // meant to be equivalent, so we must specify a concrete value for each 1334 // enumerator. 1335 Ret += " " + EnumName + " = " + llvm::utostr(Idx); 1336 } 1337 Ret += "\n };\n\n"; 1338 return Ret; 1339 } 1340 1341 void WriteSemanticSpellingSwitch(const std::string &VarName, 1342 const SemanticSpellingMap &Map, 1343 raw_ostream &OS) { 1344 OS << " switch (" << VarName << ") {\n default: " 1345 << "llvm_unreachable(\"Unknown spelling list index\");\n"; 1346 for (const auto &I : Map) 1347 OS << " case " << I.first << ": return " << I.second << ";\n"; 1348 OS << " }\n"; 1349 } 1350 1351 // Emits the LateParsed property for attributes. 1352 static void emitClangAttrLateParsedList(RecordKeeper &Records, raw_ostream &OS) { 1353 OS << "#if defined(CLANG_ATTR_LATE_PARSED_LIST)\n"; 1354 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 1355 1356 for (const auto *Attr : Attrs) { 1357 bool LateParsed = Attr->getValueAsBit("LateParsed"); 1358 1359 if (LateParsed) { 1360 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr); 1361 1362 // FIXME: Handle non-GNU attributes 1363 for (const auto &I : Spellings) { 1364 if (I.variety() != "GNU") 1365 continue; 1366 OS << ".Case(\"" << I.name() << "\", " << LateParsed << ")\n"; 1367 } 1368 } 1369 } 1370 OS << "#endif // CLANG_ATTR_LATE_PARSED_LIST\n\n"; 1371 } 1372 1373 /// \brief Emits the first-argument-is-type property for attributes. 1374 static void emitClangAttrTypeArgList(RecordKeeper &Records, raw_ostream &OS) { 1375 OS << "#if defined(CLANG_ATTR_TYPE_ARG_LIST)\n"; 1376 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 1377 1378 for (const auto *Attr : Attrs) { 1379 // Determine whether the first argument is a type. 1380 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args"); 1381 if (Args.empty()) 1382 continue; 1383 1384 if (Args[0]->getSuperClasses().back()->getName() != "TypeArgument") 1385 continue; 1386 1387 // All these spellings take a single type argument. 1388 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr); 1389 std::set<std::string> Emitted; 1390 for (const auto &S : Spellings) { 1391 if (Emitted.insert(S.name()).second) 1392 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n"; 1393 } 1394 } 1395 OS << "#endif // CLANG_ATTR_TYPE_ARG_LIST\n\n"; 1396 } 1397 1398 /// \brief Emits the parse-arguments-in-unevaluated-context property for 1399 /// attributes. 1400 static void emitClangAttrArgContextList(RecordKeeper &Records, raw_ostream &OS) { 1401 OS << "#if defined(CLANG_ATTR_ARG_CONTEXT_LIST)\n"; 1402 ParsedAttrMap Attrs = getParsedAttrList(Records); 1403 for (const auto &I : Attrs) { 1404 const Record &Attr = *I.second; 1405 1406 if (!Attr.getValueAsBit("ParseArgumentsAsUnevaluated")) 1407 continue; 1408 1409 // All these spellings take are parsed unevaluated. 1410 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr); 1411 std::set<std::string> Emitted; 1412 for (const auto &S : Spellings) { 1413 if (Emitted.insert(S.name()).second) 1414 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n"; 1415 } 1416 } 1417 OS << "#endif // CLANG_ATTR_ARG_CONTEXT_LIST\n\n"; 1418 } 1419 1420 static bool isIdentifierArgument(Record *Arg) { 1421 return !Arg->getSuperClasses().empty() && 1422 llvm::StringSwitch<bool>(Arg->getSuperClasses().back()->getName()) 1423 .Case("IdentifierArgument", true) 1424 .Case("EnumArgument", true) 1425 .Case("VariadicEnumArgument", true) 1426 .Default(false); 1427 } 1428 1429 // Emits the first-argument-is-identifier property for attributes. 1430 static void emitClangAttrIdentifierArgList(RecordKeeper &Records, raw_ostream &OS) { 1431 OS << "#if defined(CLANG_ATTR_IDENTIFIER_ARG_LIST)\n"; 1432 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 1433 1434 for (const auto *Attr : Attrs) { 1435 // Determine whether the first argument is an identifier. 1436 std::vector<Record *> Args = Attr->getValueAsListOfDefs("Args"); 1437 if (Args.empty() || !isIdentifierArgument(Args[0])) 1438 continue; 1439 1440 // All these spellings take an identifier argument. 1441 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr); 1442 std::set<std::string> Emitted; 1443 for (const auto &S : Spellings) { 1444 if (Emitted.insert(S.name()).second) 1445 OS << ".Case(\"" << S.name() << "\", " << "true" << ")\n"; 1446 } 1447 } 1448 OS << "#endif // CLANG_ATTR_IDENTIFIER_ARG_LIST\n\n"; 1449 } 1450 1451 namespace clang { 1452 1453 // Emits the class definitions for attributes. 1454 void EmitClangAttrClass(RecordKeeper &Records, raw_ostream &OS) { 1455 emitSourceFileHeader("Attribute classes' definitions", OS); 1456 1457 OS << "#ifndef LLVM_CLANG_ATTR_CLASSES_INC\n"; 1458 OS << "#define LLVM_CLANG_ATTR_CLASSES_INC\n\n"; 1459 1460 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 1461 1462 for (const auto *Attr : Attrs) { 1463 const Record &R = *Attr; 1464 1465 // FIXME: Currently, documentation is generated as-needed due to the fact 1466 // that there is no way to allow a generated project "reach into" the docs 1467 // directory (for instance, it may be an out-of-tree build). However, we want 1468 // to ensure that every attribute has a Documentation field, and produce an 1469 // error if it has been neglected. Otherwise, the on-demand generation which 1470 // happens server-side will fail. This code is ensuring that functionality, 1471 // even though this Emitter doesn't technically need the documentation. 1472 // When attribute documentation can be generated as part of the build 1473 // itself, this code can be removed. 1474 (void)R.getValueAsListOfDefs("Documentation"); 1475 1476 if (!R.getValueAsBit("ASTNode")) 1477 continue; 1478 1479 ArrayRef<Record *> Supers = R.getSuperClasses(); 1480 assert(!Supers.empty() && "Forgot to specify a superclass for the attr"); 1481 std::string SuperName; 1482 for (const auto *Super : llvm::make_range(Supers.rbegin(), Supers.rend())) { 1483 const Record &R = *Super; 1484 if (R.getName() != "TargetSpecificAttr" && SuperName.empty()) 1485 SuperName = R.getName(); 1486 } 1487 1488 OS << "class " << R.getName() << "Attr : public " << SuperName << " {\n"; 1489 1490 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args"); 1491 std::vector<std::unique_ptr<Argument>> Args; 1492 Args.reserve(ArgRecords.size()); 1493 1494 bool HasOptArg = false; 1495 bool HasFakeArg = false; 1496 for (const auto *ArgRecord : ArgRecords) { 1497 Args.emplace_back(createArgument(*ArgRecord, R.getName())); 1498 Args.back()->writeDeclarations(OS); 1499 OS << "\n\n"; 1500 1501 // For these purposes, fake takes priority over optional. 1502 if (Args.back()->isFake()) { 1503 HasFakeArg = true; 1504 } else if (Args.back()->isOptional()) { 1505 HasOptArg = true; 1506 } 1507 } 1508 1509 OS << "\npublic:\n"; 1510 1511 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R); 1512 1513 // If there are zero or one spellings, all spelling-related functionality 1514 // can be elided. If all of the spellings share the same name, the spelling 1515 // functionality can also be elided. 1516 bool ElideSpelling = (Spellings.size() <= 1) || 1517 SpellingNamesAreCommon(Spellings); 1518 1519 // This maps spelling index values to semantic Spelling enumerants. 1520 SemanticSpellingMap SemanticToSyntacticMap; 1521 1522 if (!ElideSpelling) 1523 OS << CreateSemanticSpellings(Spellings, SemanticToSyntacticMap); 1524 1525 // Emit CreateImplicit factory methods. 1526 auto emitCreateImplicit = [&](bool emitFake) { 1527 OS << " static " << R.getName() << "Attr *CreateImplicit("; 1528 OS << "ASTContext &Ctx"; 1529 if (!ElideSpelling) 1530 OS << ", Spelling S"; 1531 for (auto const &ai : Args) { 1532 if (ai->isFake() && !emitFake) continue; 1533 OS << ", "; 1534 ai->writeCtorParameters(OS); 1535 } 1536 OS << ", SourceRange Loc = SourceRange()"; 1537 OS << ") {\n"; 1538 OS << " " << R.getName() << "Attr *A = new (Ctx) " << R.getName(); 1539 OS << "Attr(Loc, Ctx, "; 1540 for (auto const &ai : Args) { 1541 if (ai->isFake() && !emitFake) continue; 1542 ai->writeImplicitCtorArgs(OS); 1543 OS << ", "; 1544 } 1545 OS << (ElideSpelling ? "0" : "S") << ");\n"; 1546 OS << " A->setImplicit(true);\n"; 1547 OS << " return A;\n }\n\n"; 1548 }; 1549 1550 // Emit a CreateImplicit that takes all the arguments. 1551 emitCreateImplicit(true); 1552 1553 // Emit a CreateImplicit that takes all the non-fake arguments. 1554 if (HasFakeArg) { 1555 emitCreateImplicit(false); 1556 } 1557 1558 // Emit constructors. 1559 auto emitCtor = [&](bool emitOpt, bool emitFake) { 1560 auto shouldEmitArg = [=](const std::unique_ptr<Argument> &arg) { 1561 if (arg->isFake()) return emitFake; 1562 if (arg->isOptional()) return emitOpt; 1563 return true; 1564 }; 1565 1566 OS << " " << R.getName() << "Attr(SourceRange R, ASTContext &Ctx\n"; 1567 for (auto const &ai : Args) { 1568 if (!shouldEmitArg(ai)) continue; 1569 OS << " , "; 1570 ai->writeCtorParameters(OS); 1571 OS << "\n"; 1572 } 1573 1574 OS << " , "; 1575 OS << "unsigned SI\n"; 1576 1577 OS << " )\n"; 1578 OS << " : " << SuperName << "(attr::" << R.getName() << ", R, SI, " 1579 << R.getValueAsBit("LateParsed") << ", " 1580 << R.getValueAsBit("DuplicatesAllowedWhileMerging") << ")\n"; 1581 1582 for (auto const &ai : Args) { 1583 OS << " , "; 1584 if (!shouldEmitArg(ai)) { 1585 ai->writeCtorDefaultInitializers(OS); 1586 } else { 1587 ai->writeCtorInitializers(OS); 1588 } 1589 OS << "\n"; 1590 } 1591 1592 OS << " {\n"; 1593 1594 for (auto const &ai : Args) { 1595 if (!shouldEmitArg(ai)) continue; 1596 ai->writeCtorBody(OS); 1597 OS << "\n"; 1598 } 1599 OS << " }\n\n"; 1600 1601 }; 1602 1603 // Emit a constructor that includes all the arguments. 1604 // This is necessary for cloning. 1605 emitCtor(true, true); 1606 1607 // Emit a constructor that takes all the non-fake arguments. 1608 if (HasFakeArg) { 1609 emitCtor(true, false); 1610 } 1611 1612 // Emit a constructor that takes all the non-fake, non-optional arguments. 1613 if (HasOptArg) { 1614 emitCtor(false, false); 1615 } 1616 1617 OS << " " << R.getName() << "Attr *clone(ASTContext &C) const;\n"; 1618 OS << " void printPretty(raw_ostream &OS,\n" 1619 << " const PrintingPolicy &Policy) const;\n"; 1620 OS << " const char *getSpelling() const;\n"; 1621 1622 if (!ElideSpelling) { 1623 assert(!SemanticToSyntacticMap.empty() && "Empty semantic mapping list"); 1624 OS << " Spelling getSemanticSpelling() const {\n"; 1625 WriteSemanticSpellingSwitch("SpellingListIndex", SemanticToSyntacticMap, 1626 OS); 1627 OS << " }\n"; 1628 } 1629 1630 writeAttrAccessorDefinition(R, OS); 1631 1632 for (auto const &ai : Args) { 1633 ai->writeAccessors(OS); 1634 OS << "\n\n"; 1635 1636 // Don't write conversion routines for fake arguments. 1637 if (ai->isFake()) continue; 1638 1639 if (ai->isEnumArg()) 1640 static_cast<const EnumArgument *>(ai.get())->writeConversion(OS); 1641 else if (ai->isVariadicEnumArg()) 1642 static_cast<const VariadicEnumArgument *>(ai.get()) 1643 ->writeConversion(OS); 1644 } 1645 1646 OS << R.getValueAsString("AdditionalMembers"); 1647 OS << "\n\n"; 1648 1649 OS << " static bool classof(const Attr *A) { return A->getKind() == " 1650 << "attr::" << R.getName() << "; }\n"; 1651 1652 OS << "};\n\n"; 1653 } 1654 1655 OS << "#endif\n"; 1656 } 1657 1658 // Emits the class method definitions for attributes. 1659 void EmitClangAttrImpl(RecordKeeper &Records, raw_ostream &OS) { 1660 emitSourceFileHeader("Attribute classes' member function definitions", OS); 1661 1662 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 1663 1664 for (auto *Attr : Attrs) { 1665 Record &R = *Attr; 1666 1667 if (!R.getValueAsBit("ASTNode")) 1668 continue; 1669 1670 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args"); 1671 std::vector<std::unique_ptr<Argument>> Args; 1672 for (const auto *Arg : ArgRecords) 1673 Args.emplace_back(createArgument(*Arg, R.getName())); 1674 1675 for (auto const &ai : Args) 1676 ai->writeAccessorDefinitions(OS); 1677 1678 OS << R.getName() << "Attr *" << R.getName() 1679 << "Attr::clone(ASTContext &C) const {\n"; 1680 OS << " auto *A = new (C) " << R.getName() << "Attr(getLocation(), C"; 1681 for (auto const &ai : Args) { 1682 OS << ", "; 1683 ai->writeCloneArgs(OS); 1684 } 1685 OS << ", getSpellingListIndex());\n"; 1686 OS << " A->Inherited = Inherited;\n"; 1687 OS << " A->IsPackExpansion = IsPackExpansion;\n"; 1688 OS << " A->Implicit = Implicit;\n"; 1689 OS << " return A;\n}\n\n"; 1690 1691 writePrettyPrintFunction(R, Args, OS); 1692 writeGetSpellingFunction(R, OS); 1693 } 1694 1695 // Instead of relying on virtual dispatch we just create a huge dispatch 1696 // switch. This is both smaller and faster than virtual functions. 1697 auto EmitFunc = [&](const char *Method) { 1698 OS << " switch (getKind()) {\n"; 1699 for (const auto *Attr : Attrs) { 1700 const Record &R = *Attr; 1701 if (!R.getValueAsBit("ASTNode")) 1702 continue; 1703 1704 OS << " case attr::" << R.getName() << ":\n"; 1705 OS << " return cast<" << R.getName() << "Attr>(this)->" << Method 1706 << ";\n"; 1707 } 1708 OS << " case attr::NUM_ATTRS:\n"; 1709 OS << " break;\n"; 1710 OS << " }\n"; 1711 OS << " llvm_unreachable(\"Unexpected attribute kind!\");\n"; 1712 OS << "}\n\n"; 1713 }; 1714 1715 OS << "const char *Attr::getSpelling() const {\n"; 1716 EmitFunc("getSpelling()"); 1717 1718 OS << "Attr *Attr::clone(ASTContext &C) const {\n"; 1719 EmitFunc("clone(C)"); 1720 1721 OS << "void Attr::printPretty(raw_ostream &OS, " 1722 "const PrintingPolicy &Policy) const {\n"; 1723 EmitFunc("printPretty(OS, Policy)"); 1724 } 1725 1726 } // end namespace clang 1727 1728 static void EmitAttrList(raw_ostream &OS, StringRef Class, 1729 const std::vector<Record*> &AttrList) { 1730 std::vector<Record*>::const_iterator i = AttrList.begin(), e = AttrList.end(); 1731 1732 if (i != e) { 1733 // Move the end iterator back to emit the last attribute. 1734 for(--e; i != e; ++i) { 1735 if (!(*i)->getValueAsBit("ASTNode")) 1736 continue; 1737 1738 OS << Class << "(" << (*i)->getName() << ")\n"; 1739 } 1740 1741 OS << "LAST_" << Class << "(" << (*i)->getName() << ")\n\n"; 1742 } 1743 } 1744 1745 // Determines if an attribute has a Pragma spelling. 1746 static bool AttrHasPragmaSpelling(const Record *R) { 1747 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R); 1748 return std::find_if(Spellings.begin(), Spellings.end(), 1749 [](const FlattenedSpelling &S) { 1750 return S.variety() == "Pragma"; 1751 }) != Spellings.end(); 1752 } 1753 1754 namespace clang { 1755 // Emits the enumeration list for attributes. 1756 void EmitClangAttrList(RecordKeeper &Records, raw_ostream &OS) { 1757 emitSourceFileHeader("List of all attributes that Clang recognizes", OS); 1758 1759 OS << "#ifndef LAST_ATTR\n"; 1760 OS << "#define LAST_ATTR(NAME) ATTR(NAME)\n"; 1761 OS << "#endif\n\n"; 1762 1763 OS << "#ifndef INHERITABLE_ATTR\n"; 1764 OS << "#define INHERITABLE_ATTR(NAME) ATTR(NAME)\n"; 1765 OS << "#endif\n\n"; 1766 1767 OS << "#ifndef LAST_INHERITABLE_ATTR\n"; 1768 OS << "#define LAST_INHERITABLE_ATTR(NAME) INHERITABLE_ATTR(NAME)\n"; 1769 OS << "#endif\n\n"; 1770 1771 OS << "#ifndef INHERITABLE_PARAM_ATTR\n"; 1772 OS << "#define INHERITABLE_PARAM_ATTR(NAME) ATTR(NAME)\n"; 1773 OS << "#endif\n\n"; 1774 1775 OS << "#ifndef LAST_INHERITABLE_PARAM_ATTR\n"; 1776 OS << "#define LAST_INHERITABLE_PARAM_ATTR(NAME)" 1777 " INHERITABLE_PARAM_ATTR(NAME)\n"; 1778 OS << "#endif\n\n"; 1779 1780 OS << "#ifndef PRAGMA_SPELLING_ATTR\n"; 1781 OS << "#define PRAGMA_SPELLING_ATTR(NAME)\n"; 1782 OS << "#endif\n\n"; 1783 1784 OS << "#ifndef LAST_PRAGMA_SPELLING_ATTR\n"; 1785 OS << "#define LAST_PRAGMA_SPELLING_ATTR(NAME) PRAGMA_SPELLING_ATTR(NAME)\n"; 1786 OS << "#endif\n\n"; 1787 1788 Record *InhClass = Records.getClass("InheritableAttr"); 1789 Record *InhParamClass = Records.getClass("InheritableParamAttr"); 1790 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"), 1791 NonInhAttrs, InhAttrs, InhParamAttrs, PragmaAttrs; 1792 for (auto *Attr : Attrs) { 1793 if (!Attr->getValueAsBit("ASTNode")) 1794 continue; 1795 1796 if (AttrHasPragmaSpelling(Attr)) 1797 PragmaAttrs.push_back(Attr); 1798 1799 if (Attr->isSubClassOf(InhParamClass)) 1800 InhParamAttrs.push_back(Attr); 1801 else if (Attr->isSubClassOf(InhClass)) 1802 InhAttrs.push_back(Attr); 1803 else 1804 NonInhAttrs.push_back(Attr); 1805 } 1806 1807 EmitAttrList(OS, "PRAGMA_SPELLING_ATTR", PragmaAttrs); 1808 EmitAttrList(OS, "INHERITABLE_PARAM_ATTR", InhParamAttrs); 1809 EmitAttrList(OS, "INHERITABLE_ATTR", InhAttrs); 1810 EmitAttrList(OS, "ATTR", NonInhAttrs); 1811 1812 OS << "#undef LAST_ATTR\n"; 1813 OS << "#undef INHERITABLE_ATTR\n"; 1814 OS << "#undef LAST_INHERITABLE_ATTR\n"; 1815 OS << "#undef LAST_INHERITABLE_PARAM_ATTR\n"; 1816 OS << "#undef LAST_PRAGMA_ATTR\n"; 1817 OS << "#undef PRAGMA_SPELLING_ATTR\n"; 1818 OS << "#undef ATTR\n"; 1819 } 1820 1821 // Emits the code to read an attribute from a precompiled header. 1822 void EmitClangAttrPCHRead(RecordKeeper &Records, raw_ostream &OS) { 1823 emitSourceFileHeader("Attribute deserialization code", OS); 1824 1825 Record *InhClass = Records.getClass("InheritableAttr"); 1826 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), 1827 ArgRecords; 1828 std::vector<std::unique_ptr<Argument>> Args; 1829 1830 OS << " switch (Kind) {\n"; 1831 OS << " default:\n"; 1832 OS << " llvm_unreachable(\"Unknown attribute!\");\n"; 1833 for (const auto *Attr : Attrs) { 1834 const Record &R = *Attr; 1835 if (!R.getValueAsBit("ASTNode")) 1836 continue; 1837 1838 OS << " case attr::" << R.getName() << ": {\n"; 1839 if (R.isSubClassOf(InhClass)) 1840 OS << " bool isInherited = Record[Idx++];\n"; 1841 OS << " bool isImplicit = Record[Idx++];\n"; 1842 OS << " unsigned Spelling = Record[Idx++];\n"; 1843 ArgRecords = R.getValueAsListOfDefs("Args"); 1844 Args.clear(); 1845 for (const auto *Arg : ArgRecords) { 1846 Args.emplace_back(createArgument(*Arg, R.getName())); 1847 Args.back()->writePCHReadDecls(OS); 1848 } 1849 OS << " New = new (Context) " << R.getName() << "Attr(Range, Context"; 1850 for (auto const &ri : Args) { 1851 OS << ", "; 1852 ri->writePCHReadArgs(OS); 1853 } 1854 OS << ", Spelling);\n"; 1855 if (R.isSubClassOf(InhClass)) 1856 OS << " cast<InheritableAttr>(New)->setInherited(isInherited);\n"; 1857 OS << " New->setImplicit(isImplicit);\n"; 1858 OS << " break;\n"; 1859 OS << " }\n"; 1860 } 1861 OS << " }\n"; 1862 } 1863 1864 // Emits the code to write an attribute to a precompiled header. 1865 void EmitClangAttrPCHWrite(RecordKeeper &Records, raw_ostream &OS) { 1866 emitSourceFileHeader("Attribute serialization code", OS); 1867 1868 Record *InhClass = Records.getClass("InheritableAttr"); 1869 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args; 1870 1871 OS << " switch (A->getKind()) {\n"; 1872 OS << " default:\n"; 1873 OS << " llvm_unreachable(\"Unknown attribute kind!\");\n"; 1874 OS << " break;\n"; 1875 for (const auto *Attr : Attrs) { 1876 const Record &R = *Attr; 1877 if (!R.getValueAsBit("ASTNode")) 1878 continue; 1879 OS << " case attr::" << R.getName() << ": {\n"; 1880 Args = R.getValueAsListOfDefs("Args"); 1881 if (R.isSubClassOf(InhClass) || !Args.empty()) 1882 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName() 1883 << "Attr>(A);\n"; 1884 if (R.isSubClassOf(InhClass)) 1885 OS << " Record.push_back(SA->isInherited());\n"; 1886 OS << " Record.push_back(A->isImplicit());\n"; 1887 OS << " Record.push_back(A->getSpellingListIndex());\n"; 1888 1889 for (const auto *Arg : Args) 1890 createArgument(*Arg, R.getName())->writePCHWrite(OS); 1891 OS << " break;\n"; 1892 OS << " }\n"; 1893 } 1894 OS << " }\n"; 1895 } 1896 1897 // Generate a conditional expression to check if the current target satisfies 1898 // the conditions for a TargetSpecificAttr record, and append the code for 1899 // those checks to the Test string. If the FnName string pointer is non-null, 1900 // append a unique suffix to distinguish this set of target checks from other 1901 // TargetSpecificAttr records. 1902 static void GenerateTargetSpecificAttrChecks(const Record *R, 1903 std::vector<std::string> &Arches, 1904 std::string &Test, 1905 std::string *FnName) { 1906 // It is assumed that there will be an llvm::Triple object 1907 // named "T" and a TargetInfo object named "Target" within 1908 // scope that can be used to determine whether the attribute exists in 1909 // a given target. 1910 Test += "("; 1911 1912 for (auto I = Arches.begin(), E = Arches.end(); I != E; ++I) { 1913 std::string Part = *I; 1914 Test += "T.getArch() == llvm::Triple::" + Part; 1915 if (I + 1 != E) 1916 Test += " || "; 1917 if (FnName) 1918 *FnName += Part; 1919 } 1920 Test += ")"; 1921 1922 // If the attribute is specific to particular OSes, check those. 1923 if (!R->isValueUnset("OSes")) { 1924 // We know that there was at least one arch test, so we need to and in the 1925 // OS tests. 1926 Test += " && ("; 1927 std::vector<std::string> OSes = R->getValueAsListOfStrings("OSes"); 1928 for (auto I = OSes.begin(), E = OSes.end(); I != E; ++I) { 1929 std::string Part = *I; 1930 1931 Test += "T.getOS() == llvm::Triple::" + Part; 1932 if (I + 1 != E) 1933 Test += " || "; 1934 if (FnName) 1935 *FnName += Part; 1936 } 1937 Test += ")"; 1938 } 1939 1940 // If one or more CXX ABIs are specified, check those as well. 1941 if (!R->isValueUnset("CXXABIs")) { 1942 Test += " && ("; 1943 std::vector<std::string> CXXABIs = R->getValueAsListOfStrings("CXXABIs"); 1944 for (auto I = CXXABIs.begin(), E = CXXABIs.end(); I != E; ++I) { 1945 std::string Part = *I; 1946 Test += "Target.getCXXABI().getKind() == TargetCXXABI::" + Part; 1947 if (I + 1 != E) 1948 Test += " || "; 1949 if (FnName) 1950 *FnName += Part; 1951 } 1952 Test += ")"; 1953 } 1954 } 1955 1956 static void GenerateHasAttrSpellingStringSwitch( 1957 const std::vector<Record *> &Attrs, raw_ostream &OS, 1958 const std::string &Variety = "", const std::string &Scope = "") { 1959 for (const auto *Attr : Attrs) { 1960 // C++11-style attributes have specific version information associated with 1961 // them. If the attribute has no scope, the version information must not 1962 // have the default value (1), as that's incorrect. Instead, the unscoped 1963 // attribute version information should be taken from the SD-6 standing 1964 // document, which can be found at: 1965 // https://isocpp.org/std/standing-documents/sd-6-sg10-feature-test-recommendations 1966 int Version = 1; 1967 1968 if (Variety == "CXX11") { 1969 std::vector<Record *> Spellings = Attr->getValueAsListOfDefs("Spellings"); 1970 for (const auto &Spelling : Spellings) { 1971 if (Spelling->getValueAsString("Variety") == "CXX11") { 1972 Version = static_cast<int>(Spelling->getValueAsInt("Version")); 1973 if (Scope.empty() && Version == 1) 1974 PrintError(Spelling->getLoc(), "C++ standard attributes must " 1975 "have valid version information."); 1976 break; 1977 } 1978 } 1979 } 1980 1981 std::string Test; 1982 if (Attr->isSubClassOf("TargetSpecificAttr")) { 1983 const Record *R = Attr->getValueAsDef("Target"); 1984 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches"); 1985 GenerateTargetSpecificAttrChecks(R, Arches, Test, nullptr); 1986 1987 // If this is the C++11 variety, also add in the LangOpts test. 1988 if (Variety == "CXX11") 1989 Test += " && LangOpts.CPlusPlus11"; 1990 } else if (Variety == "CXX11") 1991 // C++11 mode should be checked against LangOpts, which is presumed to be 1992 // present in the caller. 1993 Test = "LangOpts.CPlusPlus11"; 1994 1995 std::string TestStr = 1996 !Test.empty() ? Test + " ? " + llvm::itostr(Version) + " : 0" : "1"; 1997 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Attr); 1998 for (const auto &S : Spellings) 1999 if (Variety.empty() || (Variety == S.variety() && 2000 (Scope.empty() || Scope == S.nameSpace()))) 2001 OS << " .Case(\"" << S.name() << "\", " << TestStr << ")\n"; 2002 } 2003 OS << " .Default(0);\n"; 2004 } 2005 2006 // Emits the list of spellings for attributes. 2007 void EmitClangAttrHasAttrImpl(RecordKeeper &Records, raw_ostream &OS) { 2008 emitSourceFileHeader("Code to implement the __has_attribute logic", OS); 2009 2010 // Separate all of the attributes out into four group: generic, C++11, GNU, 2011 // and declspecs. Then generate a big switch statement for each of them. 2012 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 2013 std::vector<Record *> Declspec, GNU, Pragma; 2014 std::map<std::string, std::vector<Record *>> CXX; 2015 2016 // Walk over the list of all attributes, and split them out based on the 2017 // spelling variety. 2018 for (auto *R : Attrs) { 2019 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*R); 2020 for (const auto &SI : Spellings) { 2021 std::string Variety = SI.variety(); 2022 if (Variety == "GNU") 2023 GNU.push_back(R); 2024 else if (Variety == "Declspec") 2025 Declspec.push_back(R); 2026 else if (Variety == "CXX11") 2027 CXX[SI.nameSpace()].push_back(R); 2028 else if (Variety == "Pragma") 2029 Pragma.push_back(R); 2030 } 2031 } 2032 2033 OS << "const llvm::Triple &T = Target.getTriple();\n"; 2034 OS << "switch (Syntax) {\n"; 2035 OS << "case AttrSyntax::GNU:\n"; 2036 OS << " return llvm::StringSwitch<int>(Name)\n"; 2037 GenerateHasAttrSpellingStringSwitch(GNU, OS, "GNU"); 2038 OS << "case AttrSyntax::Declspec:\n"; 2039 OS << " return llvm::StringSwitch<int>(Name)\n"; 2040 GenerateHasAttrSpellingStringSwitch(Declspec, OS, "Declspec"); 2041 OS << "case AttrSyntax::Pragma:\n"; 2042 OS << " return llvm::StringSwitch<int>(Name)\n"; 2043 GenerateHasAttrSpellingStringSwitch(Pragma, OS, "Pragma"); 2044 OS << "case AttrSyntax::CXX: {\n"; 2045 // C++11-style attributes are further split out based on the Scope. 2046 for (std::map<std::string, std::vector<Record *>>::iterator I = CXX.begin(), 2047 E = CXX.end(); 2048 I != E; ++I) { 2049 if (I != CXX.begin()) 2050 OS << " else "; 2051 if (I->first.empty()) 2052 OS << "if (!Scope || Scope->getName() == \"\") {\n"; 2053 else 2054 OS << "if (Scope->getName() == \"" << I->first << "\") {\n"; 2055 OS << " return llvm::StringSwitch<int>(Name)\n"; 2056 GenerateHasAttrSpellingStringSwitch(I->second, OS, "CXX11", I->first); 2057 OS << "}"; 2058 } 2059 OS << "\n}\n"; 2060 OS << "}\n"; 2061 } 2062 2063 void EmitClangAttrSpellingListIndex(RecordKeeper &Records, raw_ostream &OS) { 2064 emitSourceFileHeader("Code to translate different attribute spellings " 2065 "into internal identifiers", OS); 2066 2067 OS << 2068 " switch (AttrKind) {\n" 2069 " default:\n" 2070 " llvm_unreachable(\"Unknown attribute kind!\");\n" 2071 " break;\n"; 2072 2073 ParsedAttrMap Attrs = getParsedAttrList(Records); 2074 for (const auto &I : Attrs) { 2075 const Record &R = *I.second; 2076 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R); 2077 OS << " case AT_" << I.first << ": {\n"; 2078 for (unsigned I = 0; I < Spellings.size(); ++ I) { 2079 OS << " if (Name == \"" << Spellings[I].name() << "\" && " 2080 << "SyntaxUsed == " 2081 << StringSwitch<unsigned>(Spellings[I].variety()) 2082 .Case("GNU", 0) 2083 .Case("CXX11", 1) 2084 .Case("Declspec", 2) 2085 .Case("Keyword", 3) 2086 .Case("Pragma", 4) 2087 .Default(0) 2088 << " && Scope == \"" << Spellings[I].nameSpace() << "\")\n" 2089 << " return " << I << ";\n"; 2090 } 2091 2092 OS << " break;\n"; 2093 OS << " }\n"; 2094 } 2095 2096 OS << " }\n"; 2097 OS << " return 0;\n"; 2098 } 2099 2100 // Emits code used by RecursiveASTVisitor to visit attributes 2101 void EmitClangAttrASTVisitor(RecordKeeper &Records, raw_ostream &OS) { 2102 emitSourceFileHeader("Used by RecursiveASTVisitor to visit attributes.", OS); 2103 2104 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 2105 2106 // Write method declarations for Traverse* methods. 2107 // We emit this here because we only generate methods for attributes that 2108 // are declared as ASTNodes. 2109 OS << "#ifdef ATTR_VISITOR_DECLS_ONLY\n\n"; 2110 for (const auto *Attr : Attrs) { 2111 const Record &R = *Attr; 2112 if (!R.getValueAsBit("ASTNode")) 2113 continue; 2114 OS << " bool Traverse" 2115 << R.getName() << "Attr(" << R.getName() << "Attr *A);\n"; 2116 OS << " bool Visit" 2117 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n" 2118 << " return true; \n" 2119 << " }\n"; 2120 } 2121 OS << "\n#else // ATTR_VISITOR_DECLS_ONLY\n\n"; 2122 2123 // Write individual Traverse* methods for each attribute class. 2124 for (const auto *Attr : Attrs) { 2125 const Record &R = *Attr; 2126 if (!R.getValueAsBit("ASTNode")) 2127 continue; 2128 2129 OS << "template <typename Derived>\n" 2130 << "bool VISITORCLASS<Derived>::Traverse" 2131 << R.getName() << "Attr(" << R.getName() << "Attr *A) {\n" 2132 << " if (!getDerived().VisitAttr(A))\n" 2133 << " return false;\n" 2134 << " if (!getDerived().Visit" << R.getName() << "Attr(A))\n" 2135 << " return false;\n"; 2136 2137 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args"); 2138 for (const auto *Arg : ArgRecords) 2139 createArgument(*Arg, R.getName())->writeASTVisitorTraversal(OS); 2140 2141 OS << " return true;\n"; 2142 OS << "}\n\n"; 2143 } 2144 2145 // Write generic Traverse routine 2146 OS << "template <typename Derived>\n" 2147 << "bool VISITORCLASS<Derived>::TraverseAttr(Attr *A) {\n" 2148 << " if (!A)\n" 2149 << " return true;\n" 2150 << "\n" 2151 << " switch (A->getKind()) {\n" 2152 << " default:\n" 2153 << " return true;\n"; 2154 2155 for (const auto *Attr : Attrs) { 2156 const Record &R = *Attr; 2157 if (!R.getValueAsBit("ASTNode")) 2158 continue; 2159 2160 OS << " case attr::" << R.getName() << ":\n" 2161 << " return getDerived().Traverse" << R.getName() << "Attr(" 2162 << "cast<" << R.getName() << "Attr>(A));\n"; 2163 } 2164 OS << " }\n"; // end case 2165 OS << "}\n"; // end function 2166 OS << "#endif // ATTR_VISITOR_DECLS_ONLY\n"; 2167 } 2168 2169 // Emits code to instantiate dependent attributes on templates. 2170 void EmitClangAttrTemplateInstantiate(RecordKeeper &Records, raw_ostream &OS) { 2171 emitSourceFileHeader("Template instantiation code for attributes", OS); 2172 2173 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"); 2174 2175 OS << "namespace clang {\n" 2176 << "namespace sema {\n\n" 2177 << "Attr *instantiateTemplateAttribute(const Attr *At, ASTContext &C, " 2178 << "Sema &S,\n" 2179 << " const MultiLevelTemplateArgumentList &TemplateArgs) {\n" 2180 << " switch (At->getKind()) {\n" 2181 << " default:\n" 2182 << " break;\n"; 2183 2184 for (const auto *Attr : Attrs) { 2185 const Record &R = *Attr; 2186 if (!R.getValueAsBit("ASTNode")) 2187 continue; 2188 2189 OS << " case attr::" << R.getName() << ": {\n"; 2190 bool ShouldClone = R.getValueAsBit("Clone"); 2191 2192 if (!ShouldClone) { 2193 OS << " return nullptr;\n"; 2194 OS << " }\n"; 2195 continue; 2196 } 2197 2198 OS << " const " << R.getName() << "Attr *A = cast<" 2199 << R.getName() << "Attr>(At);\n"; 2200 bool TDependent = R.getValueAsBit("TemplateDependent"); 2201 2202 if (!TDependent) { 2203 OS << " return A->clone(C);\n"; 2204 OS << " }\n"; 2205 continue; 2206 } 2207 2208 std::vector<Record*> ArgRecords = R.getValueAsListOfDefs("Args"); 2209 std::vector<std::unique_ptr<Argument>> Args; 2210 Args.reserve(ArgRecords.size()); 2211 2212 for (const auto *ArgRecord : ArgRecords) 2213 Args.emplace_back(createArgument(*ArgRecord, R.getName())); 2214 2215 for (auto const &ai : Args) 2216 ai->writeTemplateInstantiation(OS); 2217 2218 OS << " return new (C) " << R.getName() << "Attr(A->getLocation(), C"; 2219 for (auto const &ai : Args) { 2220 OS << ", "; 2221 ai->writeTemplateInstantiationArgs(OS); 2222 } 2223 OS << ", A->getSpellingListIndex());\n }\n"; 2224 } 2225 OS << " } // end switch\n" 2226 << " llvm_unreachable(\"Unknown attribute!\");\n" 2227 << " return nullptr;\n" 2228 << "}\n\n" 2229 << "} // end namespace sema\n" 2230 << "} // end namespace clang\n"; 2231 } 2232 2233 // Emits the list of parsed attributes. 2234 void EmitClangAttrParsedAttrList(RecordKeeper &Records, raw_ostream &OS) { 2235 emitSourceFileHeader("List of all attributes that Clang recognizes", OS); 2236 2237 OS << "#ifndef PARSED_ATTR\n"; 2238 OS << "#define PARSED_ATTR(NAME) NAME\n"; 2239 OS << "#endif\n\n"; 2240 2241 ParsedAttrMap Names = getParsedAttrList(Records); 2242 for (const auto &I : Names) { 2243 OS << "PARSED_ATTR(" << I.first << ")\n"; 2244 } 2245 } 2246 2247 static bool isArgVariadic(const Record &R, StringRef AttrName) { 2248 return createArgument(R, AttrName)->isVariadic(); 2249 } 2250 2251 static void emitArgInfo(const Record &R, std::stringstream &OS) { 2252 // This function will count the number of arguments specified for the 2253 // attribute and emit the number of required arguments followed by the 2254 // number of optional arguments. 2255 std::vector<Record *> Args = R.getValueAsListOfDefs("Args"); 2256 unsigned ArgCount = 0, OptCount = 0; 2257 bool HasVariadic = false; 2258 for (const auto *Arg : Args) { 2259 Arg->getValueAsBit("Optional") ? ++OptCount : ++ArgCount; 2260 if (!HasVariadic && isArgVariadic(*Arg, R.getName())) 2261 HasVariadic = true; 2262 } 2263 2264 // If there is a variadic argument, we will set the optional argument count 2265 // to its largest value. Since it's currently a 4-bit number, we set it to 15. 2266 OS << ArgCount << ", " << (HasVariadic ? 15 : OptCount); 2267 } 2268 2269 static void GenerateDefaultAppertainsTo(raw_ostream &OS) { 2270 OS << "static bool defaultAppertainsTo(Sema &, const AttributeList &,"; 2271 OS << "const Decl *) {\n"; 2272 OS << " return true;\n"; 2273 OS << "}\n\n"; 2274 } 2275 2276 static std::string CalculateDiagnostic(const Record &S) { 2277 // If the SubjectList object has a custom diagnostic associated with it, 2278 // return that directly. 2279 std::string CustomDiag = S.getValueAsString("CustomDiag"); 2280 if (!CustomDiag.empty()) 2281 return CustomDiag; 2282 2283 // Given the list of subjects, determine what diagnostic best fits. 2284 enum { 2285 Func = 1U << 0, 2286 Var = 1U << 1, 2287 ObjCMethod = 1U << 2, 2288 Param = 1U << 3, 2289 Class = 1U << 4, 2290 GenericRecord = 1U << 5, 2291 Type = 1U << 6, 2292 ObjCIVar = 1U << 7, 2293 ObjCProp = 1U << 8, 2294 ObjCInterface = 1U << 9, 2295 Block = 1U << 10, 2296 Namespace = 1U << 11, 2297 Field = 1U << 12, 2298 CXXMethod = 1U << 13, 2299 ObjCProtocol = 1U << 14, 2300 Enum = 1U << 15 2301 }; 2302 uint32_t SubMask = 0; 2303 2304 std::vector<Record *> Subjects = S.getValueAsListOfDefs("Subjects"); 2305 for (const auto *Subject : Subjects) { 2306 const Record &R = *Subject; 2307 std::string Name; 2308 2309 if (R.isSubClassOf("SubsetSubject")) { 2310 PrintError(R.getLoc(), "SubsetSubjects should use a custom diagnostic"); 2311 // As a fallback, look through the SubsetSubject to see what its base 2312 // type is, and use that. This needs to be updated if SubsetSubjects 2313 // are allowed within other SubsetSubjects. 2314 Name = R.getValueAsDef("Base")->getName(); 2315 } else 2316 Name = R.getName(); 2317 2318 uint32_t V = StringSwitch<uint32_t>(Name) 2319 .Case("Function", Func) 2320 .Case("Var", Var) 2321 .Case("ObjCMethod", ObjCMethod) 2322 .Case("ParmVar", Param) 2323 .Case("TypedefName", Type) 2324 .Case("ObjCIvar", ObjCIVar) 2325 .Case("ObjCProperty", ObjCProp) 2326 .Case("Record", GenericRecord) 2327 .Case("ObjCInterface", ObjCInterface) 2328 .Case("ObjCProtocol", ObjCProtocol) 2329 .Case("Block", Block) 2330 .Case("CXXRecord", Class) 2331 .Case("Namespace", Namespace) 2332 .Case("Field", Field) 2333 .Case("CXXMethod", CXXMethod) 2334 .Case("Enum", Enum) 2335 .Default(0); 2336 if (!V) { 2337 // Something wasn't in our mapping, so be helpful and let the developer 2338 // know about it. 2339 PrintFatalError(R.getLoc(), "Unknown subject type: " + R.getName()); 2340 return ""; 2341 } 2342 2343 SubMask |= V; 2344 } 2345 2346 switch (SubMask) { 2347 // For the simple cases where there's only a single entry in the mask, we 2348 // don't have to resort to bit fiddling. 2349 case Func: return "ExpectedFunction"; 2350 case Var: return "ExpectedVariable"; 2351 case Param: return "ExpectedParameter"; 2352 case Class: return "ExpectedClass"; 2353 case Enum: return "ExpectedEnum"; 2354 case CXXMethod: 2355 // FIXME: Currently, this maps to ExpectedMethod based on existing code, 2356 // but should map to something a bit more accurate at some point. 2357 case ObjCMethod: return "ExpectedMethod"; 2358 case Type: return "ExpectedType"; 2359 case ObjCInterface: return "ExpectedObjectiveCInterface"; 2360 case ObjCProtocol: return "ExpectedObjectiveCProtocol"; 2361 2362 // "GenericRecord" means struct, union or class; check the language options 2363 // and if not compiling for C++, strip off the class part. Note that this 2364 // relies on the fact that the context for this declares "Sema &S". 2365 case GenericRecord: 2366 return "(S.getLangOpts().CPlusPlus ? ExpectedStructOrUnionOrClass : " 2367 "ExpectedStructOrUnion)"; 2368 case Func | ObjCMethod | Block: return "ExpectedFunctionMethodOrBlock"; 2369 case Func | ObjCMethod | Class: return "ExpectedFunctionMethodOrClass"; 2370 case Func | Param: 2371 case Func | ObjCMethod | Param: return "ExpectedFunctionMethodOrParameter"; 2372 case Func | ObjCMethod: return "ExpectedFunctionOrMethod"; 2373 case Func | Var: return "ExpectedVariableOrFunction"; 2374 2375 // If not compiling for C++, the class portion does not apply. 2376 case Func | Var | Class: 2377 return "(S.getLangOpts().CPlusPlus ? ExpectedFunctionVariableOrClass : " 2378 "ExpectedVariableOrFunction)"; 2379 2380 case ObjCMethod | ObjCProp: return "ExpectedMethodOrProperty"; 2381 case ObjCProtocol | ObjCInterface: 2382 return "ExpectedObjectiveCInterfaceOrProtocol"; 2383 case Field | Var: return "ExpectedFieldOrGlobalVar"; 2384 } 2385 2386 PrintFatalError(S.getLoc(), 2387 "Could not deduce diagnostic argument for Attr subjects"); 2388 2389 return ""; 2390 } 2391 2392 static std::string GetSubjectWithSuffix(const Record *R) { 2393 std::string B = R->getName(); 2394 if (B == "DeclBase") 2395 return "Decl"; 2396 return B + "Decl"; 2397 } 2398 2399 static std::string GenerateCustomAppertainsTo(const Record &Subject, 2400 raw_ostream &OS) { 2401 std::string FnName = "is" + Subject.getName(); 2402 2403 // If this code has already been generated, simply return the previous 2404 // instance of it. 2405 static std::set<std::string> CustomSubjectSet; 2406 std::set<std::string>::iterator I = CustomSubjectSet.find(FnName); 2407 if (I != CustomSubjectSet.end()) 2408 return *I; 2409 2410 Record *Base = Subject.getValueAsDef("Base"); 2411 2412 // Not currently support custom subjects within custom subjects. 2413 if (Base->isSubClassOf("SubsetSubject")) { 2414 PrintFatalError(Subject.getLoc(), 2415 "SubsetSubjects within SubsetSubjects is not supported"); 2416 return ""; 2417 } 2418 2419 OS << "static bool " << FnName << "(const Decl *D) {\n"; 2420 OS << " if (const " << GetSubjectWithSuffix(Base) << " *S = dyn_cast<"; 2421 OS << GetSubjectWithSuffix(Base); 2422 OS << ">(D))\n"; 2423 OS << " return " << Subject.getValueAsString("CheckCode") << ";\n"; 2424 OS << " return false;\n"; 2425 OS << "}\n\n"; 2426 2427 CustomSubjectSet.insert(FnName); 2428 return FnName; 2429 } 2430 2431 static std::string GenerateAppertainsTo(const Record &Attr, raw_ostream &OS) { 2432 // If the attribute does not contain a Subjects definition, then use the 2433 // default appertainsTo logic. 2434 if (Attr.isValueUnset("Subjects")) 2435 return "defaultAppertainsTo"; 2436 2437 const Record *SubjectObj = Attr.getValueAsDef("Subjects"); 2438 std::vector<Record*> Subjects = SubjectObj->getValueAsListOfDefs("Subjects"); 2439 2440 // If the list of subjects is empty, it is assumed that the attribute 2441 // appertains to everything. 2442 if (Subjects.empty()) 2443 return "defaultAppertainsTo"; 2444 2445 bool Warn = SubjectObj->getValueAsDef("Diag")->getValueAsBit("Warn"); 2446 2447 // Otherwise, generate an appertainsTo check specific to this attribute which 2448 // checks all of the given subjects against the Decl passed in. Return the 2449 // name of that check to the caller. 2450 std::string FnName = "check" + Attr.getName() + "AppertainsTo"; 2451 std::stringstream SS; 2452 SS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr, "; 2453 SS << "const Decl *D) {\n"; 2454 SS << " if ("; 2455 for (auto I = Subjects.begin(), E = Subjects.end(); I != E; ++I) { 2456 // If the subject has custom code associated with it, generate a function 2457 // for it. The function cannot be inlined into this check (yet) because it 2458 // requires the subject to be of a specific type, and were that information 2459 // inlined here, it would not support an attribute with multiple custom 2460 // subjects. 2461 if ((*I)->isSubClassOf("SubsetSubject")) { 2462 SS << "!" << GenerateCustomAppertainsTo(**I, OS) << "(D)"; 2463 } else { 2464 SS << "!isa<" << GetSubjectWithSuffix(*I) << ">(D)"; 2465 } 2466 2467 if (I + 1 != E) 2468 SS << " && "; 2469 } 2470 SS << ") {\n"; 2471 SS << " S.Diag(Attr.getLoc(), diag::"; 2472 SS << (Warn ? "warn_attribute_wrong_decl_type" : 2473 "err_attribute_wrong_decl_type"); 2474 SS << ")\n"; 2475 SS << " << Attr.getName() << "; 2476 SS << CalculateDiagnostic(*SubjectObj) << ";\n"; 2477 SS << " return false;\n"; 2478 SS << " }\n"; 2479 SS << " return true;\n"; 2480 SS << "}\n\n"; 2481 2482 OS << SS.str(); 2483 return FnName; 2484 } 2485 2486 static void GenerateDefaultLangOptRequirements(raw_ostream &OS) { 2487 OS << "static bool defaultDiagnoseLangOpts(Sema &, "; 2488 OS << "const AttributeList &) {\n"; 2489 OS << " return true;\n"; 2490 OS << "}\n\n"; 2491 } 2492 2493 static std::string GenerateLangOptRequirements(const Record &R, 2494 raw_ostream &OS) { 2495 // If the attribute has an empty or unset list of language requirements, 2496 // return the default handler. 2497 std::vector<Record *> LangOpts = R.getValueAsListOfDefs("LangOpts"); 2498 if (LangOpts.empty()) 2499 return "defaultDiagnoseLangOpts"; 2500 2501 // Generate the test condition, as well as a unique function name for the 2502 // diagnostic test. The list of options should usually be short (one or two 2503 // options), and the uniqueness isn't strictly necessary (it is just for 2504 // codegen efficiency). 2505 std::string FnName = "check", Test; 2506 for (auto I = LangOpts.begin(), E = LangOpts.end(); I != E; ++I) { 2507 std::string Part = (*I)->getValueAsString("Name"); 2508 if ((*I)->getValueAsBit("Negated")) 2509 Test += "!"; 2510 Test += "S.LangOpts." + Part; 2511 if (I + 1 != E) 2512 Test += " || "; 2513 FnName += Part; 2514 } 2515 FnName += "LangOpts"; 2516 2517 // If this code has already been generated, simply return the previous 2518 // instance of it. 2519 static std::set<std::string> CustomLangOptsSet; 2520 std::set<std::string>::iterator I = CustomLangOptsSet.find(FnName); 2521 if (I != CustomLangOptsSet.end()) 2522 return *I; 2523 2524 OS << "static bool " << FnName << "(Sema &S, const AttributeList &Attr) {\n"; 2525 OS << " if (" << Test << ")\n"; 2526 OS << " return true;\n\n"; 2527 OS << " S.Diag(Attr.getLoc(), diag::warn_attribute_ignored) "; 2528 OS << "<< Attr.getName();\n"; 2529 OS << " return false;\n"; 2530 OS << "}\n\n"; 2531 2532 CustomLangOptsSet.insert(FnName); 2533 return FnName; 2534 } 2535 2536 static void GenerateDefaultTargetRequirements(raw_ostream &OS) { 2537 OS << "static bool defaultTargetRequirements(const TargetInfo &) {\n"; 2538 OS << " return true;\n"; 2539 OS << "}\n\n"; 2540 } 2541 2542 static std::string GenerateTargetRequirements(const Record &Attr, 2543 const ParsedAttrMap &Dupes, 2544 raw_ostream &OS) { 2545 // If the attribute is not a target specific attribute, return the default 2546 // target handler. 2547 if (!Attr.isSubClassOf("TargetSpecificAttr")) 2548 return "defaultTargetRequirements"; 2549 2550 // Get the list of architectures to be tested for. 2551 const Record *R = Attr.getValueAsDef("Target"); 2552 std::vector<std::string> Arches = R->getValueAsListOfStrings("Arches"); 2553 if (Arches.empty()) { 2554 PrintError(Attr.getLoc(), "Empty list of target architectures for a " 2555 "target-specific attr"); 2556 return "defaultTargetRequirements"; 2557 } 2558 2559 // If there are other attributes which share the same parsed attribute kind, 2560 // such as target-specific attributes with a shared spelling, collapse the 2561 // duplicate architectures. This is required because a shared target-specific 2562 // attribute has only one AttributeList::Kind enumeration value, but it 2563 // applies to multiple target architectures. In order for the attribute to be 2564 // considered valid, all of its architectures need to be included. 2565 if (!Attr.isValueUnset("ParseKind")) { 2566 std::string APK = Attr.getValueAsString("ParseKind"); 2567 for (const auto &I : Dupes) { 2568 if (I.first == APK) { 2569 std::vector<std::string> DA = I.second->getValueAsDef("Target") 2570 ->getValueAsListOfStrings("Arches"); 2571 std::copy(DA.begin(), DA.end(), std::back_inserter(Arches)); 2572 } 2573 } 2574 } 2575 2576 std::string FnName = "isTarget"; 2577 std::string Test; 2578 GenerateTargetSpecificAttrChecks(R, Arches, Test, &FnName); 2579 2580 // If this code has already been generated, simply return the previous 2581 // instance of it. 2582 static std::set<std::string> CustomTargetSet; 2583 std::set<std::string>::iterator I = CustomTargetSet.find(FnName); 2584 if (I != CustomTargetSet.end()) 2585 return *I; 2586 2587 OS << "static bool " << FnName << "(const TargetInfo &Target) {\n"; 2588 OS << " const llvm::Triple &T = Target.getTriple();\n"; 2589 OS << " return " << Test << ";\n"; 2590 OS << "}\n\n"; 2591 2592 CustomTargetSet.insert(FnName); 2593 return FnName; 2594 } 2595 2596 static void GenerateDefaultSpellingIndexToSemanticSpelling(raw_ostream &OS) { 2597 OS << "static unsigned defaultSpellingIndexToSemanticSpelling(" 2598 << "const AttributeList &Attr) {\n"; 2599 OS << " return UINT_MAX;\n"; 2600 OS << "}\n\n"; 2601 } 2602 2603 static std::string GenerateSpellingIndexToSemanticSpelling(const Record &Attr, 2604 raw_ostream &OS) { 2605 // If the attribute does not have a semantic form, we can bail out early. 2606 if (!Attr.getValueAsBit("ASTNode")) 2607 return "defaultSpellingIndexToSemanticSpelling"; 2608 2609 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr); 2610 2611 // If there are zero or one spellings, or all of the spellings share the same 2612 // name, we can also bail out early. 2613 if (Spellings.size() <= 1 || SpellingNamesAreCommon(Spellings)) 2614 return "defaultSpellingIndexToSemanticSpelling"; 2615 2616 // Generate the enumeration we will use for the mapping. 2617 SemanticSpellingMap SemanticToSyntacticMap; 2618 std::string Enum = CreateSemanticSpellings(Spellings, SemanticToSyntacticMap); 2619 std::string Name = Attr.getName() + "AttrSpellingMap"; 2620 2621 OS << "static unsigned " << Name << "(const AttributeList &Attr) {\n"; 2622 OS << Enum; 2623 OS << " unsigned Idx = Attr.getAttributeSpellingListIndex();\n"; 2624 WriteSemanticSpellingSwitch("Idx", SemanticToSyntacticMap, OS); 2625 OS << "}\n\n"; 2626 2627 return Name; 2628 } 2629 2630 static bool IsKnownToGCC(const Record &Attr) { 2631 // Look at the spellings for this subject; if there are any spellings which 2632 // claim to be known to GCC, the attribute is known to GCC. 2633 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr); 2634 for (const auto &I : Spellings) { 2635 if (I.knownToGCC()) 2636 return true; 2637 } 2638 return false; 2639 } 2640 2641 /// Emits the parsed attribute helpers 2642 void EmitClangAttrParsedAttrImpl(RecordKeeper &Records, raw_ostream &OS) { 2643 emitSourceFileHeader("Parsed attribute helpers", OS); 2644 2645 // Get the list of parsed attributes, and accept the optional list of 2646 // duplicates due to the ParseKind. 2647 ParsedAttrMap Dupes; 2648 ParsedAttrMap Attrs = getParsedAttrList(Records, &Dupes); 2649 2650 // Generate the default appertainsTo, target and language option diagnostic, 2651 // and spelling list index mapping methods. 2652 GenerateDefaultAppertainsTo(OS); 2653 GenerateDefaultLangOptRequirements(OS); 2654 GenerateDefaultTargetRequirements(OS); 2655 GenerateDefaultSpellingIndexToSemanticSpelling(OS); 2656 2657 // Generate the appertainsTo diagnostic methods and write their names into 2658 // another mapping. At the same time, generate the AttrInfoMap object 2659 // contents. Due to the reliance on generated code, use separate streams so 2660 // that code will not be interleaved. 2661 std::stringstream SS; 2662 for (auto I = Attrs.begin(), E = Attrs.end(); I != E; ++I) { 2663 // TODO: If the attribute's kind appears in the list of duplicates, that is 2664 // because it is a target-specific attribute that appears multiple times. 2665 // It would be beneficial to test whether the duplicates are "similar 2666 // enough" to each other to not cause problems. For instance, check that 2667 // the spellings are identical, and custom parsing rules match, etc. 2668 2669 // We need to generate struct instances based off ParsedAttrInfo from 2670 // AttributeList.cpp. 2671 SS << " { "; 2672 emitArgInfo(*I->second, SS); 2673 SS << ", " << I->second->getValueAsBit("HasCustomParsing"); 2674 SS << ", " << I->second->isSubClassOf("TargetSpecificAttr"); 2675 SS << ", " << I->second->isSubClassOf("TypeAttr"); 2676 SS << ", " << IsKnownToGCC(*I->second); 2677 SS << ", " << GenerateAppertainsTo(*I->second, OS); 2678 SS << ", " << GenerateLangOptRequirements(*I->second, OS); 2679 SS << ", " << GenerateTargetRequirements(*I->second, Dupes, OS); 2680 SS << ", " << GenerateSpellingIndexToSemanticSpelling(*I->second, OS); 2681 SS << " }"; 2682 2683 if (I + 1 != E) 2684 SS << ","; 2685 2686 SS << " // AT_" << I->first << "\n"; 2687 } 2688 2689 OS << "static const ParsedAttrInfo AttrInfoMap[AttributeList::UnknownAttribute + 1] = {\n"; 2690 OS << SS.str(); 2691 OS << "};\n\n"; 2692 } 2693 2694 // Emits the kind list of parsed attributes 2695 void EmitClangAttrParsedAttrKinds(RecordKeeper &Records, raw_ostream &OS) { 2696 emitSourceFileHeader("Attribute name matcher", OS); 2697 2698 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 2699 std::vector<StringMatcher::StringPair> GNU, Declspec, CXX11, Keywords, Pragma; 2700 std::set<std::string> Seen; 2701 for (const auto *A : Attrs) { 2702 const Record &Attr = *A; 2703 2704 bool SemaHandler = Attr.getValueAsBit("SemaHandler"); 2705 bool Ignored = Attr.getValueAsBit("Ignored"); 2706 if (SemaHandler || Ignored) { 2707 // Attribute spellings can be shared between target-specific attributes, 2708 // and can be shared between syntaxes for the same attribute. For 2709 // instance, an attribute can be spelled GNU<"interrupt"> for an ARM- 2710 // specific attribute, or MSP430-specific attribute. Additionally, an 2711 // attribute can be spelled GNU<"dllexport"> and Declspec<"dllexport"> 2712 // for the same semantic attribute. Ultimately, we need to map each of 2713 // these to a single AttributeList::Kind value, but the StringMatcher 2714 // class cannot handle duplicate match strings. So we generate a list of 2715 // string to match based on the syntax, and emit multiple string matchers 2716 // depending on the syntax used. 2717 std::string AttrName; 2718 if (Attr.isSubClassOf("TargetSpecificAttr") && 2719 !Attr.isValueUnset("ParseKind")) { 2720 AttrName = Attr.getValueAsString("ParseKind"); 2721 if (Seen.find(AttrName) != Seen.end()) 2722 continue; 2723 Seen.insert(AttrName); 2724 } else 2725 AttrName = NormalizeAttrName(StringRef(Attr.getName())).str(); 2726 2727 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(Attr); 2728 for (const auto &S : Spellings) { 2729 std::string RawSpelling = S.name(); 2730 std::vector<StringMatcher::StringPair> *Matches = nullptr; 2731 std::string Spelling, Variety = S.variety(); 2732 if (Variety == "CXX11") { 2733 Matches = &CXX11; 2734 Spelling += S.nameSpace(); 2735 Spelling += "::"; 2736 } else if (Variety == "GNU") 2737 Matches = &GNU; 2738 else if (Variety == "Declspec") 2739 Matches = &Declspec; 2740 else if (Variety == "Keyword") 2741 Matches = &Keywords; 2742 else if (Variety == "Pragma") 2743 Matches = &Pragma; 2744 2745 assert(Matches && "Unsupported spelling variety found"); 2746 2747 Spelling += NormalizeAttrSpelling(RawSpelling); 2748 if (SemaHandler) 2749 Matches->push_back(StringMatcher::StringPair(Spelling, 2750 "return AttributeList::AT_" + AttrName + ";")); 2751 else 2752 Matches->push_back(StringMatcher::StringPair(Spelling, 2753 "return AttributeList::IgnoredAttribute;")); 2754 } 2755 } 2756 } 2757 2758 OS << "static AttributeList::Kind getAttrKind(StringRef Name, "; 2759 OS << "AttributeList::Syntax Syntax) {\n"; 2760 OS << " if (AttributeList::AS_GNU == Syntax) {\n"; 2761 StringMatcher("Name", GNU, OS).Emit(); 2762 OS << " } else if (AttributeList::AS_Declspec == Syntax) {\n"; 2763 StringMatcher("Name", Declspec, OS).Emit(); 2764 OS << " } else if (AttributeList::AS_CXX11 == Syntax) {\n"; 2765 StringMatcher("Name", CXX11, OS).Emit(); 2766 OS << " } else if (AttributeList::AS_Keyword == Syntax || "; 2767 OS << "AttributeList::AS_ContextSensitiveKeyword == Syntax) {\n"; 2768 StringMatcher("Name", Keywords, OS).Emit(); 2769 OS << " } else if (AttributeList::AS_Pragma == Syntax) {\n"; 2770 StringMatcher("Name", Pragma, OS).Emit(); 2771 OS << " }\n"; 2772 OS << " return AttributeList::UnknownAttribute;\n" 2773 << "}\n"; 2774 } 2775 2776 // Emits the code to dump an attribute. 2777 void EmitClangAttrDump(RecordKeeper &Records, raw_ostream &OS) { 2778 emitSourceFileHeader("Attribute dumper", OS); 2779 2780 OS << 2781 " switch (A->getKind()) {\n" 2782 " default:\n" 2783 " llvm_unreachable(\"Unknown attribute kind!\");\n" 2784 " break;\n"; 2785 std::vector<Record*> Attrs = Records.getAllDerivedDefinitions("Attr"), Args; 2786 for (const auto *Attr : Attrs) { 2787 const Record &R = *Attr; 2788 if (!R.getValueAsBit("ASTNode")) 2789 continue; 2790 OS << " case attr::" << R.getName() << ": {\n"; 2791 2792 // If the attribute has a semantically-meaningful name (which is determined 2793 // by whether there is a Spelling enumeration for it), then write out the 2794 // spelling used for the attribute. 2795 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(R); 2796 if (Spellings.size() > 1 && !SpellingNamesAreCommon(Spellings)) 2797 OS << " OS << \" \" << A->getSpelling();\n"; 2798 2799 Args = R.getValueAsListOfDefs("Args"); 2800 if (!Args.empty()) { 2801 OS << " const " << R.getName() << "Attr *SA = cast<" << R.getName() 2802 << "Attr>(A);\n"; 2803 for (const auto *Arg : Args) 2804 createArgument(*Arg, R.getName())->writeDump(OS); 2805 2806 for (auto AI = Args.begin(), AE = Args.end(); AI != AE; ++AI) 2807 createArgument(**AI, R.getName())->writeDumpChildren(OS); 2808 } 2809 OS << 2810 " break;\n" 2811 " }\n"; 2812 } 2813 OS << " }\n"; 2814 } 2815 2816 void EmitClangAttrParserStringSwitches(RecordKeeper &Records, 2817 raw_ostream &OS) { 2818 emitSourceFileHeader("Parser-related llvm::StringSwitch cases", OS); 2819 emitClangAttrArgContextList(Records, OS); 2820 emitClangAttrIdentifierArgList(Records, OS); 2821 emitClangAttrTypeArgList(Records, OS); 2822 emitClangAttrLateParsedList(Records, OS); 2823 } 2824 2825 class DocumentationData { 2826 public: 2827 const Record *Documentation; 2828 const Record *Attribute; 2829 2830 DocumentationData(const Record &Documentation, const Record &Attribute) 2831 : Documentation(&Documentation), Attribute(&Attribute) {} 2832 }; 2833 2834 static void WriteCategoryHeader(const Record *DocCategory, 2835 raw_ostream &OS) { 2836 const std::string &Name = DocCategory->getValueAsString("Name"); 2837 OS << Name << "\n" << std::string(Name.length(), '=') << "\n"; 2838 2839 // If there is content, print that as well. 2840 std::string ContentStr = DocCategory->getValueAsString("Content"); 2841 // Trim leading and trailing newlines and spaces. 2842 OS << StringRef(ContentStr).trim(); 2843 2844 OS << "\n\n"; 2845 } 2846 2847 enum SpellingKind { 2848 GNU = 1 << 0, 2849 CXX11 = 1 << 1, 2850 Declspec = 1 << 2, 2851 Keyword = 1 << 3, 2852 Pragma = 1 << 4 2853 }; 2854 2855 static void WriteDocumentation(const DocumentationData &Doc, 2856 raw_ostream &OS) { 2857 // FIXME: there is no way to have a per-spelling category for the attribute 2858 // documentation. This may not be a limiting factor since the spellings 2859 // should generally be consistently applied across the category. 2860 2861 std::vector<FlattenedSpelling> Spellings = GetFlattenedSpellings(*Doc.Attribute); 2862 2863 // Determine the heading to be used for this attribute. 2864 std::string Heading = Doc.Documentation->getValueAsString("Heading"); 2865 bool CustomHeading = !Heading.empty(); 2866 if (Heading.empty()) { 2867 // If there's only one spelling, we can simply use that. 2868 if (Spellings.size() == 1) 2869 Heading = Spellings.begin()->name(); 2870 else { 2871 std::set<std::string> Uniques; 2872 for (auto I = Spellings.begin(), E = Spellings.end(); 2873 I != E && Uniques.size() <= 1; ++I) { 2874 std::string Spelling = NormalizeNameForSpellingComparison(I->name()); 2875 Uniques.insert(Spelling); 2876 } 2877 // If the semantic map has only one spelling, that is sufficient for our 2878 // needs. 2879 if (Uniques.size() == 1) 2880 Heading = *Uniques.begin(); 2881 } 2882 } 2883 2884 // If the heading is still empty, it is an error. 2885 if (Heading.empty()) 2886 PrintFatalError(Doc.Attribute->getLoc(), 2887 "This attribute requires a heading to be specified"); 2888 2889 // Gather a list of unique spellings; this is not the same as the semantic 2890 // spelling for the attribute. Variations in underscores and other non- 2891 // semantic characters are still acceptable. 2892 std::vector<std::string> Names; 2893 2894 unsigned SupportedSpellings = 0; 2895 for (const auto &I : Spellings) { 2896 SpellingKind Kind = StringSwitch<SpellingKind>(I.variety()) 2897 .Case("GNU", GNU) 2898 .Case("CXX11", CXX11) 2899 .Case("Declspec", Declspec) 2900 .Case("Keyword", Keyword) 2901 .Case("Pragma", Pragma); 2902 2903 // Mask in the supported spelling. 2904 SupportedSpellings |= Kind; 2905 2906 std::string Name; 2907 if (Kind == CXX11 && !I.nameSpace().empty()) 2908 Name = I.nameSpace() + "::"; 2909 Name += I.name(); 2910 2911 // If this name is the same as the heading, do not add it. 2912 if (Name != Heading) 2913 Names.push_back(Name); 2914 } 2915 2916 // Print out the heading for the attribute. If there are alternate spellings, 2917 // then display those after the heading. 2918 if (!CustomHeading && !Names.empty()) { 2919 Heading += " ("; 2920 for (auto I = Names.begin(), E = Names.end(); I != E; ++I) { 2921 if (I != Names.begin()) 2922 Heading += ", "; 2923 Heading += *I; 2924 } 2925 Heading += ")"; 2926 } 2927 OS << Heading << "\n" << std::string(Heading.length(), '-') << "\n"; 2928 2929 if (!SupportedSpellings) 2930 PrintFatalError(Doc.Attribute->getLoc(), 2931 "Attribute has no supported spellings; cannot be " 2932 "documented"); 2933 2934 // List what spelling syntaxes the attribute supports. 2935 OS << ".. csv-table:: Supported Syntaxes\n"; 2936 OS << " :header: \"GNU\", \"C++11\", \"__declspec\", \"Keyword\","; 2937 OS << " \"Pragma\"\n\n"; 2938 OS << " \""; 2939 if (SupportedSpellings & GNU) OS << "X"; 2940 OS << "\",\""; 2941 if (SupportedSpellings & CXX11) OS << "X"; 2942 OS << "\",\""; 2943 if (SupportedSpellings & Declspec) OS << "X"; 2944 OS << "\",\""; 2945 if (SupportedSpellings & Keyword) OS << "X"; 2946 OS << "\", \""; 2947 if (SupportedSpellings & Pragma) OS << "X"; 2948 OS << "\"\n\n"; 2949 2950 // If the attribute is deprecated, print a message about it, and possibly 2951 // provide a replacement attribute. 2952 if (!Doc.Documentation->isValueUnset("Deprecated")) { 2953 OS << "This attribute has been deprecated, and may be removed in a future " 2954 << "version of Clang."; 2955 const Record &Deprecated = *Doc.Documentation->getValueAsDef("Deprecated"); 2956 std::string Replacement = Deprecated.getValueAsString("Replacement"); 2957 if (!Replacement.empty()) 2958 OS << " This attribute has been superseded by ``" 2959 << Replacement << "``."; 2960 OS << "\n\n"; 2961 } 2962 2963 std::string ContentStr = Doc.Documentation->getValueAsString("Content"); 2964 // Trim leading and trailing newlines and spaces. 2965 OS << StringRef(ContentStr).trim(); 2966 2967 OS << "\n\n\n"; 2968 } 2969 2970 void EmitClangAttrDocs(RecordKeeper &Records, raw_ostream &OS) { 2971 // Get the documentation introduction paragraph. 2972 const Record *Documentation = Records.getDef("GlobalDocumentation"); 2973 if (!Documentation) { 2974 PrintFatalError("The Documentation top-level definition is missing, " 2975 "no documentation will be generated."); 2976 return; 2977 } 2978 2979 OS << Documentation->getValueAsString("Intro") << "\n"; 2980 2981 // Gather the Documentation lists from each of the attributes, based on the 2982 // category provided. 2983 std::vector<Record *> Attrs = Records.getAllDerivedDefinitions("Attr"); 2984 std::map<const Record *, std::vector<DocumentationData>> SplitDocs; 2985 for (const auto *A : Attrs) { 2986 const Record &Attr = *A; 2987 std::vector<Record *> Docs = Attr.getValueAsListOfDefs("Documentation"); 2988 for (const auto *D : Docs) { 2989 const Record &Doc = *D; 2990 const Record *Category = Doc.getValueAsDef("Category"); 2991 // If the category is "undocumented", then there cannot be any other 2992 // documentation categories (otherwise, the attribute would become 2993 // documented). 2994 std::string Cat = Category->getValueAsString("Name"); 2995 bool Undocumented = Cat == "Undocumented"; 2996 if (Undocumented && Docs.size() > 1) 2997 PrintFatalError(Doc.getLoc(), 2998 "Attribute is \"Undocumented\", but has multiple " 2999 "documentation categories"); 3000 3001 if (!Undocumented) 3002 SplitDocs[Category].push_back(DocumentationData(Doc, Attr)); 3003 } 3004 } 3005 3006 // Having split the attributes out based on what documentation goes where, 3007 // we can begin to generate sections of documentation. 3008 for (const auto &I : SplitDocs) { 3009 WriteCategoryHeader(I.first, OS); 3010 3011 // Walk over each of the attributes in the category and write out their 3012 // documentation. 3013 for (const auto &Doc : I.second) 3014 WriteDocumentation(Doc, OS); 3015 } 3016 } 3017 3018 } // end namespace clang 3019