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