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