Home | History | Annotate | Download | only in Basic
      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 
    226   CASE(17, '_', 'p', __private_macro__);
    227 #undef CASE
    228 #undef HASH
    229   }
    230 }
    231 
    232 //===----------------------------------------------------------------------===//
    233 // Stats Implementation
    234 //===----------------------------------------------------------------------===//
    235 
    236 /// PrintStats - Print statistics about how well the identifier table is doing
    237 /// at hashing identifiers.
    238 void IdentifierTable::PrintStats() const {
    239   unsigned NumBuckets = HashTable.getNumBuckets();
    240   unsigned NumIdentifiers = HashTable.getNumItems();
    241   unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
    242   unsigned AverageIdentifierSize = 0;
    243   unsigned MaxIdentifierLength = 0;
    244 
    245   // TODO: Figure out maximum times an identifier had to probe for -stats.
    246   for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
    247        I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
    248     unsigned IdLen = I->getKeyLength();
    249     AverageIdentifierSize += IdLen;
    250     if (MaxIdentifierLength < IdLen)
    251       MaxIdentifierLength = IdLen;
    252   }
    253 
    254   fprintf(stderr, "\n*** Identifier Table Stats:\n");
    255   fprintf(stderr, "# Identifiers:   %d\n", NumIdentifiers);
    256   fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
    257   fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
    258           NumIdentifiers/(double)NumBuckets);
    259   fprintf(stderr, "Ave identifier length: %f\n",
    260           (AverageIdentifierSize/(double)NumIdentifiers));
    261   fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
    262 
    263   // Compute statistics about the memory allocated for identifiers.
    264   HashTable.getAllocator().PrintStats();
    265 }
    266 
    267 //===----------------------------------------------------------------------===//
    268 // SelectorTable Implementation
    269 //===----------------------------------------------------------------------===//
    270 
    271 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
    272   return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
    273 }
    274 
    275 namespace clang {
    276 /// MultiKeywordSelector - One of these variable length records is kept for each
    277 /// selector containing more than one keyword. We use a folding set
    278 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
    279 /// this class is provided strictly through Selector.
    280 class MultiKeywordSelector
    281   : public DeclarationNameExtra, public llvm::FoldingSetNode {
    282   MultiKeywordSelector(unsigned nKeys) {
    283     ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
    284   }
    285 public:
    286   // Constructor for keyword selectors.
    287   MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV) {
    288     assert((nKeys > 1) && "not a multi-keyword selector");
    289     ExtraKindOrNumArgs = NUM_EXTRA_KINDS + nKeys;
    290 
    291     // Fill in the trailing keyword array.
    292     IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this+1);
    293     for (unsigned i = 0; i != nKeys; ++i)
    294       KeyInfo[i] = IIV[i];
    295   }
    296 
    297   // getName - Derive the full selector name and return it.
    298   std::string getName() const;
    299 
    300   unsigned getNumArgs() const { return ExtraKindOrNumArgs - NUM_EXTRA_KINDS; }
    301 
    302   typedef IdentifierInfo *const *keyword_iterator;
    303   keyword_iterator keyword_begin() const {
    304     return reinterpret_cast<keyword_iterator>(this+1);
    305   }
    306   keyword_iterator keyword_end() const {
    307     return keyword_begin()+getNumArgs();
    308   }
    309   IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
    310     assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
    311     return keyword_begin()[i];
    312   }
    313   static void Profile(llvm::FoldingSetNodeID &ID,
    314                       keyword_iterator ArgTys, unsigned NumArgs) {
    315     ID.AddInteger(NumArgs);
    316     for (unsigned i = 0; i != NumArgs; ++i)
    317       ID.AddPointer(ArgTys[i]);
    318   }
    319   void Profile(llvm::FoldingSetNodeID &ID) {
    320     Profile(ID, keyword_begin(), getNumArgs());
    321   }
    322 };
    323 } // end namespace clang.
    324 
    325 unsigned Selector::getNumArgs() const {
    326   unsigned IIF = getIdentifierInfoFlag();
    327   if (IIF == ZeroArg)
    328     return 0;
    329   if (IIF == OneArg)
    330     return 1;
    331   // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
    332   MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
    333   return SI->getNumArgs();
    334 }
    335 
    336 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
    337   if (getIdentifierInfoFlag()) {
    338     assert(argIndex == 0 && "illegal keyword index");
    339     return getAsIdentifierInfo();
    340   }
    341   // We point to a MultiKeywordSelector (pointer doesn't contain any flags).
    342   MultiKeywordSelector *SI = reinterpret_cast<MultiKeywordSelector *>(InfoPtr);
    343   return SI->getIdentifierInfoForSlot(argIndex);
    344 }
    345 
    346 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
    347   IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
    348   return II? II->getName() : StringRef();
    349 }
    350 
    351 std::string MultiKeywordSelector::getName() const {
    352   llvm::SmallString<256> Str;
    353   llvm::raw_svector_ostream OS(Str);
    354   for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
    355     if (*I)
    356       OS << (*I)->getName();
    357     OS << ':';
    358   }
    359 
    360   return OS.str();
    361 }
    362 
    363 std::string Selector::getAsString() const {
    364   if (InfoPtr == 0)
    365     return "<null selector>";
    366 
    367   if (InfoPtr & ArgFlags) {
    368     IdentifierInfo *II = getAsIdentifierInfo();
    369 
    370     // If the number of arguments is 0 then II is guaranteed to not be null.
    371     if (getNumArgs() == 0)
    372       return II->getName();
    373 
    374     if (!II)
    375       return ":";
    376 
    377     return II->getName().str() + ":";
    378   }
    379 
    380   // We have a multiple keyword selector (no embedded flags).
    381   return reinterpret_cast<MultiKeywordSelector *>(InfoPtr)->getName();
    382 }
    383 
    384 /// Interpreting the given string using the normal CamelCase
    385 /// conventions, determine whether the given string starts with the
    386 /// given "word", which is assumed to end in a lowercase letter.
    387 static bool startsWithWord(StringRef name, StringRef word) {
    388   if (name.size() < word.size()) return false;
    389   return ((name.size() == word.size() ||
    390            !islower(name[word.size()]))
    391           && name.startswith(word));
    392 }
    393 
    394 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
    395   IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
    396   if (!first) return OMF_None;
    397 
    398   StringRef name = first->getName();
    399   if (sel.isUnarySelector()) {
    400     if (name == "autorelease") return OMF_autorelease;
    401     if (name == "dealloc") return OMF_dealloc;
    402     if (name == "finalize") return OMF_finalize;
    403     if (name == "release") return OMF_release;
    404     if (name == "retain") return OMF_retain;
    405     if (name == "retainCount") return OMF_retainCount;
    406     if (name == "self") return OMF_self;
    407   }
    408 
    409   if (name == "performSelector") return OMF_performSelector;
    410 
    411   // The other method families may begin with a prefix of underscores.
    412   while (!name.empty() && name.front() == '_')
    413     name = name.substr(1);
    414 
    415   if (name.empty()) return OMF_None;
    416   switch (name.front()) {
    417   case 'a':
    418     if (startsWithWord(name, "alloc")) return OMF_alloc;
    419     break;
    420   case 'c':
    421     if (startsWithWord(name, "copy")) return OMF_copy;
    422     break;
    423   case 'i':
    424     if (startsWithWord(name, "init")) return OMF_init;
    425     break;
    426   case 'm':
    427     if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
    428     break;
    429   case 'n':
    430     if (startsWithWord(name, "new")) return OMF_new;
    431     break;
    432   default:
    433     break;
    434   }
    435 
    436   return OMF_None;
    437 }
    438 
    439 namespace {
    440   struct SelectorTableImpl {
    441     llvm::FoldingSet<MultiKeywordSelector> Table;
    442     llvm::BumpPtrAllocator Allocator;
    443   };
    444 } // end anonymous namespace.
    445 
    446 static SelectorTableImpl &getSelectorTableImpl(void *P) {
    447   return *static_cast<SelectorTableImpl*>(P);
    448 }
    449 
    450 size_t SelectorTable::getTotalMemory() const {
    451   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
    452   return SelTabImpl.Allocator.getTotalMemory();
    453 }
    454 
    455 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
    456   if (nKeys < 2)
    457     return Selector(IIV[0], nKeys);
    458 
    459   SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
    460 
    461   // Unique selector, to guarantee there is one per name.
    462   llvm::FoldingSetNodeID ID;
    463   MultiKeywordSelector::Profile(ID, IIV, nKeys);
    464 
    465   void *InsertPos = 0;
    466   if (MultiKeywordSelector *SI =
    467         SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
    468     return Selector(SI);
    469 
    470   // MultiKeywordSelector objects are not allocated with new because they have a
    471   // variable size array (for parameter types) at the end of them.
    472   unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
    473   MultiKeywordSelector *SI =
    474     (MultiKeywordSelector*)SelTabImpl.Allocator.Allocate(Size,
    475                                          llvm::alignOf<MultiKeywordSelector>());
    476   new (SI) MultiKeywordSelector(nKeys, IIV);
    477   SelTabImpl.Table.InsertNode(SI, InsertPos);
    478   return Selector(SI);
    479 }
    480 
    481 SelectorTable::SelectorTable() {
    482   Impl = new SelectorTableImpl();
    483 }
    484 
    485 SelectorTable::~SelectorTable() {
    486   delete &getSelectorTableImpl(Impl);
    487 }
    488 
    489 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
    490   switch (Operator) {
    491   case OO_None:
    492   case NUM_OVERLOADED_OPERATORS:
    493     return 0;
    494 
    495 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
    496   case OO_##Name: return Spelling;
    497 #include "clang/Basic/OperatorKinds.def"
    498   }
    499 
    500   return 0;
    501 }
    502