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 <cstdio>
20 
21 using namespace clang;
22 
23 //===----------------------------------------------------------------------===//
24 // IdentifierInfo Implementation
25 //===----------------------------------------------------------------------===//
26 
27 IdentifierInfo::IdentifierInfo() {
28   TokenID = tok::identifier;
29   ObjCOrBuiltinID = 0;
30   HasMacro = false;
31   IsExtension = false;
32   IsPoisoned = false;
33   IsCPPOperatorKeyword = false;
34   NeedsHandleIdentifier = false;
35   FETokenInfo = 0;
36   Entry = 0;
37 }
38 
39 //===----------------------------------------------------------------------===//
40 // IdentifierTable Implementation
41 //===----------------------------------------------------------------------===//
42 
43 IdentifierInfoLookup::~IdentifierInfoLookup() {}
44 
45 ExternalIdentifierLookup::~ExternalIdentifierLookup() {}
46 
47 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
48                                  IdentifierInfoLookup* externalLookup)
49   : HashTable(8192), // Start with space for 8K identifiers.
50     ExternalLookup(externalLookup) {
51 
52   // Populate the identifier table with info about keywords for the current
53   // language.
54   AddKeywords(LangOpts);
55 }
56 
57 //===----------------------------------------------------------------------===//
58 // Language Keyword Implementation
59 //===----------------------------------------------------------------------===//
60 
61 // Constants for TokenKinds.def
62 namespace {
63   enum {
64     KEYALL = 1,
65     KEYC99 = 2,
66     KEYCXX = 4,
67     KEYCXX0X = 8,
68     KEYGNU = 16,
69     KEYMS = 32
70   };
71 }
72 
73 /// AddKeyword - This method is used to associate a token ID with specific
74 /// identifiers because they are language keywords.  This causes the lexer to
75 /// automatically map matching identifiers to specialized token codes.
76 ///
77 /// The C90/C99/CPP/CPP0x flags are set to 0 if the token should be
78 /// enabled in the specified langauge, set to 1 if it is an extension
79 /// in the specified language, and set to 2 if disabled in the
80 /// specified language.
81 static void AddKeyword(const char *Keyword, unsigned KWLen,
82                        tok::TokenKind TokenCode, unsigned Flags,
83                        const LangOptions &LangOpts, IdentifierTable &Table) {
84   unsigned AddResult = 0;
85   if (Flags & KEYALL) AddResult = 2;
86   else if (LangOpts.CPlusPlus && (Flags & KEYCXX)) AddResult = 2;
87   else if (LangOpts.CPlusPlus0x && (Flags & KEYCXX0X)) AddResult = 2;
88   else if (LangOpts.C99 && (Flags & KEYC99)) AddResult = 2;
89   else if (LangOpts.GNUMode && (Flags & KEYGNU)) AddResult = 1;
90   else if (LangOpts.Microsoft && (Flags & KEYMS)) AddResult = 1;
91 
92   // Don't add this keyword if disabled in this language.
93   if (AddResult == 0) return;
94 
95   IdentifierInfo &Info = Table.get(Keyword, Keyword+KWLen);
96   Info.setTokenID(TokenCode);
97   Info.setIsExtensionToken(AddResult == 1);
98 }
99 
100 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
101 /// representations.
102 static void AddCXXOperatorKeyword(const char *Keyword, unsigned KWLen,
103                                   tok::TokenKind TokenCode,
104                                   IdentifierTable &Table) {
105   IdentifierInfo &Info = Table.get(Keyword, Keyword + KWLen);
106   Info.setTokenID(TokenCode);
107   Info.setIsCPlusPlusOperatorKeyword();
108 }
109 
110 /// AddObjCKeyword - Register an Objective-C @keyword like "class" "selector" or
111 /// "property".
112 static void AddObjCKeyword(tok::ObjCKeywordKind ObjCID,
113                            const char *Name, unsigned NameLen,
114                            IdentifierTable &Table) {
115   Table.get(Name, Name+NameLen).setObjCKeywordID(ObjCID);
116 }
117 
118 /// AddKeywords - Add all keywords to the symbol table.
119 ///
120 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
121   // Add keywords and tokens for the current language.
122 #define KEYWORD(NAME, FLAGS) \
123   AddKeyword(#NAME, strlen(#NAME), tok::kw_ ## NAME,  \
124              FLAGS, LangOpts, *this);
125 #define ALIAS(NAME, TOK, FLAGS) \
126   AddKeyword(NAME, strlen(NAME), tok::kw_ ## TOK,  \
127              FLAGS, LangOpts, *this);
128 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
129   if (LangOpts.CXXOperatorNames)          \
130     AddCXXOperatorKeyword(#NAME, strlen(#NAME), tok::ALIAS, *this);
131 #define OBJC1_AT_KEYWORD(NAME) \
132   if (LangOpts.ObjC1)          \
133     AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
134 #define OBJC2_AT_KEYWORD(NAME) \
135   if (LangOpts.ObjC2)          \
136     AddObjCKeyword(tok::objc_##NAME, #NAME, strlen(#NAME), *this);
137 #include "clang/Basic/TokenKinds.def"
138 }
139 
140 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
141   // We use a perfect hash function here involving the length of the keyword,
142   // the first and third character.  For preprocessor ID's there are no
143   // collisions (if there were, the switch below would complain about duplicate
144   // case values).  Note that this depends on 'if' being null terminated.
145 
146 #define HASH(LEN, FIRST, THIRD) \
147   (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
148 #define CASE(LEN, FIRST, THIRD, NAME) \
149   case HASH(LEN, FIRST, THIRD): \
150     return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
151 
152   unsigned Len = getLength();
153   if (Len < 2) return tok::pp_not_keyword;
154   const char *Name = getName();
155   switch (HASH(Len, Name[0], Name[2])) {
156   default: return tok::pp_not_keyword;
157   CASE( 2, 'i', '\0', if);
158   CASE( 4, 'e', 'i', elif);
159   CASE( 4, 'e', 's', else);
160   CASE( 4, 'l', 'n', line);
161   CASE( 4, 's', 'c', sccs);
162   CASE( 5, 'e', 'd', endif);
163   CASE( 5, 'e', 'r', error);
164   CASE( 5, 'i', 'e', ident);
165   CASE( 5, 'i', 'd', ifdef);
166   CASE( 5, 'u', 'd', undef);
167 
168   CASE( 6, 'a', 's', assert);
169   CASE( 6, 'd', 'f', define);
170   CASE( 6, 'i', 'n', ifndef);
171   CASE( 6, 'i', 'p', import);
172   CASE( 6, 'p', 'a', pragma);
173 
174   CASE( 7, 'd', 'f', defined);
175   CASE( 7, 'i', 'c', include);
176   CASE( 7, 'w', 'r', warning);
177 
178   CASE( 8, 'u', 'a', unassert);
179   CASE(12, 'i', 'c', include_next);
180 
181   CASE(16, '_', 'i', __include_macros);
182 #undef CASE
183 #undef HASH
184   }
185 }
186 
187 //===----------------------------------------------------------------------===//
188 // Stats Implementation
189 //===----------------------------------------------------------------------===//
190 
191 /// PrintStats - Print statistics about how well the identifier table is doing
192 /// at hashing identifiers.
193 void IdentifierTable::PrintStats() const {
194   unsigned NumBuckets = HashTable.getNumBuckets();
195   unsigned NumIdentifiers = HashTable.getNumItems();
196   unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
197   unsigned AverageIdentifierSize = 0;
198   unsigned MaxIdentifierLength = 0;
199 
200   // TODO: Figure out maximum times an identifier had to probe for -stats.
201   for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
202        I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
203     unsigned IdLen = I->getKeyLength();
204     AverageIdentifierSize += IdLen;
205     if (MaxIdentifierLength < IdLen)
206       MaxIdentifierLength = IdLen;
207   }
208 
209   fprintf(stderr, "\n*** Identifier Table Stats:\n");
210   fprintf(stderr, "# Identifiers:   %d\n", NumIdentifiers);
211   fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
212   fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
213           NumIdentifiers/(double)NumBuckets);
214   fprintf(stderr, "Ave identifier length: %f\n",
215           (AverageIdentifierSize/(double)NumIdentifiers));
216   fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
217 
218   // Compute statistics about the memory allocated for identifiers.
219   HashTable.getAllocator().PrintStats();
220 }
221 
222 //===----------------------------------------------------------------------===//
223 // SelectorTable Implementation
224 //===----------------------------------------------------------------------===//
225 
226 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
227   return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
228 }
229 
230 namespace clang {
231 /// MultiKeywordSelector - One of these variable length records is kept for each
232 /// selector containing more than one keyword. We use a folding set
233 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
234 /// this class is provided strictly through Selector.
235 class MultiKeywordSelector
236   : public DeclarationNameExtra, public llvm::FoldingSetNode {
237   MultiKeywordSelector(unsigned nKeys) {
238     ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
239   }
240 public:
241   // Constructor for keyword selectors.
242   MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
243     assert((nKeys > 1) && "not a multi-keyword selector");
244     ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
245 
246     // Fill in the trailing keyword array.
247     IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
248     for (unsigned i = 0; i != nKeys; ++i)
249       KeyInfo[i] = IIV[i];
250   }
251 
252   // getName - Derive the full selector name and return it.
253   std::string getName() const;
254 
255   unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
256 
257   typedef IdentifierInfo *const *keyword_iterator;
258   keyword_iterator keyword_begin() const {
259     return reinterpret_cast<keyword_iterator>(this+1);
260   }
261   keyword_iterator keyword_end() const {
262     return keyword_begin()+getNumArgs();
263   }
264   IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
265     assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
266     return keyword_begin()[i];
267   }
268   static void Profile(llvm::FoldingSetNodeID &ID,
269                       keyword_iterator ArgTys, unsigned NumArgs) {
270     ID.AddInteger(NumArgs);
271     for (unsigned i = 0; i != NumArgs; ++i)
272       ID.AddPointer(ArgTys[i]);
273   }
274   void Profile(llvm::FoldingSetNodeID &ID) {
275     Profile(ID, keyword_begin(), getNumArgs());
276   }
277 };
278 } // end namespace clang.
279 
280 unsigned Selector::getNumArgs() const {
281   unsigned IIF = getIdentifierInfoFlag();
282   if (IIF == ZeroArg)
283     return 0;
284   if (IIF == OneArg)
285     return 1;
286   // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
287   MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
288   return SI->getNumArgs();
289 }
290 
291 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
292   if (getIdentifierInfoFlag()) {
293     assert(argIndex == 0 && "illegal keyword index");
294     return getAsIdentifierInfo();
295   }
296   // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
297   MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
298   return SI->getIdentifierInfoForSlot(argIndex);
299 }
300 
301 std::string MultiKeywordSelector::getName() const {
302   std::string Result;
303   unsigned Length = 0;
304   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
305     if (*I)
306       Length += (*I)->getLength();
307     ++Length;  // :
308   }
309 
310   Result.reserve(Length);
311 
312   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
313     if (*I)
314       Result.insert(Result.end(), (*I)->getName(),
315                     (*I)->getName()+(*I)->getLength());
316     Result.push_back(':');
317   }
318 
319   return Result;
320 }
321 
322 std::string Selector::getAsString() const {
323   if (InfoPtr == 0)
324     return "<null selector>";
325 
326   if (InfoPtr & ArgFlags) {
327     IdentifierInfo *II = getAsIdentifierInfo();
328 
329     // If the number of arguments is 0 then II is guaranteed to not be null.
330     if (getNumArgs() == 0)
331       return II->getName();
332 
333     std::string Res = II ? II->getName() : "";
334     Res += ":";
335     return Res;
336   }
337 
338   // We have a multiple keyword selector (no embedded flags).
339   return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName();
340 }
341 
342 
343 namespace {
344   struct SelectorTableImpl {
345     llvm::FoldingSet<MultiKeywordSelector> Table;
346     llvm::BumpPtrAllocator Allocator;
347   };
348 } // end anonymous namespace.
349 
350 static SelectorTableImpl &getSelectorTableImpl(void *P) {
351   return *static_cast<SelectorTableImpl*>(P);
352 }
353 
354 
355 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
356   if (nKeys < 2)
357     return Selector(IIV[0], nKeys);
358 
359   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
360 
361   // Unique selector, to guarantee there is one per name.
362   llvm::FoldingSetNodeID ID;
363   MultiKeywordSelector::Profile(ID, IIV, nKeys);
364 
365   void *InsertPos = 0;
366   if (MultiKeywordSelector *SI =
367         SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
368     return Selector(SI);
369 
370   // MultiKeywordSelector objects are not allocated with new because they have a
371   // variable size array (for parameter types) at the end of them.
372   unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
373   MultiKeywordSelector *SI =
374     (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
375                                          llvm::alignof<MultiKeywordSelector>());
376   new (SI) MultiKeywordSelector(nKeys, IIV);
377   SelTabImpl.Table.InsertNode(SI, InsertPos);
378   return Selector(SI);
379 }
380 
381 SelectorTable::SelectorTable() {
382   Impl = new SelectorTableImpl();
383 }
384 
385 SelectorTable::~SelectorTable() {
386   delete &getSelectorTableImpl(Impl);
387 }
388 
389