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