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