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