xref: /freebsd/contrib/llvm-project/clang/lib/Basic/IdentifierTable.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
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   // Add the 'import' contextual keyword.
231   get("import").setModulesImport(true);
232 }
233 
234 /// Checks if the specified token kind represents a keyword in the
235 /// specified language.
236 /// \returns Status of the keyword in the language.
237 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
238                                       tok::TokenKind K) {
239   switch (K) {
240 #define KEYWORD(NAME, FLAGS) \
241   case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
242 #include "clang/Basic/TokenKinds.def"
243   default: return KS_Disabled;
244   }
245 }
246 
247 /// Returns true if the identifier represents a keyword in the
248 /// specified language.
249 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
250   switch (getTokenKwStatus(LangOpts, getTokenID())) {
251   case KS_Enabled:
252   case KS_Extension:
253     return true;
254   default:
255     return false;
256   }
257 }
258 
259 /// Returns true if the identifier represents a C++ keyword in the
260 /// specified language.
261 bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
262   if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
263     return false;
264   // This is a C++ keyword if this identifier is not a keyword when checked
265   // using LangOptions without C++ support.
266   LangOptions LangOptsNoCPP = LangOpts;
267   LangOptsNoCPP.CPlusPlus = false;
268   LangOptsNoCPP.CPlusPlus11 = false;
269   LangOptsNoCPP.CPlusPlus20 = false;
270   return !isKeyword(LangOptsNoCPP);
271 }
272 
273 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
274   // We use a perfect hash function here involving the length of the keyword,
275   // the first and third character.  For preprocessor ID's there are no
276   // collisions (if there were, the switch below would complain about duplicate
277   // case values).  Note that this depends on 'if' being null terminated.
278 
279 #define HASH(LEN, FIRST, THIRD) \
280   (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
281 #define CASE(LEN, FIRST, THIRD, NAME) \
282   case HASH(LEN, FIRST, THIRD): \
283     return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
284 
285   unsigned Len = getLength();
286   if (Len < 2) return tok::pp_not_keyword;
287   const char *Name = getNameStart();
288   switch (HASH(Len, Name[0], Name[2])) {
289   default: return tok::pp_not_keyword;
290   CASE( 2, 'i', '\0', if);
291   CASE( 4, 'e', 'i', elif);
292   CASE( 4, 'e', 's', else);
293   CASE( 4, 'l', 'n', line);
294   CASE( 4, 's', 'c', sccs);
295   CASE( 5, 'e', 'd', endif);
296   CASE( 5, 'e', 'r', error);
297   CASE( 5, 'i', 'e', ident);
298   CASE( 5, 'i', 'd', ifdef);
299   CASE( 5, 'u', 'd', undef);
300 
301   CASE( 6, 'a', 's', assert);
302   CASE( 6, 'd', 'f', define);
303   CASE( 6, 'i', 'n', ifndef);
304   CASE( 6, 'i', 'p', import);
305   CASE( 6, 'p', 'a', pragma);
306 
307   CASE( 7, 'd', 'f', defined);
308   CASE( 7, 'i', 'c', include);
309   CASE( 7, 'w', 'r', warning);
310 
311   CASE( 8, 'u', 'a', unassert);
312   CASE(12, 'i', 'c', include_next);
313 
314   CASE(14, '_', 'p', __public_macro);
315 
316   CASE(15, '_', 'p', __private_macro);
317 
318   CASE(16, '_', 'i', __include_macros);
319 #undef CASE
320 #undef HASH
321   }
322 }
323 
324 //===----------------------------------------------------------------------===//
325 // Stats Implementation
326 //===----------------------------------------------------------------------===//
327 
328 /// PrintStats - Print statistics about how well the identifier table is doing
329 /// at hashing identifiers.
330 void IdentifierTable::PrintStats() const {
331   unsigned NumBuckets = HashTable.getNumBuckets();
332   unsigned NumIdentifiers = HashTable.getNumItems();
333   unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
334   unsigned AverageIdentifierSize = 0;
335   unsigned MaxIdentifierLength = 0;
336 
337   // TODO: Figure out maximum times an identifier had to probe for -stats.
338   for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
339        I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
340     unsigned IdLen = I->getKeyLength();
341     AverageIdentifierSize += IdLen;
342     if (MaxIdentifierLength < IdLen)
343       MaxIdentifierLength = IdLen;
344   }
345 
346   fprintf(stderr, "\n*** Identifier Table Stats:\n");
347   fprintf(stderr, "# Identifiers:   %d\n", NumIdentifiers);
348   fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
349   fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
350           NumIdentifiers/(double)NumBuckets);
351   fprintf(stderr, "Ave identifier length: %f\n",
352           (AverageIdentifierSize/(double)NumIdentifiers));
353   fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
354 
355   // Compute statistics about the memory allocated for identifiers.
356   HashTable.getAllocator().PrintStats();
357 }
358 
359 //===----------------------------------------------------------------------===//
360 // SelectorTable Implementation
361 //===----------------------------------------------------------------------===//
362 
363 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
364   return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
365 }
366 
367 namespace clang {
368 
369 /// One of these variable length records is kept for each
370 /// selector containing more than one keyword. We use a folding set
371 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
372 /// this class is provided strictly through Selector.
373 class alignas(IdentifierInfoAlignment) MultiKeywordSelector
374     : public detail::DeclarationNameExtra,
375       public llvm::FoldingSetNode {
376   MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
377 
378 public:
379   // Constructor for keyword selectors.
380   MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
381       : DeclarationNameExtra(nKeys) {
382     assert((nKeys > 1) && "not a multi-keyword selector");
383 
384     // Fill in the trailing keyword array.
385     IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1);
386     for (unsigned i = 0; i != nKeys; ++i)
387       KeyInfo[i] = IIV[i];
388   }
389 
390   // getName - Derive the full selector name and return it.
391   std::string getName() const;
392 
393   using DeclarationNameExtra::getNumArgs;
394 
395   using keyword_iterator = IdentifierInfo *const *;
396 
397   keyword_iterator keyword_begin() const {
398     return reinterpret_cast<keyword_iterator>(this + 1);
399   }
400 
401   keyword_iterator keyword_end() const {
402     return keyword_begin() + getNumArgs();
403   }
404 
405   IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
406     assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
407     return keyword_begin()[i];
408   }
409 
410   static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
411                       unsigned NumArgs) {
412     ID.AddInteger(NumArgs);
413     for (unsigned i = 0; i != NumArgs; ++i)
414       ID.AddPointer(ArgTys[i]);
415   }
416 
417   void Profile(llvm::FoldingSetNodeID &ID) {
418     Profile(ID, keyword_begin(), getNumArgs());
419   }
420 };
421 
422 } // namespace clang.
423 
424 bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const {
425   assert(!Names.empty() && "must have >= 1 selector slots");
426   if (getNumArgs() != Names.size())
427     return false;
428   for (unsigned I = 0, E = Names.size(); I != E; ++I) {
429     if (getNameForSlot(I) != Names[I])
430       return false;
431   }
432   return true;
433 }
434 
435 bool Selector::isUnarySelector(StringRef Name) const {
436   return isUnarySelector() && getNameForSlot(0) == Name;
437 }
438 
439 unsigned Selector::getNumArgs() const {
440   unsigned IIF = getIdentifierInfoFlag();
441   if (IIF <= ZeroArg)
442     return 0;
443   if (IIF == OneArg)
444     return 1;
445   // We point to a MultiKeywordSelector.
446   MultiKeywordSelector *SI = getMultiKeywordSelector();
447   return SI->getNumArgs();
448 }
449 
450 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
451   if (getIdentifierInfoFlag() < MultiArg) {
452     assert(argIndex == 0 && "illegal keyword index");
453     return getAsIdentifierInfo();
454   }
455 
456   // We point to a MultiKeywordSelector.
457   MultiKeywordSelector *SI = getMultiKeywordSelector();
458   return SI->getIdentifierInfoForSlot(argIndex);
459 }
460 
461 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
462   IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
463   return II ? II->getName() : StringRef();
464 }
465 
466 std::string MultiKeywordSelector::getName() const {
467   SmallString<256> Str;
468   llvm::raw_svector_ostream OS(Str);
469   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
470     if (*I)
471       OS << (*I)->getName();
472     OS << ':';
473   }
474 
475   return std::string(OS.str());
476 }
477 
478 std::string Selector::getAsString() const {
479   if (InfoPtr == 0)
480     return "<null selector>";
481 
482   if (getIdentifierInfoFlag() < MultiArg) {
483     IdentifierInfo *II = getAsIdentifierInfo();
484 
485     if (getNumArgs() == 0) {
486       assert(II && "If the number of arguments is 0 then II is guaranteed to "
487                    "not be null.");
488       return std::string(II->getName());
489     }
490 
491     if (!II)
492       return ":";
493 
494     return II->getName().str() + ":";
495   }
496 
497   // We have a multiple keyword selector.
498   return getMultiKeywordSelector()->getName();
499 }
500 
501 void Selector::print(llvm::raw_ostream &OS) const {
502   OS << getAsString();
503 }
504 
505 LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); }
506 
507 /// Interpreting the given string using the normal CamelCase
508 /// conventions, determine whether the given string starts with the
509 /// given "word", which is assumed to end in a lowercase letter.
510 static bool startsWithWord(StringRef name, StringRef word) {
511   if (name.size() < word.size()) return false;
512   return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
513           name.startswith(word));
514 }
515 
516 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
517   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
518   if (!first) return OMF_None;
519 
520   StringRef name = first->getName();
521   if (sel.isUnarySelector()) {
522     if (name == "autorelease") return OMF_autorelease;
523     if (name == "dealloc") return OMF_dealloc;
524     if (name == "finalize") return OMF_finalize;
525     if (name == "release") return OMF_release;
526     if (name == "retain") return OMF_retain;
527     if (name == "retainCount") return OMF_retainCount;
528     if (name == "self") return OMF_self;
529     if (name == "initialize") return OMF_initialize;
530   }
531 
532   if (name == "performSelector" || name == "performSelectorInBackground" ||
533       name == "performSelectorOnMainThread")
534     return OMF_performSelector;
535 
536   // The other method families may begin with a prefix of underscores.
537   while (!name.empty() && name.front() == '_')
538     name = name.substr(1);
539 
540   if (name.empty()) return OMF_None;
541   switch (name.front()) {
542   case 'a':
543     if (startsWithWord(name, "alloc")) return OMF_alloc;
544     break;
545   case 'c':
546     if (startsWithWord(name, "copy")) return OMF_copy;
547     break;
548   case 'i':
549     if (startsWithWord(name, "init")) return OMF_init;
550     break;
551   case 'm':
552     if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
553     break;
554   case 'n':
555     if (startsWithWord(name, "new")) return OMF_new;
556     break;
557   default:
558     break;
559   }
560 
561   return OMF_None;
562 }
563 
564 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
565   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
566   if (!first) return OIT_None;
567 
568   StringRef name = first->getName();
569 
570   if (name.empty()) return OIT_None;
571   switch (name.front()) {
572     case 'a':
573       if (startsWithWord(name, "array")) return OIT_Array;
574       break;
575     case 'd':
576       if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
577       if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
578       break;
579     case 's':
580       if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
581       if (startsWithWord(name, "standard")) return OIT_Singleton;
582       break;
583     case 'i':
584       if (startsWithWord(name, "init")) return OIT_Init;
585       break;
586     default:
587       break;
588   }
589   return OIT_None;
590 }
591 
592 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
593   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
594   if (!first) return SFF_None;
595 
596   StringRef name = first->getName();
597 
598   switch (name.front()) {
599     case 'a':
600       if (name == "appendFormat") return SFF_NSString;
601       break;
602 
603     case 'i':
604       if (name == "initWithFormat") return SFF_NSString;
605       break;
606 
607     case 'l':
608       if (name == "localizedStringWithFormat") return SFF_NSString;
609       break;
610 
611     case 's':
612       if (name == "stringByAppendingFormat" ||
613           name == "stringWithFormat") return SFF_NSString;
614       break;
615   }
616   return SFF_None;
617 }
618 
619 namespace {
620 
621 struct SelectorTableImpl {
622   llvm::FoldingSet<MultiKeywordSelector> Table;
623   llvm::BumpPtrAllocator Allocator;
624 };
625 
626 } // namespace
627 
628 static SelectorTableImpl &getSelectorTableImpl(void *P) {
629   return *static_cast<SelectorTableImpl*>(P);
630 }
631 
632 SmallString<64>
633 SelectorTable::constructSetterName(StringRef Name) {
634   SmallString<64> SetterName("set");
635   SetterName += Name;
636   SetterName[3] = toUppercase(SetterName[3]);
637   return SetterName;
638 }
639 
640 Selector
641 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
642                                        SelectorTable &SelTable,
643                                        const IdentifierInfo *Name) {
644   IdentifierInfo *SetterName =
645     &Idents.get(constructSetterName(Name->getName()));
646   return SelTable.getUnarySelector(SetterName);
647 }
648 
649 std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) {
650   StringRef Name = Sel.getNameForSlot(0);
651   assert(Name.startswith("set") && "invalid setter name");
652   return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str();
653 }
654 
655 size_t SelectorTable::getTotalMemory() const {
656   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
657   return SelTabImpl.Allocator.getTotalMemory();
658 }
659 
660 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
661   if (nKeys < 2)
662     return Selector(IIV[0], nKeys);
663 
664   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
665 
666   // Unique selector, to guarantee there is one per name.
667   llvm::FoldingSetNodeID ID;
668   MultiKeywordSelector::Profile(ID, IIV, nKeys);
669 
670   void *InsertPos = nullptr;
671   if (MultiKeywordSelector *SI =
672         SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
673     return Selector(SI);
674 
675   // MultiKeywordSelector objects are not allocated with new because they have a
676   // variable size array (for parameter types) at the end of them.
677   unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
678   MultiKeywordSelector *SI =
679       (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
680           Size, alignof(MultiKeywordSelector));
681   new (SI) MultiKeywordSelector(nKeys, IIV);
682   SelTabImpl.Table.InsertNode(SI, InsertPos);
683   return Selector(SI);
684 }
685 
686 SelectorTable::SelectorTable() {
687   Impl = new SelectorTableImpl();
688 }
689 
690 SelectorTable::~SelectorTable() {
691   delete &getSelectorTableImpl(Impl);
692 }
693 
694 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
695   switch (Operator) {
696   case OO_None:
697   case NUM_OVERLOADED_OPERATORS:
698     return nullptr;
699 
700 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
701   case OO_##Name: return Spelling;
702 #include "clang/Basic/OperatorKinds.def"
703   }
704 
705   llvm_unreachable("Invalid OverloadedOperatorKind!");
706 }
707 
708 StringRef clang::getNullabilitySpelling(NullabilityKind kind,
709                                         bool isContextSensitive) {
710   switch (kind) {
711   case NullabilityKind::NonNull:
712     return isContextSensitive ? "nonnull" : "_Nonnull";
713 
714   case NullabilityKind::Nullable:
715     return isContextSensitive ? "nullable" : "_Nullable";
716 
717   case NullabilityKind::Unspecified:
718     return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
719   }
720   llvm_unreachable("Unknown nullability kind.");
721 }
722