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