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