IdentifierTable.cpp revision 9670e179a67d868e171feac44fb8f9e2f108c5e8
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/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/ADT/StringSwitch.h"
21#include "llvm/Support/raw_ostream.h"
22#include <cstdio>
23
24using namespace clang;
25
26//===----------------------------------------------------------------------===//
27// IdentifierInfo Implementation
28//===----------------------------------------------------------------------===//
29
30IdentifierInfo::IdentifierInfo() {
31  TokenID = tok::identifier;
32  ObjCOrBuiltinID = 0;
33  HasMacro = false;
34  IsExtension = false;
35  IsPoisoned = false;
36  IsCPPOperatorKeyword = false;
37  NeedsHandleIdentifier = false;
38  IsFromAST = false;
39  RevertedTokenID = false;
40  FETokenInfo = 0;
41  Entry = 0;
42}
43
44//===----------------------------------------------------------------------===//
45// IdentifierTable Implementation
46//===----------------------------------------------------------------------===//
47
48IdentifierIterator::~IdentifierIterator() { }
49
50IdentifierInfoLookup::~IdentifierInfoLookup() {}
51
52namespace {
53  /// \brief A simple identifier lookup iterator that represents an
54  /// empty sequence of identifiers.
55  class EmptyLookupIterator : public IdentifierIterator
56  {
57  public:
58    virtual llvm::StringRef Next() { return llvm::StringRef(); }
59  };
60}
61
62IdentifierIterator *IdentifierInfoLookup::getIdentifiers() const {
63  return new EmptyLookupIterator();
64}
65
66ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
67
68IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
69                                 IdentifierInfoLookup* externalLookup)
70  : HashTable(8192), // Start with space for 8K identifiers.
71    ExternalLookup(externalLookup) {
72
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
83namespace {
84  enum {
85    KEYC99 = 0x1,
86    KEYCXX = 0x2,
87    KEYCXX0X = 0x4,
88    KEYGNU = 0x8,
89    KEYMS = 0x10,
90    BOOLSUPPORT = 0x20,
91    KEYALTIVEC = 0x40,
92    KEYNOCXX = 0x80,
93    KEYBORLAND = 0x100,
94    KEYOPENCL = 0x200,
95    KEYC1X = 0x400,
96    KEYARC = 0x800,
97    KEYALL = 0x0fff
98  };
99}
100
101/// AddKeyword - This method is used to associate a token ID with specific
102/// identifiers because they are language keywords.  This causes the lexer to
103/// automatically map matching identifiers to specialized token codes.
104///
105/// The C90/C99/CPP/CPP0x flags are set to 2 if the token should be
106/// enabled in the specified langauge, set to 1 if it is an extension
107/// in the specified language, and set to 0 if disabled in the
108/// specified language.
109static void AddKeyword(llvm::StringRef Keyword,
110                       tok::TokenKind TokenCode, unsigned Flags,
111                       const LangOptions &LangOpts, IdentifierTable &Table) {
112  unsigned AddResult = 0;
113  if (Flags == KEYALL) AddResult = 2;
114  else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
115  else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2;
116  else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
117  else if (LangOpts.GNUKeywords && (Flags & KEYGNU)) AddResult = 1;
118  else if (LangOpts.Microsoft && (Flags & KEYMS)) AddResult = 1;
119  else if (LangOpts.Borland && (Flags & KEYBORLAND)) AddResult = 1;
120  else if (LangOpts.Bool && (Flags & BOOLSUPPORT)) AddResult = 2;
121  else if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) AddResult = 2;
122  else if (LangOpts.OpenCL && (Flags & KEYOPENCL)) AddResult = 2;
123  else if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) AddResult = 2;
124  else if (LangOpts.C1X && (Flags & KEYC1X)) AddResult = 2;
125  else if (LangOpts.ObjCAutoRefCount && (Flags & KEYARC)) AddResult = 2;
126
127  // Don't add this keyword if disabled in this language.
128  if (AddResult == 0) return;
129
130  IdentifierInfo &Info = Table.get(Keyword, TokenCode);
131  Info.setIsExtensionToken(AddResult == 1);
132}
133
134/// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
135/// representations.
136static void AddCXXOperatorKeyword(llvm::StringRef Keyword,
137                                  tok::TokenKind TokenCode,
138                                  IdentifierTable &Table) {
139  IdentifierInfo &Info = Table.get(Keyword, TokenCode);
140  Info.setIsCPlusPlusOperatorKeyword();
141}
142
143/// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
144/// "property".
145static void AddObjCKeyword(llvm::StringRef Name,
146                           tok::ObjCKeywordKind ObjCID,
147                           IdentifierTable &Table) {
148  Table.get(Name).setObjCKeywordID(ObjCID);
149}
150
151/// AddKeywords - Add all keywords to the symbol table.
152///
153void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
154  // Add keywords and tokens for the current language.
155#define KEYWORD(NAME, FLAGS) \
156  AddKeyword(llvm::StringRef(#NAME), tok::kw_ ## NAME,  \
157             FLAGS, LangOpts, *this);
158#define ALIAS(NAME, TOK, FLAGS) \
159  AddKeyword(llvm::StringRef(NAME), tok::kw_ ## TOK,  \
160             FLAGS, LangOpts, *this);
161#define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
162  if (LangOpts.CXXOperatorNames)          \
163    AddCXXOperatorKeyword(llvm::StringRef(#NAME), tok::ALIAS, *this);
164#define OBJC1_AT_KEYWORD(NAME) \
165  if (LangOpts.ObjC1)          \
166    AddObjCKeyword(llvm::StringRef(#NAME), tok::objc_##NAME, *this);
167#define OBJC2_AT_KEYWORD(NAME) \
168  if (LangOpts.ObjC2)          \
169    AddObjCKeyword(llvm::StringRef(#NAME), tok::objc_##NAME, *this);
170#define TESTING_KEYWORD(NAME, FLAGS)
171#include "clang/Basic/TokenKinds.def"
172
173  if (LangOpts.ParseUnknownAnytype)
174    AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
175               LangOpts, *this);
176}
177
178tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
179  // We use a perfect hash function here involving the length of the keyword,
180  // the first and third character.  For preprocessor ID's there are no
181  // collisions (if there were, the switch below would complain about duplicate
182  // case values).  Note that this depends on 'if' being null terminated.
183
184#define HASH(LEN, FIRST, THIRD) \
185  (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
186#define CASE(LEN, FIRST, THIRD, NAME) \
187  case HASH(LEN, FIRST, THIRD): \
188    return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
189
190  unsigned Len = getLength();
191  if (Len < 2) return tok::pp_not_keyword;
192  const char *Name = getNameStart();
193  switch (HASH(Len, Name[0], Name[2])) {
194  default: return tok::pp_not_keyword;
195  CASE( 2, 'i', '\0', if);
196  CASE( 4, 'e', 'i', elif);
197  CASE( 4, 'e', 's', else);
198  CASE( 4, 'l', 'n', line);
199  CASE( 4, 's', 'c', sccs);
200  CASE( 5, 'e', 'd', endif);
201  CASE( 5, 'e', 'r', error);
202  CASE( 5, 'i', 'e', ident);
203  CASE( 5, 'i', 'd', ifdef);
204  CASE( 5, 'u', 'd', undef);
205
206  CASE( 6, 'a', 's', assert);
207  CASE( 6, 'd', 'f', define);
208  CASE( 6, 'i', 'n', ifndef);
209  CASE( 6, 'i', 'p', import);
210  CASE( 6, 'p', 'a', pragma);
211
212  CASE( 7, 'd', 'f', defined);
213  CASE( 7, 'i', 'c', include);
214  CASE( 7, 'w', 'r', warning);
215
216  CASE( 8, 'u', 'a', unassert);
217  CASE(12, 'i', 'c', include_next);
218
219  CASE(16, '_', 'i', __include_macros);
220#undef CASE
221#undef HASH
222  }
223}
224
225//===----------------------------------------------------------------------===//
226// Stats Implementation
227//===----------------------------------------------------------------------===//
228
229/// PrintStats - Print statistics about how well the identifier table is doing
230/// at hashing identifiers.
231void IdentifierTable::PrintStats() const {
232  unsigned NumBuckets = HashTable.getNumBuckets();
233  unsigned NumIdentifiers = HashTable.getNumItems();
234  unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
235  unsigned AverageIdentifierSize = 0;
236  unsigned MaxIdentifierLength = 0;
237
238  // TODO: Figure out maximum times an identifier had to probe for -stats.
239  for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
240       I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
241    unsigned IdLen = I->getKeyLength();
242    AverageIdentifierSize += IdLen;
243    if (MaxIdentifierLength < IdLen)
244      MaxIdentifierLength = IdLen;
245  }
246
247  fprintf(stderr, "\n*** Identifier Table Stats:\n");
248  fprintf(stderr, "# Identifiers:   %d\n", NumIdentifiers);
249  fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
250  fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
251          NumIdentifiers/(double)NumBuckets);
252  fprintf(stderr, "Ave identifier length: %f\n",
253          (AverageIdentifierSize/(double)NumIdentifiers));
254  fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
255
256  // Compute statistics about the memory allocated for identifiers.
257  HashTable.getAllocator().PrintStats();
258}
259
260//===----------------------------------------------------------------------===//
261// SelectorTable Implementation
262//===----------------------------------------------------------------------===//
263
264unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
265  return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
266}
267
268namespace clang {
269/// MultiKeywordSelector - One of these variable length records is kept for each
270/// selector containing more than one keyword. We use a folding set
271/// to unique aggregate names (keyword selectors in ObjC parlance). Access to
272/// this class is provided strictly through Selector.
273class MultiKeywordSelector
274  : public DeclarationNameExtra, public llvm::FoldingSetNode {
275  MultiKeywordSelector(unsigned nKeys) {
276    ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
277  }
278public:
279  // Constructor for keyword selectors.
280  MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
281    assert((nKeys > 1) && "not a multi-keyword selector");
282    ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
283
284    // Fill in the trailing keyword array.
285    IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
286    for (unsigned i = 0; i != nKeys; ++i)
287      KeyInfo[i] = IIV[i];
288  }
289
290  // getName - Derive the full selector name and return it.
291  std::string getName() const;
292
293  unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
294
295  typedef IdentifierInfo *const *keyword_iterator;
296  keyword_iterator keyword_begin() const {
297    return reinterpret_cast<keyword_iterator>(this+1);
298  }
299  keyword_iterator keyword_end() const {
300    return keyword_begin()+getNumArgs();
301  }
302  IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
303    assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
304    return keyword_begin()[i];
305  }
306  static void Profile(llvm::FoldingSetNodeID &ID,
307                      keyword_iterator ArgTys, unsigned NumArgs) {
308    ID.AddInteger(NumArgs);
309    for (unsigned i = 0; i != NumArgs; ++i)
310      ID.AddPointer(ArgTys[i]);
311  }
312  void Profile(llvm::FoldingSetNodeID &ID) {
313    Profile(ID, keyword_begin(), getNumArgs());
314  }
315};
316} // end namespace clang.
317
318unsigned Selector::getNumArgs() const {
319  unsigned IIF = getIdentifierInfoFlag();
320  if (IIF == ZeroArg)
321    return 0;
322  if (IIF == OneArg)
323    return 1;
324  // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
325  MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
326  return SI->getNumArgs();
327}
328
329IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
330  if (getIdentifierInfoFlag()) {
331    assert(argIndex == 0 && "illegal keyword index");
332    return getAsIdentifierInfo();
333  }
334  // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
335  MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
336  return SI->getIdentifierInfoForSlot(argIndex);
337}
338
339llvm::StringRef Selector::getNameForSlot(unsigned int argIndex) const {
340  IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
341  return II? II->getName() : llvm::StringRef();
342}
343
344std::string MultiKeywordSelector::getName() const {
345  llvm::SmallString<256> Str;
346  llvm::raw_svector_ostream OS(Str);
347  for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
348    if (*I)
349      OS << (*I)->getName();
350    OS << ':';
351  }
352
353  return OS.str();
354}
355
356std::string Selector::getAsString() const {
357  if (InfoPtr == 0)
358    return "<null selector>";
359
360  if (InfoPtr & ArgFlags) {
361    IdentifierInfo *II = getAsIdentifierInfo();
362
363    // If the number of arguments is 0 then II is guaranteed to not be null.
364    if (getNumArgs() == 0)
365      return II->getName();
366
367    if (!II)
368      return ":";
369
370    return II->getName().str() + ":";
371  }
372
373  // We have a multiple keyword selector (no embedded flags).
374  return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName();
375}
376
377/// Interpreting the given string using the normal CamelCase
378/// conventions, determine whether the given string starts with the
379/// given "word", which is assumed to end in a lowercase letter.
380static bool startsWithWord(llvm::StringRef name, llvm::StringRef word) {
381  if (name.size() < word.size()) return false;
382  return ((name.size() == word.size() ||
383           !islower(name[word.size()]))
384          && name.startswith(word));
385}
386
387ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
388  IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
389  if (!first) return OMF_None;
390
391  llvm::StringRef name = first->getName();
392  if (sel.isUnarySelector()) {
393    if (name == "autorelease") return OMF_autorelease;
394    if (name == "dealloc") return OMF_dealloc;
395    if (name == "release") return OMF_release;
396    if (name == "retain") return OMF_retain;
397    if (name == "retainCount") return OMF_retainCount;
398    if (name == "self") return OMF_self;
399  }
400
401  if (name == "performSelector") return OMF_performSelector;
402
403  // The other method families may begin with a prefix of underscores.
404  while (!name.empty() && name.front() == '_')
405    name = name.substr(1);
406
407  if (name.empty()) return OMF_None;
408  switch (name.front()) {
409  case 'a':
410    if (startsWithWord(name, "alloc")) return OMF_alloc;
411    break;
412  case 'c':
413    if (startsWithWord(name, "copy")) return OMF_copy;
414    break;
415  case 'i':
416    if (startsWithWord(name, "init")) return OMF_init;
417    break;
418  case 'm':
419    if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
420    break;
421  case 'n':
422    if (startsWithWord(name, "new")) return OMF_new;
423    break;
424  default:
425    break;
426  }
427
428  return OMF_None;
429}
430
431namespace {
432  struct SelectorTableImpl {
433    llvm::FoldingSet<MultiKeywordSelector> Table;
434    llvm::BumpPtrAllocator Allocator;
435  };
436} // end anonymous namespace.
437
438static SelectorTableImpl &getSelectorTableImpl(void *P) {
439  return *static_cast<SelectorTableImpl*>(P);
440}
441
442size_t SelectorTable::getTotalMemory() const {
443  SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
444  return SelTabImpl.Allocator.getTotalMemory();
445}
446
447Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
448  if (nKeys < 2)
449    return Selector(IIV[0], nKeys);
450
451  SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
452
453  // Unique selector, to guarantee there is one per name.
454  llvm::FoldingSetNodeID ID;
455  MultiKeywordSelector::Profile(ID, IIV, nKeys);
456
457  void *InsertPos = 0;
458  if (MultiKeywordSelector *SI =
459        SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
460    return Selector(SI);
461
462  // MultiKeywordSelector objects are not allocated with new because they have a
463  // variable size array (for parameter types) at the end of them.
464  unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
465  MultiKeywordSelector *SI =
466    (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
467                                         llvm::alignOf<MultiKeywordSelector>());
468  new (SI) MultiKeywordSelector(nKeys, IIV);
469  SelTabImpl.Table.InsertNode(SI, InsertPos);
470  return Selector(SI);
471}
472
473SelectorTable::SelectorTable() {
474  Impl = new SelectorTableImpl();
475}
476
477SelectorTable::~SelectorTable() {
478  delete &getSelectorTableImpl(Impl);
479}
480
481const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
482  switch (Operator) {
483  case OO_None:
484  case NUM_OVERLOADED_OPERATORS:
485    return 0;
486
487#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
488  case OO_##Name: return Spelling;
489#include "clang/Basic/OperatorKinds.def"
490  }
491
492  return 0;
493}
494
495