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