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