Home | History | Annotate | Line # | Download | only in Basic
      1 //===- IdentifierTable.cpp - Hash table for identifier lookup -------------===//
      2 //
      3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
      4 // See https://llvm.org/LICENSE.txt for license information.
      5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
      6 //
      7 //===----------------------------------------------------------------------===//
      8 //
      9 // This file implements the IdentifierInfo, IdentifierVisitor, and
     10 // IdentifierTable interfaces.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #include "clang/Basic/IdentifierTable.h"
     15 #include "clang/Basic/CharInfo.h"
     16 #include "clang/Basic/LangOptions.h"
     17 #include "clang/Basic/OperatorKinds.h"
     18 #include "clang/Basic/Specifiers.h"
     19 #include "clang/Basic/TargetBuiltins.h"
     20 #include "clang/Basic/TokenKinds.h"
     21 #include "llvm/ADT/DenseMapInfo.h"
     22 #include "llvm/ADT/FoldingSet.h"
     23 #include "llvm/ADT/SmallString.h"
     24 #include "llvm/ADT/StringMap.h"
     25 #include "llvm/ADT/StringRef.h"
     26 #include "llvm/Support/Allocator.h"
     27 #include "llvm/Support/ErrorHandling.h"
     28 #include "llvm/Support/raw_ostream.h"
     29 #include <cassert>
     30 #include <cstdio>
     31 #include <cstring>
     32 #include <string>
     33 
     34 using namespace clang;
     35 
     36 // A check to make sure the ObjCOrBuiltinID has sufficient room to store the
     37 // largest possible target/aux-target combination. If we exceed this, we likely
     38 // need to just change the ObjCOrBuiltinIDBits value in IdentifierTable.h.
     39 static_assert(2 * LargestBuiltinID < (2 << (ObjCOrBuiltinIDBits - 1)),
     40               "Insufficient ObjCOrBuiltinID Bits");
     41 
     42 //===----------------------------------------------------------------------===//
     43 // IdentifierTable Implementation
     44 //===----------------------------------------------------------------------===//
     45 
     46 IdentifierIterator::~IdentifierIterator() = default;
     47 
     48 IdentifierInfoLookup::~IdentifierInfoLookup() = default;
     49 
     50 namespace {
     51 
     52 /// A simple identifier lookup iterator that represents an
     53 /// empty sequence of identifiers.
     54 class EmptyLookupIterator : public IdentifierIterator
     55 {
     56 public:
     57   StringRef Next() override { return StringRef(); }
     58 };
     59 
     60 } // namespace
     61 
     62 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
     63   return new EmptyLookupIterator();
     64 }
     65 
     66 IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
     67     : HashTable(8192), // Start with space for 8K identifiers.
     68       ExternalLookup(ExternalLookup) {}
     69 
     70 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
     71                                  IdentifierInfoLookup *ExternalLookup)
     72     : IdentifierTable(ExternalLookup) {
     73   // Populate the identifier table with info about keywords for the current
     74   // language.
     75   AddKeywords(LangOpts);
     76 }
     77 
     78 //===----------------------------------------------------------------------===//
     79 // Language Keyword Implementation
     80 //===----------------------------------------------------------------------===//
     81 
     82 // Constants for TokenKinds.def
     83 namespace {
     84 
     85   enum {
     86     KEYC99        = 0x1,
     87     KEYCXX        = 0x2,
     88     KEYCXX11      = 0x4,
     89     KEYGNU        = 0x8,
     90     KEYMS         = 0x10,
     91     BOOLSUPPORT   = 0x20,
     92     KEYALTIVEC    = 0x40,
     93     KEYNOCXX      = 0x80,
     94     KEYBORLAND    = 0x100,
     95     KEYOPENCLC    = 0x200,
     96     KEYC11        = 0x400,
     97     KEYNOMS18     = 0x800,
     98     KEYNOOPENCL   = 0x1000,
     99     WCHARSUPPORT  = 0x2000,
    100     HALFSUPPORT   = 0x4000,
    101     CHAR8SUPPORT  = 0x8000,
    102     KEYCONCEPTS   = 0x10000,
    103     KEYOBJC       = 0x20000,
    104     KEYZVECTOR    = 0x40000,
    105     KEYCOROUTINES = 0x80000,
    106     KEYMODULES    = 0x100000,
    107     KEYCXX20      = 0x200000,
    108     KEYOPENCLCXX  = 0x400000,
    109     KEYMSCOMPAT   = 0x800000,
    110     KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
    111     KEYALL = (0xffffff & ~KEYNOMS18 &
    112               ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
    113   };
    114 
    115   /// How a keyword is treated in the selected standard.
    116   enum KeywordStatus {
    117     KS_Disabled,    // Disabled
    118     KS_Extension,   // Is an extension
    119     KS_Enabled,     // Enabled
    120     KS_Future       // Is a keyword in future standard
    121   };
    122 
    123 } // namespace
    124 
    125 /// Translates flags as specified in TokenKinds.def into keyword status
    126 /// in the given language standard.
    127 static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
    128                                       unsigned Flags) {
    129   if (Flags == KEYALL) return KS_Enabled;
    130   if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
    131   if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
    132   if (LangOpts.CPlusPlus20 && (Flags & KEYCXX20)) return KS_Enabled;
    133   if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
    134   if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
    135   if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
    136   if (LangOpts.MSVCCompat && (Flags & KEYMSCOMPAT)) return KS_Enabled;
    137   if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
    138   if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
    139   if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
    140   if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
    141   if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
    142   if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
    143   if (LangOpts.ZVector && (Flags & KEYZVECTOR)) return KS_Enabled;
    144   if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLC))
    145     return KS_Enabled;
    146   if (LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLCXX)) return KS_Enabled;
    147   if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
    148   if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
    149   // We treat bridge casts as objective-C keywords so we can warn on them
    150   // in non-arc mode.
    151   if (LangOpts.ObjC && (Flags & KEYOBJC)) return KS_Enabled;
    152   if (LangOpts.CPlusPlus20 && (Flags & KEYCONCEPTS)) return KS_Enabled;
    153   if (LangOpts.Coroutines && (Flags & KEYCOROUTINES)) return KS_Enabled;
    154   if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
    155   if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
    156   if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus20 && (Flags & CHAR8SUPPORT))
    157     return KS_Future;
    158   return KS_Disabled;
    159 }
    160 
    161 /// AddKeyword - This method is used to associate a token ID with specific
    162 /// identifiers because they are language keywords.  This causes the lexer to
    163 /// automatically map matching identifiers to specialized token codes.
    164 static void AddKeyword(StringRef Keyword,
    165                        tok::TokenKind TokenCode, unsigned Flags,
    166                        const LangOptions &LangOpts, IdentifierTable &Table) {
    167   KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
    168 
    169   // Don't add this keyword under MSVCCompat.
    170   if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
    171       !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
    172     return;
    173 
    174   // Don't add this keyword under OpenCL.
    175   if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
    176     return;
    177 
    178   // Don't add this keyword if disabled in this language.
    179   if (AddResult == KS_Disabled) return;
    180 
    181   IdentifierInfo &Info =
    182       Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
    183   Info.setIsExtensionToken(AddResult == KS_Extension);
    184   Info.setIsFutureCompatKeyword(AddResult == KS_Future);
    185 }
    186 
    187 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
    188 /// representations.
    189 static void AddCXXOperatorKeyword(StringRef Keyword,
    190                                   tok::TokenKind TokenCode,
    191                                   IdentifierTable &Table) {
    192   IdentifierInfo &Info = Table.get(Keyword, TokenCode);
    193   Info.setIsCPlusPlusOperatorKeyword();
    194 }
    195 
    196 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
    197 /// or "property".
    198 static void AddObjCKeyword(StringRef Name,
    199                            tok::ObjCKeywordKind ObjCID,
    200                            IdentifierTable &Table) {
    201   Table.get(Name).setObjCKeywordID(ObjCID);
    202 }
    203 
    204 /// AddKeywords - Add all keywords to the symbol table.
    205 ///
    206 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
    207   // Add keywords and tokens for the current language.
    208 #define KEYWORD(NAME, FLAGS) \
    209   AddKeyword(StringRef(#NAME), tok::kw_ ## NAME,  \
    210              FLAGS, LangOpts, *this);
    211 #define ALIAS(NAME, TOK, FLAGS) \
    212   AddKeyword(StringRef(NAME), tok::kw_ ## TOK,  \
    213              FLAGS, LangOpts, *this);
    214 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
    215   if (LangOpts.CXXOperatorNames)          \
    216     AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
    217 #define OBJC_AT_KEYWORD(NAME)  \
    218   if (LangOpts.ObjC)           \
    219     AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
    220 #define TESTING_KEYWORD(NAME, FLAGS)
    221 #include "clang/Basic/TokenKinds.def"
    222 
    223   if (LangOpts.ParseUnknownAnytype)
    224     AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
    225                LangOpts, *this);
    226 
    227   if (LangOpts.DeclSpecKeyword)
    228     AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
    229 
    230   if (LangOpts.IEEE128)
    231     AddKeyword("__ieee128", tok::kw___float128, KEYALL, LangOpts, *this);
    232 
    233   // Add the 'import' contextual keyword.
    234   get("import").setModulesImport(true);
    235 }
    236 
    237 /// Checks if the specified token kind represents a keyword in the
    238 /// specified language.
    239 /// \returns Status of the keyword in the language.
    240 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
    241                                       tok::TokenKind K) {
    242   switch (K) {
    243 #define KEYWORD(NAME, FLAGS) \
    244   case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
    245 #include "clang/Basic/TokenKinds.def"
    246   default: return KS_Disabled;
    247   }
    248 }
    249 
    250 /// Returns true if the identifier represents a keyword in the
    251 /// specified language.
    252 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
    253   switch (getTokenKwStatus(LangOpts, getTokenID())) {
    254   case KS_Enabled:
    255   case KS_Extension:
    256     return true;
    257   default:
    258     return false;
    259   }
    260 }
    261 
    262 /// Returns true if the identifier represents a C++ keyword in the
    263 /// specified language.
    264 bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
    265   if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
    266     return false;
    267   // This is a C++ keyword if this identifier is not a keyword when checked
    268   // using LangOptions without C++ support.
    269   LangOptions LangOptsNoCPP = LangOpts;
    270   LangOptsNoCPP.CPlusPlus = false;
    271   LangOptsNoCPP.CPlusPlus11 = false;
    272   LangOptsNoCPP.CPlusPlus20 = false;
    273   return !isKeyword(LangOptsNoCPP);
    274 }
    275 
    276 ReservedIdentifierStatus
    277 IdentifierInfo::isReserved(const LangOptions &LangOpts) const {
    278   StringRef Name = getName();
    279 
    280   // '_' is a reserved identifier, but its use is so common (e.g. to store
    281   // ignored values) that we don't warn on it.
    282   if (Name.size() <= 1)
    283     return ReservedIdentifierStatus::NotReserved;
    284 
    285   // [lex.name] p3
    286   if (Name[0] == '_') {
    287 
    288     // Each name that begins with an underscore followed by an uppercase letter
    289     // or another underscore is reserved.
    290     if (Name[1] == '_')
    291       return ReservedIdentifierStatus::StartsWithDoubleUnderscore;
    292 
    293     if ('A' <= Name[1] && Name[1] <= 'Z')
    294       return ReservedIdentifierStatus::
    295           StartsWithUnderscoreFollowedByCapitalLetter;
    296 
    297     // This is a bit misleading: it actually means it's only reserved if we're
    298     // at global scope because it starts with an underscore.
    299     return ReservedIdentifierStatus::StartsWithUnderscoreAtGlobalScope;
    300   }
    301 
    302   // Each name that contains a double underscore (__) is reserved.
    303   if (LangOpts.CPlusPlus && Name.contains("__"))
    304     return ReservedIdentifierStatus::ContainsDoubleUnderscore;
    305 
    306   return ReservedIdentifierStatus::NotReserved;
    307 }
    308 
    309 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
    310   // We use a perfect hash function here involving the length of the keyword,
    311   // the first and third character.  For preprocessor ID's there are no
    312   // collisions (if there were, the switch below would complain about duplicate
    313   // case values).  Note that this depends on 'if' being null terminated.
    314 
    315 #define HASH(LEN, FIRST, THIRD) \
    316   (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
    317 #define CASE(LEN, FIRST, THIRD, NAME) \
    318   case HASH(LEN, FIRST, THIRD): \
    319     return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
    320 
    321   unsigned Len = getLength();
    322   if (Len < 2) return tok::pp_not_keyword;
    323   const char *Name = getNameStart();
    324   switch (HASH(Len, Name[0], Name[2])) {
    325   default: return tok::pp_not_keyword;
    326   CASE( 2, 'i', '\0', if);
    327   CASE( 4, 'e', 'i', elif);
    328   CASE( 4, 'e', 's', else);
    329   CASE( 4, 'l', 'n', line);
    330   CASE( 4, 's', 'c', sccs);
    331   CASE( 5, 'e', 'd', endif);
    332   CASE( 5, 'e', 'r', error);
    333   CASE( 5, 'i', 'e', ident);
    334   CASE( 5, 'i', 'd', ifdef);
    335   CASE( 5, 'u', 'd', undef);
    336 
    337   CASE( 6, 'a', 's', assert);
    338   CASE( 6, 'd', 'f', define);
    339   CASE( 6, 'i', 'n', ifndef);
    340   CASE( 6, 'i', 'p', import);
    341   CASE( 6, 'p', 'a', pragma);
    342 
    343   CASE( 7, 'd', 'f', defined);
    344   CASE( 7, 'i', 'c', include);
    345   CASE( 7, 'w', 'r', warning);
    346 
    347   CASE( 8, 'u', 'a', unassert);
    348   CASE(12, 'i', 'c', include_next);
    349 
    350   CASE(14, '_', 'p', __public_macro);
    351 
    352   CASE(15, '_', 'p', __private_macro);
    353 
    354   CASE(16, '_', 'i', __include_macros);
    355 #undef CASE
    356 #undef HASH
    357   }
    358 }
    359 
    360 //===----------------------------------------------------------------------===//
    361 // Stats Implementation
    362 //===----------------------------------------------------------------------===//
    363 
    364 /// PrintStats - Print statistics about how well the identifier table is doing
    365 /// at hashing identifiers.
    366 void IdentifierTable::PrintStats() const {
    367   unsigned NumBuckets = HashTable.getNumBuckets();
    368   unsigned NumIdentifiers = HashTable.getNumItems();
    369   unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
    370   unsigned AverageIdentifierSize = 0;
    371   unsigned MaxIdentifierLength = 0;
    372 
    373   // TODO: Figure out maximum times an identifier had to probe for -stats.
    374   for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
    375        I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
    376     unsigned IdLen = I->getKeyLength();
    377     AverageIdentifierSize += IdLen;
    378     if (MaxIdentifierLength < IdLen)
    379       MaxIdentifierLength = IdLen;
    380   }
    381 
    382   fprintf(stderr, "\n*** Identifier Table Stats:\n");
    383   fprintf(stderr, "# Identifiers:   %d\n", NumIdentifiers);
    384   fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
    385   fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
    386           NumIdentifiers/(double)NumBuckets);
    387   fprintf(stderr, "Ave identifier length: %f\n",
    388           (AverageIdentifierSize/(double)NumIdentifiers));
    389   fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
    390 
    391   // Compute statistics about the memory allocated for identifiers.
    392   HashTable.getAllocator().PrintStats();
    393 }
    394 
    395 //===----------------------------------------------------------------------===//
    396 // SelectorTable Implementation
    397 //===----------------------------------------------------------------------===//
    398 
    399 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
    400   return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
    401 }
    402 
    403 namespace clang {
    404 
    405 /// One of these variable length records is kept for each
    406 /// selector containing more than one keyword. We use a folding set
    407 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
    408 /// this class is provided strictly through Selector.
    409 class alignas(IdentifierInfoAlignment) MultiKeywordSelector
    410     : public detail::DeclarationNameExtra,
    411       public llvm::FoldingSetNode {
    412   MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
    413 
    414 public:
    415   // Constructor for keyword selectors.
    416   MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
    417       : DeclarationNameExtra(nKeys) {
    418     assert((nKeys > 1) && "not a multi-keyword selector");
    419 
    420     // Fill in the trailing keyword array.
    421     IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1);
    422     for (unsigned i = 0; i != nKeys; ++i)
    423       KeyInfo[i] = IIV[i];
    424   }
    425 
    426   // getName - Derive the full selector name and return it.
    427   std::string getName() const;
    428 
    429   using DeclarationNameExtra::getNumArgs;
    430 
    431   using keyword_iterator = IdentifierInfo *const *;
    432 
    433   keyword_iterator keyword_begin() const {
    434     return reinterpret_cast<keyword_iterator>(this + 1);
    435   }
    436 
    437   keyword_iterator keyword_end() const {
    438     return keyword_begin() + getNumArgs();
    439   }
    440 
    441   IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
    442     assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
    443     return keyword_begin()[i];
    444   }
    445 
    446   static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
    447                       unsigned NumArgs) {
    448     ID.AddInteger(NumArgs);
    449     for (unsigned i = 0; i != NumArgs; ++i)
    450       ID.AddPointer(ArgTys[i]);
    451   }
    452 
    453   void Profile(llvm::FoldingSetNodeID &ID) {
    454     Profile(ID, keyword_begin(), getNumArgs());
    455   }
    456 };
    457 
    458 } // namespace clang.
    459 
    460 bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const {
    461   assert(!Names.empty() && "must have >= 1 selector slots");
    462   if (getNumArgs() != Names.size())
    463     return false;
    464   for (unsigned I = 0, E = Names.size(); I != E; ++I) {
    465     if (getNameForSlot(I) != Names[I])
    466       return false;
    467   }
    468   return true;
    469 }
    470 
    471 bool Selector::isUnarySelector(StringRef Name) const {
    472   return isUnarySelector() && getNameForSlot(0) == Name;
    473 }
    474 
    475 unsigned Selector::getNumArgs() const {
    476   unsigned IIF = getIdentifierInfoFlag();
    477   if (IIF <= ZeroArg)
    478     return 0;
    479   if (IIF == OneArg)
    480     return 1;
    481   // We point to a MultiKeywordSelector.
    482   MultiKeywordSelector *SI = getMultiKeywordSelector();
    483   return SI->getNumArgs();
    484 }
    485 
    486 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
    487   if (getIdentifierInfoFlag() < MultiArg) {
    488     assert(argIndex == 0 && "illegal keyword index");
    489     return getAsIdentifierInfo();
    490   }
    491 
    492   // We point to a MultiKeywordSelector.
    493   MultiKeywordSelector *SI = getMultiKeywordSelector();
    494   return SI->getIdentifierInfoForSlot(argIndex);
    495 }
    496 
    497 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
    498   IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
    499   return II ? II->getName() : StringRef();
    500 }
    501 
    502 std::string MultiKeywordSelector::getName() const {
    503   SmallString<256> Str;
    504   llvm::raw_svector_ostream OS(Str);
    505   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
    506     if (*I)
    507       OS << (*I)->getName();
    508     OS << ':';
    509   }
    510 
    511   return std::string(OS.str());
    512 }
    513 
    514 std::string Selector::getAsString() const {
    515   if (InfoPtr == 0)
    516     return "<null selector>";
    517 
    518   if (getIdentifierInfoFlag() < MultiArg) {
    519     IdentifierInfo *II = getAsIdentifierInfo();
    520 
    521     if (getNumArgs() == 0) {
    522       assert(II && "If the number of arguments is 0 then II is guaranteed to "
    523                    "not be null.");
    524       return std::string(II->getName());
    525     }
    526 
    527     if (!II)
    528       return ":";
    529 
    530     return II->getName().str() + ":";
    531   }
    532 
    533   // We have a multiple keyword selector.
    534   return getMultiKeywordSelector()->getName();
    535 }
    536 
    537 void Selector::print(llvm::raw_ostream &OS) const {
    538   OS << getAsString();
    539 }
    540 
    541 LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); }
    542 
    543 /// Interpreting the given string using the normal CamelCase
    544 /// conventions, determine whether the given string starts with the
    545 /// given "word", which is assumed to end in a lowercase letter.
    546 static bool startsWithWord(StringRef name, StringRef word) {
    547   if (name.size() < word.size()) return false;
    548   return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
    549           name.startswith(word));
    550 }
    551 
    552 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
    553   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
    554   if (!first) return OMF_None;
    555 
    556   StringRef name = first->getName();
    557   if (sel.isUnarySelector()) {
    558     if (name == "autorelease") return OMF_autorelease;
    559     if (name == "dealloc") return OMF_dealloc;
    560     if (name == "finalize") return OMF_finalize;
    561     if (name == "release") return OMF_release;
    562     if (name == "retain") return OMF_retain;
    563     if (name == "retainCount") return OMF_retainCount;
    564     if (name == "self") return OMF_self;
    565     if (name == "initialize") return OMF_initialize;
    566   }
    567 
    568   if (name == "performSelector" || name == "performSelectorInBackground" ||
    569       name == "performSelectorOnMainThread")
    570     return OMF_performSelector;
    571 
    572   // The other method families may begin with a prefix of underscores.
    573   while (!name.empty() && name.front() == '_')
    574     name = name.substr(1);
    575 
    576   if (name.empty()) return OMF_None;
    577   switch (name.front()) {
    578   case 'a':
    579     if (startsWithWord(name, "alloc")) return OMF_alloc;
    580     break;
    581   case 'c':
    582     if (startsWithWord(name, "copy")) return OMF_copy;
    583     break;
    584   case 'i':
    585     if (startsWithWord(name, "init")) return OMF_init;
    586     break;
    587   case 'm':
    588     if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
    589     break;
    590   case 'n':
    591     if (startsWithWord(name, "new")) return OMF_new;
    592     break;
    593   default:
    594     break;
    595   }
    596 
    597   return OMF_None;
    598 }
    599 
    600 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
    601   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
    602   if (!first) return OIT_None;
    603 
    604   StringRef name = first->getName();
    605 
    606   if (name.empty()) return OIT_None;
    607   switch (name.front()) {
    608     case 'a':
    609       if (startsWithWord(name, "array")) return OIT_Array;
    610       break;
    611     case 'd':
    612       if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
    613       if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
    614       break;
    615     case 's':
    616       if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
    617       if (startsWithWord(name, "standard")) return OIT_Singleton;
    618       break;
    619     case 'i':
    620       if (startsWithWord(name, "init")) return OIT_Init;
    621       break;
    622     default:
    623       break;
    624   }
    625   return OIT_None;
    626 }
    627 
    628 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
    629   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
    630   if (!first) return SFF_None;
    631 
    632   StringRef name = first->getName();
    633 
    634   switch (name.front()) {
    635     case 'a':
    636       if (name == "appendFormat") return SFF_NSString;
    637       break;
    638 
    639     case 'i':
    640       if (name == "initWithFormat") return SFF_NSString;
    641       break;
    642 
    643     case 'l':
    644       if (name == "localizedStringWithFormat") return SFF_NSString;
    645       break;
    646 
    647     case 's':
    648       if (name == "stringByAppendingFormat" ||
    649           name == "stringWithFormat") return SFF_NSString;
    650       break;
    651   }
    652   return SFF_None;
    653 }
    654 
    655 namespace {
    656 
    657 struct SelectorTableImpl {
    658   llvm::FoldingSet<MultiKeywordSelector> Table;
    659   llvm::BumpPtrAllocator Allocator;
    660 };
    661 
    662 } // namespace
    663 
    664 static SelectorTableImpl &getSelectorTableImpl(void *P) {
    665   return *static_cast<SelectorTableImpl*>(P);
    666 }
    667 
    668 SmallString<64>
    669 SelectorTable::constructSetterName(StringRef Name) {
    670   SmallString<64> SetterName("set");
    671   SetterName += Name;
    672   SetterName[3] = toUppercase(SetterName[3]);
    673   return SetterName;
    674 }
    675 
    676 Selector
    677 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
    678                                        SelectorTable &SelTable,
    679                                        const IdentifierInfo *Name) {
    680   IdentifierInfo *SetterName =
    681     &Idents.get(constructSetterName(Name->getName()));
    682   return SelTable.getUnarySelector(SetterName);
    683 }
    684 
    685 std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) {
    686   StringRef Name = Sel.getNameForSlot(0);
    687   assert(Name.startswith("set") && "invalid setter name");
    688   return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str();
    689 }
    690 
    691 size_t SelectorTable::getTotalMemory() const {
    692   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
    693   return SelTabImpl.Allocator.getTotalMemory();
    694 }
    695 
    696 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
    697   if (nKeys < 2)
    698     return Selector(IIV[0], nKeys);
    699 
    700   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
    701 
    702   // Unique selector, to guarantee there is one per name.
    703   llvm::FoldingSetNodeID ID;
    704   MultiKeywordSelector::Profile(ID, IIV, nKeys);
    705 
    706   void *InsertPos = nullptr;
    707   if (MultiKeywordSelector *SI =
    708         SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
    709     return Selector(SI);
    710 
    711   // MultiKeywordSelector objects are not allocated with new because they have a
    712   // variable size array (for parameter types) at the end of them.
    713   unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
    714   MultiKeywordSelector *SI =
    715       (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
    716           Size, alignof(MultiKeywordSelector));
    717   new (SI) MultiKeywordSelector(nKeys, IIV);
    718   SelTabImpl.Table.InsertNode(SI, InsertPos);
    719   return Selector(SI);
    720 }
    721 
    722 SelectorTable::SelectorTable() {
    723   Impl = new SelectorTableImpl();
    724 }
    725 
    726 SelectorTable::~SelectorTable() {
    727   delete &getSelectorTableImpl(Impl);
    728 }
    729 
    730 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
    731   switch (Operator) {
    732   case OO_None:
    733   case NUM_OVERLOADED_OPERATORS:
    734     return nullptr;
    735 
    736 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
    737   case OO_##Name: return Spelling;
    738 #include "clang/Basic/OperatorKinds.def"
    739   }
    740 
    741   llvm_unreachable("Invalid OverloadedOperatorKind!");
    742 }
    743 
    744 StringRef clang::getNullabilitySpelling(NullabilityKind kind,
    745                                         bool isContextSensitive) {
    746   switch (kind) {
    747   case NullabilityKind::NonNull:
    748     return isContextSensitive ? "nonnull" : "_Nonnull";
    749 
    750   case NullabilityKind::Nullable:
    751     return isContextSensitive ? "nullable" : "_Nullable";
    752 
    753   case NullabilityKind::NullableResult:
    754     assert(!isContextSensitive &&
    755            "_Nullable_result isn't supported as context-sensitive keyword");
    756     return "_Nullable_result";
    757 
    758   case NullabilityKind::Unspecified:
    759     return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
    760   }
    761   llvm_unreachable("Unknown nullability kind.");
    762 }
    763