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/CharInfo.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/FoldingSet.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Support/ErrorHandling.h"
22 #include "llvm/Support/raw_ostream.h"
25 using namespace clang;
27 //===----------------------------------------------------------------------===//
28 // IdentifierInfo Implementation
29 //===----------------------------------------------------------------------===//
31 IdentifierInfo::IdentifierInfo() {
32 TokenID = tok::identifier;
37 IsCXX11CompatKeyword = false;
39 IsCPPOperatorKeyword = false;
40 NeedsHandleIdentifier = false;
42 ChangedAfterLoad = false;
43 RevertedTokenID = false;
45 IsModulesImport = false;
50 //===----------------------------------------------------------------------===//
51 // IdentifierTable Implementation
52 //===----------------------------------------------------------------------===//
54 IdentifierIterator::~IdentifierIterator() { }
56 IdentifierInfoLookup::~IdentifierInfoLookup() {}
59 /// \brief A simple identifier lookup iterator that represents an
60 /// empty sequence of identifiers.
61 class EmptyLookupIterator : public IdentifierIterator
64 virtual StringRef Next() { return StringRef(); }
68 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
69 return new EmptyLookupIterator();
72 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
74 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
75 IdentifierInfoLookup* externalLookup)
76 : HashTable(8192), // Start with space for 8K identifiers.
77 ExternalLookup(externalLookup) {
79 // Populate the identifier table with info about keywords for the current
81 AddKeywords(LangOpts);
84 // Add the '_experimental_modules_import' contextual keyword.
85 get("import").setModulesImport(true);
88 //===----------------------------------------------------------------------===//
89 // Language Keyword Implementation
90 //===----------------------------------------------------------------------===//
92 // Constants for TokenKinds.def
108 WCHARSUPPORT = 0x02000,
109 KEYALL = (0xffff & ~KEYNOMS) // Because KEYNOMS is used to exclude.
113 /// AddKeyword - This method is used to associate a token ID with specific
114 /// identifiers because they are language keywords. This causes the lexer to
115 /// automatically map matching identifiers to specialized token codes.
117 /// The C90/C99/CPP/CPP0x flags are set to 3 if the token is a keyword in a
118 /// future language standard, set to 2 if the token should be enabled in the
119 /// specified language, set to 1 if it is an extension in the specified
120 /// language, and set to 0 if disabled in the specified language.
121 static void AddKeyword(StringRef Keyword,
122 tok::TokenKind TokenCode, unsigned Flags,
123 const LangOptions &LangOpts, IdentifierTable &Table) {
124 unsigned AddResult = 0;
125 if (Flags == KEYALL) AddResult = 2;
126 else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
127 else if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) AddResult = 2;
128 else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
129 else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1;
130 else if (LangOpts.MicrosoftExt && (Flags & KEYMS)) AddResult = 1;
131 else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1;
132 else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2;
133 else if (LangOpts.WChar && (Flags & WCHARSUPPORT)) AddResult = 2;
134 else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2;
135 else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2;
136 else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2;
137 else if (LangOpts.C11 && (Flags & KEYC11)) AddResult = 2;
138 // We treat bridge casts as objective-C keywords so we can warn on them
140 else if (LangOpts.ObjC2 && (Flags & KEYARC)) AddResult = 2;
141 else if (LangOpts.CPlusPlus && (Flags & KEYCXX11)) AddResult = 3;
143 // Don't add this keyword under MicrosoftMode.
144 if (LangOpts.MicrosoftMode && (Flags & KEYNOMS))
146 // Don't add this keyword if disabled in this language.
147 if (AddResult == 0) return;
149 IdentifierInfo &Info =
150 Table.get(Keyword, AddResult == 3 ? tok::identifier : TokenCode);
151 Info.setIsExtensionToken(AddResult == 1);
152 Info.setIsCXX11CompatKeyword(AddResult == 3);
155 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
157 static void AddCXXOperatorKeyword(StringRef Keyword,
158 tok::TokenKind TokenCode,
159 IdentifierTable &Table) {
160 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
161 Info.setIsCPlusPlusOperatorKeyword();
164 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
166 static void AddObjCKeyword(StringRef Name,
167 tok::ObjCKeywordKind ObjCID,
168 IdentifierTable &Table) {
169 Table.get(Name).setObjCKeywordID(ObjCID);
172 /// AddKeywords - Add all keywords to the symbol table.
174 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
175 // Add keywords and tokens for the current language.
176 #define KEYWORD(NAME, FLAGS) \
177 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
178 FLAGS, LangOpts, *this);
179 #define ALIAS(NAME, TOK, FLAGS) \
180 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
181 FLAGS, LangOpts, *this);
182 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
183 if (LangOpts.CXXOperatorNames) \
184 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
185 #define OBJC1_AT_KEYWORD(NAME) \
186 if (LangOpts.ObjC1) \
187 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
188 #define OBJC2_AT_KEYWORD(NAME) \
189 if (LangOpts.ObjC2) \
190 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
191 #define TESTING_KEYWORD(NAME, FLAGS)
192 #include "clang/Basic/TokenKinds.def"
194 if (LangOpts.ParseUnknownAnytype)
195 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
199 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
200 // We use a perfect hash function here involving the length of the keyword,
201 // the first and third character. For preprocessor ID's there are no
202 // collisions (if there were, the switch below would complain about duplicate
203 // case values). Note that this depends on 'if' being null terminated.
205 #define HASH(LEN, FIRST, THIRD) \
206 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
207 #define CASE(LEN, FIRST, THIRD, NAME) \
208 case HASH(LEN, FIRST, THIRD): \
209 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
211 unsigned Len = getLength();
212 if (Len < 2) return tok::pp_not_keyword;
213 const char *Name = getNameStart();
214 switch (HASH(Len, Name[0], Name[2])) {
215 default: return tok::pp_not_keyword;
216 CASE( 2, 'i', '\0', if);
217 CASE( 4, 'e', 'i', elif);
218 CASE( 4, 'e', 's', else);
219 CASE( 4, 'l', 'n', line);
220 CASE( 4, 's', 'c', sccs);
221 CASE( 5, 'e', 'd', endif);
222 CASE( 5, 'e', 'r', error);
223 CASE( 5, 'i', 'e', ident);
224 CASE( 5, 'i', 'd', ifdef);
225 CASE( 5, 'u', 'd', undef);
227 CASE( 6, 'a', 's', assert);
228 CASE( 6, 'd', 'f', define);
229 CASE( 6, 'i', 'n', ifndef);
230 CASE( 6, 'i', 'p', import);
231 CASE( 6, 'p', 'a', pragma);
233 CASE( 7, 'd', 'f', defined);
234 CASE( 7, 'i', 'c', include);
235 CASE( 7, 'w', 'r', warning);
237 CASE( 8, 'u', 'a', unassert);
238 CASE(12, 'i', 'c', include_next);
240 CASE(14, '_', 'p', __public_macro);
242 CASE(15, '_', 'p', __private_macro);
244 CASE(16, '_', 'i', __include_macros);
250 //===----------------------------------------------------------------------===//
251 // Stats Implementation
252 //===----------------------------------------------------------------------===//
254 /// PrintStats - Print statistics about how well the identifier table is doing
255 /// at hashing identifiers.
256 void IdentifierTable::PrintStats() const {
257 unsigned NumBuckets = HashTable.getNumBuckets();
258 unsigned NumIdentifiers = HashTable.getNumItems();
259 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
260 unsigned AverageIdentifierSize = 0;
261 unsigned MaxIdentifierLength = 0;
263 // TODO: Figure out maximum times an identifier had to probe for -stats.
264 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
265 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
266 unsigned IdLen = I->getKeyLength();
267 AverageIdentifierSize += IdLen;
268 if (MaxIdentifierLength < IdLen)
269 MaxIdentifierLength = IdLen;
272 fprintf(stderr, "\n*** Identifier Table Stats:\n");
273 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
274 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
275 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
276 NumIdentifiers/(double)NumBuckets);
277 fprintf(stderr, "Ave identifier length: %f\n",
278 (AverageIdentifierSize/(double)NumIdentifiers));
279 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
281 // Compute statistics about the memory allocated for identifiers.
282 HashTable.getAllocator().PrintStats();
285 //===----------------------------------------------------------------------===//
286 // SelectorTable Implementation
287 //===----------------------------------------------------------------------===//
289 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
290 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
294 /// MultiKeywordSelector - One of these variable length records is kept for each
295 /// selector containing more than one keyword. We use a folding set
296 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
297 /// this class is provided strictly through Selector.
298 class MultiKeywordSelector
299 : public DeclarationNameExtra, public llvm::FoldingSetNode {
300 MultiKeywordSelector(unsigned nKeys) {
301 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
304 // Constructor for keyword selectors.
305 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
306 assert((nKeys > 1) && "not a multi-keyword selector");
307 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
309 // Fill in the trailing keyword array.
310 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
311 for (unsigned i = 0; i != nKeys; ++i)
315 // getName - Derive the full selector name and return it.
316 std::string getName() const;
318 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
320 typedef IdentifierInfo *const *keyword_iterator;
321 keyword_iterator keyword_begin() const {
322 return reinterpret_cast<keyword_iterator>(this+1);
324 keyword_iterator keyword_end() const {
325 return keyword_begin()+getNumArgs();
327 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
328 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
329 return keyword_begin()[i];
331 static void Profile(llvm::FoldingSetNodeID &ID,
332 keyword_iterator ArgTys, unsigned NumArgs) {
333 ID.AddInteger(NumArgs);
334 for (unsigned i = 0; i != NumArgs; ++i)
335 ID.AddPointer(ArgTys[i]);
337 void Profile(llvm::FoldingSetNodeID &ID) {
338 Profile(ID, keyword_begin(), getNumArgs());
341 } // end namespace clang.
343 unsigned Selector::getNumArgs() const {
344 unsigned IIF = getIdentifierInfoFlag();
349 // We point to a MultiKeywordSelector.
350 MultiKeywordSelector *SI = getMultiKeywordSelector();
351 return SI->getNumArgs();
354 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
355 if (getIdentifierInfoFlag() < MultiArg) {
356 assert(argIndex == 0 && "illegal keyword index");
357 return getAsIdentifierInfo();
359 // We point to a MultiKeywordSelector.
360 MultiKeywordSelector *SI = getMultiKeywordSelector();
361 return SI->getIdentifierInfoForSlot(argIndex);
364 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
365 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
366 return II? II->getName() : StringRef();
369 std::string MultiKeywordSelector::getName() const {
370 SmallString<256> Str;
371 llvm::raw_svector_ostream OS(Str);
372 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
374 OS << (*I)->getName();
381 std::string Selector::getAsString() const {
383 return "<null selector>";
385 if (getIdentifierInfoFlag() < MultiArg) {
386 IdentifierInfo *II = getAsIdentifierInfo();
388 // If the number of arguments is 0 then II is guaranteed to not be null.
389 if (getNumArgs() == 0)
390 return II->getName();
395 return II->getName().str() + ":";
398 // We have a multiple keyword selector.
399 return getMultiKeywordSelector()->getName();
402 /// Interpreting the given string using the normal CamelCase
403 /// conventions, determine whether the given string starts with the
404 /// given "word", which is assumed to end in a lowercase letter.
405 static bool startsWithWord(StringRef name, StringRef word) {
406 if (name.size() < word.size()) return false;
407 return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
408 name.startswith(word));
411 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
412 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
413 if (!first) return OMF_None;
415 StringRef name = first->getName();
416 if (sel.isUnarySelector()) {
417 if (name == "autorelease") return OMF_autorelease;
418 if (name == "dealloc") return OMF_dealloc;
419 if (name == "finalize") return OMF_finalize;
420 if (name == "release") return OMF_release;
421 if (name == "retain") return OMF_retain;
422 if (name == "retainCount") return OMF_retainCount;
423 if (name == "self") return OMF_self;
426 if (name == "performSelector") return OMF_performSelector;
428 // The other method families may begin with a prefix of underscores.
429 while (!name.empty() && name.front() == '_')
430 name = name.substr(1);
432 if (name.empty()) return OMF_None;
433 switch (name.front()) {
435 if (startsWithWord(name, "alloc")) return OMF_alloc;
438 if (startsWithWord(name, "copy")) return OMF_copy;
441 if (startsWithWord(name, "init")) return OMF_init;
444 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
447 if (startsWithWord(name, "new")) return OMF_new;
457 struct SelectorTableImpl {
458 llvm::FoldingSet<MultiKeywordSelector> Table;
459 llvm::BumpPtrAllocator Allocator;
461 } // end anonymous namespace.
463 static SelectorTableImpl &getSelectorTableImpl(void *P) {
464 return *static_cast<SelectorTableImpl*>(P);
468 SelectorTable::constructSetterName(IdentifierTable &Idents,
469 SelectorTable &SelTable,
470 const IdentifierInfo *Name) {
471 SmallString<100> SelectorName;
472 SelectorName = "set";
473 SelectorName += Name->getName();
474 SelectorName[3] = toUppercase(SelectorName[3]);
475 IdentifierInfo *SetterName = &Idents.get(SelectorName);
476 return SelTable.getUnarySelector(SetterName);
479 size_t SelectorTable::getTotalMemory() const {
480 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
481 return SelTabImpl.Allocator.getTotalMemory();
484 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
486 return Selector(IIV[0], nKeys);
488 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
490 // Unique selector, to guarantee there is one per name.
491 llvm::FoldingSetNodeID ID;
492 MultiKeywordSelector::Profile(ID, IIV, nKeys);
495 if (MultiKeywordSelector *SI =
496 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
499 // MultiKeywordSelector objects are not allocated with new because they have a
500 // variable size array (for parameter types) at the end of them.
501 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
502 MultiKeywordSelector *SI =
503 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
504 llvm::alignOf<MultiKeywordSelector>());
505 new (SI) MultiKeywordSelector(nKeys, IIV);
506 SelTabImpl.Table.InsertNode(SI, InsertPos);
510 SelectorTable::SelectorTable() {
511 Impl = new SelectorTableImpl();
514 SelectorTable::~SelectorTable() {
515 delete &getSelectorTableImpl(Impl);
518 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
521 case NUM_OVERLOADED_OPERATORS:
524 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
525 case OO_##Name: return Spelling;
526 #include "clang/Basic/OperatorKinds.def"
529 llvm_unreachable("Invalid OverloadedOperatorKind!");