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