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