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