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