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