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