1 //===--- IdentifierTable.cpp - Hash table for identifier lookup -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the IdentifierInfo, IdentifierVisitor, and
11 // IdentifierTable interfaces.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Basic/IdentifierTable.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/CharInfo.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/Support/ErrorHandling.h"
21 #include "llvm/Support/raw_ostream.h"
24 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // IdentifierInfo Implementation
28 //===----------------------------------------------------------------------===//
30 IdentifierInfo::IdentifierInfo() {
31 TokenID = tok::identifier;
36 IsCXX11CompatKeyword = false;
38 IsCPPOperatorKeyword = false;
39 NeedsHandleIdentifier = false;
41 ChangedAfterLoad = false;
42 RevertedTokenID = false;
44 IsModulesImport = false;
49 //===----------------------------------------------------------------------===//
50 // IdentifierTable Implementation
51 //===----------------------------------------------------------------------===//
53 IdentifierIterator::~IdentifierIterator() { }
55 IdentifierInfoLookup::~IdentifierInfoLookup() {}
58 /// \brief A simple identifier lookup iterator that represents an
59 /// empty sequence of identifiers.
60 class EmptyLookupIterator : public IdentifierIterator
63 virtual StringRef Next() { return StringRef(); }
67 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
68 return new EmptyLookupIterator();
71 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
73 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
74 IdentifierInfoLookup* externalLookup)
75 : HashTable(8192), // Start with space for 8K identifiers.
76 ExternalLookup(externalLookup) {
78 // Populate the identifier table with info about keywords for the current
80 AddKeywords(LangOpts);
83 // Add the '_experimental_modules_import' contextual keyword.
84 get("import").setModulesImport(true);
87 //===----------------------------------------------------------------------===//
88 // Language Keyword Implementation
89 //===----------------------------------------------------------------------===//
91 // Constants for TokenKinds.def
107 WCHARSUPPORT = 0x02000,
108 KEYALL = (0xffff & ~KEYNOMS) // Because KEYNOMS is used to exclude.
112 /// AddKeyword - This method is used to associate a token ID with specific
113 /// identifiers because they are language keywords. This causes the lexer to
114 /// automatically map matching identifiers to specialized token codes.
116 /// The C90/C99/CPP/CPP0x flags are set to 3 if the token is a keyword in a
117 /// future language standard, set to 2 if the token should be enabled in the
118 /// specified language, set to 1 if it is an extension in the specified
119 /// language, and set to 0 if disabled in the specified language.
120 static void AddKeyword(StringRef Keyword,
121 tok::TokenKind TokenCode, unsigned Flags,
122 const LangOptions &LangOpts, IdentifierTable &Table) {
123 unsigned AddResult = 0;
124 if (Flags == KEYALL) AddResult = 2;
125 else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
126 else if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) AddResult = 2;
127 else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
128 else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1;
129 else if (LangOpts.MicrosoftExt && (Flags & KEYMS)) AddResult = 1;
130 else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1;
131 else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2;
132 else if (LangOpts.WChar && (Flags & WCHARSUPPORT)) AddResult = 2;
133 else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2;
134 else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2;
135 else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2;
136 else if (LangOpts.C11 && (Flags & KEYC11)) AddResult = 2;
137 // We treat bridge casts as objective-C keywords so we can warn on them
139 else if (LangOpts.ObjC2 && (Flags & KEYARC)) AddResult = 2;
140 else if (LangOpts.CPlusPlus && (Flags & KEYCXX11)) AddResult = 3;
142 // Don't add this keyword under MicrosoftMode.
143 if (LangOpts.MicrosoftMode && (Flags & KEYNOMS))
145 // Don't add this keyword if disabled in this language.
146 if (AddResult == 0) return;
148 IdentifierInfo &Info =
149 Table.get(Keyword, AddResult == 3 ? tok::identifier : TokenCode);
150 Info.setIsExtensionToken(AddResult == 1);
151 Info.setIsCXX11CompatKeyword(AddResult == 3);
154 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
156 static void AddCXXOperatorKeyword(StringRef Keyword,
157 tok::TokenKind TokenCode,
158 IdentifierTable &Table) {
159 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
160 Info.setIsCPlusPlusOperatorKeyword();
163 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
165 static void AddObjCKeyword(StringRef Name,
166 tok::ObjCKeywordKind ObjCID,
167 IdentifierTable &Table) {
168 Table.get(Name).setObjCKeywordID(ObjCID);
171 /// AddKeywords - Add all keywords to the symbol table.
173 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
174 // Add keywords and tokens for the current language.
175 #define KEYWORD(NAME, FLAGS) \
176 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
177 FLAGS, LangOpts, *this);
178 #define ALIAS(NAME, TOK, FLAGS) \
179 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
180 FLAGS, LangOpts, *this);
181 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
182 if (LangOpts.CXXOperatorNames) \
183 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
184 #define OBJC1_AT_KEYWORD(NAME) \
185 if (LangOpts.ObjC1) \
186 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
187 #define OBJC2_AT_KEYWORD(NAME) \
188 if (LangOpts.ObjC2) \
189 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
190 #define TESTING_KEYWORD(NAME, FLAGS)
191 #include "clang/Basic/TokenKinds.def"
193 if (LangOpts.ParseUnknownAnytype)
194 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
198 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
199 // We use a perfect hash function here involving the length of the keyword,
200 // the first and third character. For preprocessor ID's there are no
201 // collisions (if there were, the switch below would complain about duplicate
202 // case values). Note that this depends on 'if' being null terminated.
204 #define HASH(LEN, FIRST, THIRD) \
205 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
206 #define CASE(LEN, FIRST, THIRD, NAME) \
207 case HASH(LEN, FIRST, THIRD): \
208 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
210 unsigned Len = getLength();
211 if (Len < 2) return tok::pp_not_keyword;
212 const char *Name = getNameStart();
213 switch (HASH(Len, Name[0], Name[2])) {
214 default: return tok::pp_not_keyword;
215 CASE( 2, 'i', '\0', if);
216 CASE( 4, 'e', 'i', elif);
217 CASE( 4, 'e', 's', else);
218 CASE( 4, 'l', 'n', line);
219 CASE( 4, 's', 'c', sccs);
220 CASE( 5, 'e', 'd', endif);
221 CASE( 5, 'e', 'r', error);
222 CASE( 5, 'i', 'e', ident);
223 CASE( 5, 'i', 'd', ifdef);
224 CASE( 5, 'u', 'd', undef);
226 CASE( 6, 'a', 's', assert);
227 CASE( 6, 'd', 'f', define);
228 CASE( 6, 'i', 'n', ifndef);
229 CASE( 6, 'i', 'p', import);
230 CASE( 6, 'p', 'a', pragma);
232 CASE( 7, 'd', 'f', defined);
233 CASE( 7, 'i', 'c', include);
234 CASE( 7, 'w', 'r', warning);
236 CASE( 8, 'u', 'a', unassert);
237 CASE(12, 'i', 'c', include_next);
239 CASE(14, '_', 'p', __public_macro);
241 CASE(15, '_', 'p', __private_macro);
243 CASE(16, '_', 'i', __include_macros);
249 //===----------------------------------------------------------------------===//
250 // Stats Implementation
251 //===----------------------------------------------------------------------===//
253 /// PrintStats - Print statistics about how well the identifier table is doing
254 /// at hashing identifiers.
255 void IdentifierTable::PrintStats() const {
256 unsigned NumBuckets = HashTable.getNumBuckets();
257 unsigned NumIdentifiers = HashTable.getNumItems();
258 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
259 unsigned AverageIdentifierSize = 0;
260 unsigned MaxIdentifierLength = 0;
262 // TODO: Figure out maximum times an identifier had to probe for -stats.
263 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
264 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
265 unsigned IdLen = I->getKeyLength();
266 AverageIdentifierSize += IdLen;
267 if (MaxIdentifierLength < IdLen)
268 MaxIdentifierLength = IdLen;
271 fprintf(stderr, "\n*** Identifier Table Stats:\n");
272 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
273 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
274 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
275 NumIdentifiers/(double)NumBuckets);
276 fprintf(stderr, "Ave identifier length: %f\n",
277 (AverageIdentifierSize/(double)NumIdentifiers));
278 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
280 // Compute statistics about the memory allocated for identifiers.
281 HashTable.getAllocator().PrintStats();
284 //===----------------------------------------------------------------------===//
285 // SelectorTable Implementation
286 //===----------------------------------------------------------------------===//
288 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
289 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
293 /// MultiKeywordSelector - One of these variable length records is kept for each
294 /// selector containing more than one keyword. We use a folding set
295 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
296 /// this class is provided strictly through Selector.
297 class MultiKeywordSelector
298 : public DeclarationNameExtra, public llvm::FoldingSetNode {
299 MultiKeywordSelector(unsigned nKeys) {
300 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
303 // Constructor for keyword selectors.
304 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
305 assert((nKeys > 1) && "not a multi-keyword selector");
306 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
308 // Fill in the trailing keyword array.
309 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
310 for (unsigned i = 0; i != nKeys; ++i)
314 // getName - Derive the full selector name and return it.
315 std::string getName() const;
317 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
319 typedef IdentifierInfo *const *keyword_iterator;
320 keyword_iterator keyword_begin() const {
321 return reinterpret_cast<keyword_iterator>(this+1);
323 keyword_iterator keyword_end() const {
324 return keyword_begin()+getNumArgs();
326 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
327 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
328 return keyword_begin()[i];
330 static void Profile(llvm::FoldingSetNodeID &ID,
331 keyword_iterator ArgTys, unsigned NumArgs) {
332 ID.AddInteger(NumArgs);
333 for (unsigned i = 0; i != NumArgs; ++i)
334 ID.AddPointer(ArgTys[i]);
336 void Profile(llvm::FoldingSetNodeID &ID) {
337 Profile(ID, keyword_begin(), getNumArgs());
340 } // end namespace clang.
342 unsigned Selector::getNumArgs() const {
343 unsigned IIF = getIdentifierInfoFlag();
348 // We point to a MultiKeywordSelector.
349 MultiKeywordSelector *SI = getMultiKeywordSelector();
350 return SI->getNumArgs();
353 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
354 if (getIdentifierInfoFlag() < MultiArg) {
355 assert(argIndex == 0 && "illegal keyword index");
356 return getAsIdentifierInfo();
358 // We point to a MultiKeywordSelector.
359 MultiKeywordSelector *SI = getMultiKeywordSelector();
360 return SI->getIdentifierInfoForSlot(argIndex);
363 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
364 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
365 return II? II->getName() : StringRef();
368 std::string MultiKeywordSelector::getName() const {
369 SmallString<256> Str;
370 llvm::raw_svector_ostream OS(Str);
371 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
373 OS << (*I)->getName();
380 std::string Selector::getAsString() const {
382 return "<null selector>";
384 if (getIdentifierInfoFlag() < MultiArg) {
385 IdentifierInfo *II = getAsIdentifierInfo();
387 // If the number of arguments is 0 then II is guaranteed to not be null.
388 if (getNumArgs() == 0)
389 return II->getName();
394 return II->getName().str() + ":";
397 // We have a multiple keyword selector.
398 return getMultiKeywordSelector()->getName();
401 /// Interpreting the given string using the normal CamelCase
402 /// conventions, determine whether the given string starts with the
403 /// given "word", which is assumed to end in a lowercase letter.
404 static bool startsWithWord(StringRef name, StringRef word) {
405 if (name.size() < word.size()) return false;
406 return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
407 name.startswith(word));
410 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
411 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
412 if (!first) return OMF_None;
414 StringRef name = first->getName();
415 if (sel.isUnarySelector()) {
416 if (name == "autorelease") return OMF_autorelease;
417 if (name == "dealloc") return OMF_dealloc;
418 if (name == "finalize") return OMF_finalize;
419 if (name == "release") return OMF_release;
420 if (name == "retain") return OMF_retain;
421 if (name == "retainCount") return OMF_retainCount;
422 if (name == "self") return OMF_self;
425 if (name == "performSelector") return OMF_performSelector;
427 // The other method families may begin with a prefix of underscores.
428 while (!name.empty() && name.front() == '_')
429 name = name.substr(1);
431 if (name.empty()) return OMF_None;
432 switch (name.front()) {
434 if (startsWithWord(name, "alloc")) return OMF_alloc;
437 if (startsWithWord(name, "copy")) return OMF_copy;
440 if (startsWithWord(name, "init")) return OMF_init;
443 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
446 if (startsWithWord(name, "new")) return OMF_new;
455 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
456 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
457 if (!first) return OIT_None;
459 StringRef name = first->getName();
461 if (name.empty()) return OIT_None;
462 switch (name.front()) {
464 if (startsWithWord(name, "array")) return OIT_Array;
467 if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
468 if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
471 if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
472 if (startsWithWord(name, "standard")) return OIT_Singleton;
474 if (startsWithWord(name, "init")) return OIT_Init;
482 struct SelectorTableImpl {
483 llvm::FoldingSet<MultiKeywordSelector> Table;
484 llvm::BumpPtrAllocator Allocator;
486 } // end anonymous namespace.
488 static SelectorTableImpl &getSelectorTableImpl(void *P) {
489 return *static_cast<SelectorTableImpl*>(P);
493 SelectorTable::constructSetterName(StringRef Name) {
494 SmallString<64> SetterName("set");
496 SetterName[3] = toUppercase(SetterName[3]);
501 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
502 SelectorTable &SelTable,
503 const IdentifierInfo *Name) {
504 IdentifierInfo *SetterName =
505 &Idents.get(constructSetterName(Name->getName()));
506 return SelTable.getUnarySelector(SetterName);
509 size_t SelectorTable::getTotalMemory() const {
510 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
511 return SelTabImpl.Allocator.getTotalMemory();
514 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
516 return Selector(IIV[0], nKeys);
518 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
520 // Unique selector, to guarantee there is one per name.
521 llvm::FoldingSetNodeID ID;
522 MultiKeywordSelector::Profile(ID, IIV, nKeys);
525 if (MultiKeywordSelector *SI =
526 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
529 // MultiKeywordSelector objects are not allocated with new because they have a
530 // variable size array (for parameter types) at the end of them.
531 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
532 MultiKeywordSelector *SI =
533 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
534 llvm::alignOf<MultiKeywordSelector>());
535 new (SI) MultiKeywordSelector(nKeys, IIV);
536 SelTabImpl.Table.InsertNode(SI, InsertPos);
540 SelectorTable::SelectorTable() {
541 Impl = new SelectorTableImpl();
544 SelectorTable::~SelectorTable() {
545 delete &getSelectorTableImpl(Impl);
548 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
551 case NUM_OVERLOADED_OPERATORS:
554 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
555 case OO_##Name: return Spelling;
556 #include "clang/Basic/OperatorKinds.def"
559 llvm_unreachable("Invalid OverloadedOperatorKind!");