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 "llvm/ADT/FoldingSet.h"
18 #include "llvm/ADT/DenseMap.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
25 //===----------------------------------------------------------------------===//
26 // IdentifierInfo Implementation
27 //===----------------------------------------------------------------------===//
29 IdentifierInfo::IdentifierInfo() {
30 TokenID = tok::identifier;
35 IsCPPOperatorKeyword = false;
36 NeedsHandleIdentifier = false;
38 RevertedTokenID = false;
43 //===----------------------------------------------------------------------===//
44 // IdentifierTable Implementation
45 //===----------------------------------------------------------------------===//
47 IdentifierIterator::~IdentifierIterator() { }
49 IdentifierInfoLookup::~IdentifierInfoLookup() {}
52 /// \brief A simple identifier lookup iterator that represents an
53 /// empty sequence of identifiers.
54 class EmptyLookupIterator : public IdentifierIterator
57 virtual llvm::StringRef Next() { return llvm::StringRef(); }
61 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() const {
62 return new EmptyLookupIterator();
65 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
67 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
68 IdentifierInfoLookup* externalLookup)
69 : HashTable(8192), // Start with space for 8K identifiers.
70 ExternalLookup(externalLookup) {
72 // Populate the identifier table with info about keywords for the current
74 AddKeywords(LangOpts);
77 //===----------------------------------------------------------------------===//
78 // Language Keyword Implementation
79 //===----------------------------------------------------------------------===//
81 // Constants for TokenKinds.def
99 /// AddKeyword - This method is used to associate a token ID with specific
100 /// identifiers because they are language keywords. This causes the lexer to
101 /// automatically map matching identifiers to specialized token codes.
103 /// The C90/C99/CPP/CPP0x flags are set to 2 if the token should be
104 /// enabled in the specified langauge, set to 1 if it is an extension
105 /// in the specified language, and set to 0 if disabled in the
106 /// specified language.
107 static void AddKeyword(llvm::StringRef Keyword,
108 tok::TokenKind TokenCode, unsigned Flags,
109 const LangOptions &LangOpts, IdentifierTable &Table) {
110 unsigned AddResult = 0;
111 if (Flags == KEYALL) AddResult = 2;
112 else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
113 else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2;
114 else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
115 else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1;
116 else if (LangOpts.Microsoft && (Flags & KEYMS)) AddResult = 1;
117 else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1;
118 else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2;
119 else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2;
120 else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2;
121 else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2;
122 else if (LangOpts.C1X && (Flags & KEYC1X)) AddResult = 2;
124 // Don't add this keyword if disabled in this language.
125 if (AddResult == 0) return;
127 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
128 Info.setIsExtensionToken(AddResult == 1);
131 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
133 static void AddCXXOperatorKeyword(llvm::StringRef Keyword,
134 tok::TokenKind TokenCode,
135 IdentifierTable &Table) {
136 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
137 Info.setIsCPlusPlusOperatorKeyword();
140 /// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
142 static void AddObjCKeyword(llvm::StringRef Name,
143 tok::ObjCKeywordKind ObjCID,
144 IdentifierTable &Table) {
145 Table.get(Name).setObjCKeywordID(ObjCID);
148 /// AddKeywords - Add all keywords to the symbol table.
150 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
151 // Add keywords and tokens for the current language.
152 #define KEYWORD(NAME, FLAGS) \
153 AddKeyword(llvm::StringRef(#NAME), tok::kw_ ## NAME, \
154 FLAGS, LangOpts, *this);
155 #define ALIAS(NAME, TOK, FLAGS) \
156 AddKeyword(llvm::StringRef(NAME), tok::kw_ ## TOK, \
157 FLAGS, LangOpts, *this);
158 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
159 if (LangOpts.CXXOperatorNames) \
160 AddCXXOperatorKeyword(llvm::StringRef(#NAME), tok::ALIAS, *this);
161 #define OBJC1_AT_KEYWORD(NAME) \
162 if (LangOpts.ObjC1) \
163 AddObjCKeyword(llvm::StringRef(#NAME), tok::objc_##NAME, *this);
164 #define OBJC2_AT_KEYWORD(NAME) \
165 if (LangOpts.ObjC2) \
166 AddObjCKeyword(llvm::StringRef(#NAME), tok::objc_##NAME, *this);
167 #define TESTING_KEYWORD(NAME, FLAGS)
168 #include "clang/Basic/TokenKinds.def"
170 if (LangOpts.ParseUnknownAnytype)
171 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
175 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
176 // We use a perfect hash function here involving the length of the keyword,
177 // the first and third character. For preprocessor ID's there are no
178 // collisions (if there were, the switch below would complain about duplicate
179 // case values). Note that this depends on 'if' being null terminated.
181 #define HASH(LEN, FIRST, THIRD) \
182 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
183 #define CASE(LEN, FIRST, THIRD, NAME) \
184 case HASH(LEN, FIRST, THIRD): \
185 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
187 unsigned Len = getLength();
188 if (Len < 2) return tok::pp_not_keyword;
189 const char *Name = getNameStart();
190 switch (HASH(Len, Name[0], Name[2])) {
191 default: return tok::pp_not_keyword;
192 CASE( 2, 'i', '\0', if);
193 CASE( 4, 'e', 'i', elif);
194 CASE( 4, 'e', 's', else);
195 CASE( 4, 'l', 'n', line);
196 CASE( 4, 's', 'c', sccs);
197 CASE( 5, 'e', 'd', endif);
198 CASE( 5, 'e', 'r', error);
199 CASE( 5, 'i', 'e', ident);
200 CASE( 5, 'i', 'd', ifdef);
201 CASE( 5, 'u', 'd', undef);
203 CASE( 6, 'a', 's', assert);
204 CASE( 6, 'd', 'f', define);
205 CASE( 6, 'i', 'n', ifndef);
206 CASE( 6, 'i', 'p', import);
207 CASE( 6, 'p', 'a', pragma);
209 CASE( 7, 'd', 'f', defined);
210 CASE( 7, 'i', 'c', include);
211 CASE( 7, 'w', 'r', warning);
213 CASE( 8, 'u', 'a', unassert);
214 CASE(12, 'i', 'c', include_next);
216 CASE(16, '_', 'i', __include_macros);
222 //===----------------------------------------------------------------------===//
223 // Stats Implementation
224 //===----------------------------------------------------------------------===//
226 /// PrintStats - Print statistics about how well the identifier table is doing
227 /// at hashing identifiers.
228 void IdentifierTable::PrintStats() const {
229 unsigned NumBuckets = HashTable.getNumBuckets();
230 unsigned NumIdentifiers = HashTable.getNumItems();
231 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
232 unsigned AverageIdentifierSize = 0;
233 unsigned MaxIdentifierLength = 0;
235 // TODO: Figure out maximum times an identifier had to probe for -stats.
236 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
237 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
238 unsigned IdLen = I->getKeyLength();
239 AverageIdentifierSize += IdLen;
240 if (MaxIdentifierLength < IdLen)
241 MaxIdentifierLength = IdLen;
244 fprintf(stderr, "\n*** Identifier Table Stats:\n");
245 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
246 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
247 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
248 NumIdentifiers/(double)NumBuckets);
249 fprintf(stderr, "Ave identifier length: %f\n",
250 (AverageIdentifierSize/(double)NumIdentifiers));
251 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
253 // Compute statistics about the memory allocated for identifiers.
254 HashTable.getAllocator().PrintStats();
257 //===----------------------------------------------------------------------===//
258 // SelectorTable Implementation
259 //===----------------------------------------------------------------------===//
261 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
262 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
266 /// MultiKeywordSelector - One of these variable length records is kept for each
267 /// selector containing more than one keyword. We use a folding set
268 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
269 /// this class is provided strictly through Selector.
270 class MultiKeywordSelector
271 : public DeclarationNameExtra, public llvm::FoldingSetNode {
272 MultiKeywordSelector(unsigned nKeys) {
273 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
276 // Constructor for keyword selectors.
277 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
278 assert((nKeys > 1) && "not a multi-keyword selector");
279 ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
281 // Fill in the trailing keyword array.
282 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
283 for (unsigned i = 0; i != nKeys; ++i)
287 // getName - Derive the full selector name and return it.
288 std::string getName() const;
290 unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
292 typedef IdentifierInfo *const *keyword_iterator;
293 keyword_iterator keyword_begin() const {
294 return reinterpret_cast<keyword_iterator>(this+1);
296 keyword_iterator keyword_end() const {
297 return keyword_begin()+getNumArgs();
299 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
300 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
301 return keyword_begin()[i];
303 static void Profile(llvm::FoldingSetNodeID &ID,
304 keyword_iterator ArgTys, unsigned NumArgs) {
305 ID.AddInteger(NumArgs);
306 for (unsigned i = 0; i != NumArgs; ++i)
307 ID.AddPointer(ArgTys[i]);
309 void Profile(llvm::FoldingSetNodeID &ID) {
310 Profile(ID, keyword_begin(), getNumArgs());
313 } // end namespace clang.
315 unsigned Selector::getNumArgs() const {
316 unsigned IIF = getIdentifierInfoFlag();
321 // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
322 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
323 return SI->getNumArgs();
326 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
327 if (getIdentifierInfoFlag()) {
328 assert(argIndex == 0 && "illegal keyword index");
329 return getAsIdentifierInfo();
331 // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
332 MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
333 return SI->getIdentifierInfoForSlot(argIndex);
336 llvm::StringRef Selector::getNameForSlot(unsigned int argIndex) const {
337 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
338 return II? II->getName() : llvm::StringRef();
341 std::string MultiKeywordSelector::getName() const {
342 llvm::SmallString<256> Str;
343 llvm::raw_svector_ostream OS(Str);
344 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
346 OS << (*I)->getName();
353 std::string Selector::getAsString() const {
355 return "<null selector>";
357 if (InfoPtr & ArgFlags) {
358 IdentifierInfo *II = getAsIdentifierInfo();
360 // If the number of arguments is 0 then II is guaranteed to not be null.
361 if (getNumArgs() == 0)
362 return II->getName();
367 return II->getName().str() + ":";
370 // We have a multiple keyword selector (no embedded flags).
371 return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName();
374 /// Interpreting the given string using the normal CamelCase
375 /// conventions, determine whether the given string starts with the
376 /// given "word", which is assumed to end in a lowercase letter.
377 static bool startsWithWord(llvm::StringRef name, llvm::StringRef word) {
378 if (name.size() < word.size()) return false;
379 return ((name.size() == word.size() ||
380 !islower(name[word.size()]))
381 && name.startswith(word));
384 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
385 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
386 if (!first) return OMF_None;
388 llvm::StringRef name = first->getName();
389 if (sel.isUnarySelector()) {
390 if (name == "autorelease") return OMF_autorelease;
391 if (name == "dealloc") return OMF_dealloc;
392 if (name == "release") return OMF_release;
393 if (name == "retain") return OMF_retain;
394 if (name == "retainCount") return OMF_retainCount;
395 if (name == "self") return OMF_self;
398 // The other method families may begin with a prefix of underscores.
399 while (!name.empty() && name.front() == '_')
400 name = name.substr(1);
402 if (name.empty()) return OMF_None;
403 switch (name.front()) {
405 if (startsWithWord(name, "alloc")) return OMF_alloc;
408 if (startsWithWord(name, "copy")) return OMF_copy;
411 if (startsWithWord(name, "init")) return OMF_init;
414 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
417 if (startsWithWord(name, "new")) return OMF_new;
427 struct SelectorTableImpl {
428 llvm::FoldingSet<MultiKeywordSelector> Table;
429 llvm::BumpPtrAllocator Allocator;
431 } // end anonymous namespace.
433 static SelectorTableImpl &getSelectorTableImpl(void *P) {
434 return *static_cast<SelectorTableImpl*>(P);
437 size_t SelectorTable::getTotalMemory() const {
438 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
439 return SelTabImpl.Allocator.getTotalMemory();
442 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
444 return Selector(IIV[0], nKeys);
446 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
448 // Unique selector, to guarantee there is one per name.
449 llvm::FoldingSetNodeID ID;
450 MultiKeywordSelector::Profile(ID, IIV, nKeys);
453 if (MultiKeywordSelector *SI =
454 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
457 // MultiKeywordSelector objects are not allocated with new because they have a
458 // variable size array (for parameter types) at the end of them.
459 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
460 MultiKeywordSelector *SI =
461 (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
462 llvm::alignOf<MultiKeywordSelector>());
463 new (SI) MultiKeywordSelector(nKeys, IIV);
464 SelTabImpl.Table.InsertNode(SI, InsertPos);
468 SelectorTable::SelectorTable() {
469 Impl = new SelectorTableImpl();
472 SelectorTable::~SelectorTable() {
473 delete &getSelectorTableImpl(Impl);
476 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
479 case NUM_OVERLOADED_OPERATORS:
482 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
483 case OO_##Name: return Spelling;
484 #include "clang/Basic/OperatorKinds.def"