1 //===- IdentifierTable.h - Hash table for identifier lookup -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 /// Defines the clang::IdentifierInfo, clang::IdentifierTable, and
12 /// clang::Selector interfaces.
14 //===----------------------------------------------------------------------===//
16 #ifndef LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
17 #define LLVM_CLANG_BASIC_IDENTIFIERTABLE_H
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/TokenKinds.h"
21 #include "llvm/ADT/DenseMapInfo.h"
22 #include "llvm/ADT/SmallString.h"
23 #include "llvm/ADT/StringMap.h"
24 #include "llvm/ADT/StringRef.h"
25 #include "llvm/Support/Allocator.h"
26 #include "llvm/Support/PointerLikeTypeTraits.h"
27 #include "llvm/Support/type_traits.h"
37 class DeclarationName;
38 class DeclarationNameTable;
41 class MultiKeywordSelector;
44 /// A simple pair of identifier info and location.
45 using IdentifierLocPair = std::pair<IdentifierInfo *, SourceLocation>;
47 /// IdentifierInfo and other related classes are aligned to
48 /// 8 bytes so that DeclarationName can use the lower 3 bits
49 /// of a pointer to one of these classes.
50 enum { IdentifierInfoAlignment = 8 };
52 /// One of these records is kept for each identifier that
53 /// is lexed. This contains information about whether the token was \#define'd,
54 /// is a language keyword, or if it is a front-end token of some sort (e.g. a
55 /// variable or function name). The preprocessor keeps this information in a
56 /// set, and all tok::identifier tokens have a pointer to one of these.
57 /// It is aligned to 8 bytes because DeclarationName needs the lower 3 bits.
58 class alignas(IdentifierInfoAlignment) IdentifierInfo {
59 friend class IdentifierTable;
61 // Front-end token ID or tok::identifier.
64 // ObjC keyword ('protocol' in '@protocol') or builtin (__builtin_inf).
65 // First NUM_OBJC_KEYWORDS values are for Objective-C,
66 // the remaining values are for builtins.
67 unsigned ObjCOrBuiltinID : 13;
69 // True if there is a #define for this.
70 unsigned HasMacro : 1;
72 // True if there was a #define for this.
73 unsigned HadMacro : 1;
75 // True if the identifier is a language extension.
76 unsigned IsExtension : 1;
78 // True if the identifier is a keyword in a newer or proposed Standard.
79 unsigned IsFutureCompatKeyword : 1;
81 // True if the identifier is poisoned.
82 unsigned IsPoisoned : 1;
84 // True if the identifier is a C++ operator keyword.
85 unsigned IsCPPOperatorKeyword : 1;
87 // Internal bit set by the member function RecomputeNeedsHandleIdentifier.
88 // See comment about RecomputeNeedsHandleIdentifier for more info.
89 unsigned NeedsHandleIdentifier : 1;
91 // True if the identifier was loaded (at least partially) from an AST file.
92 unsigned IsFromAST : 1;
94 // True if the identifier has changed from the definition
95 // loaded from an AST file.
96 unsigned ChangedAfterLoad : 1;
98 // True if the identifier's frontend information has changed from the
99 // definition loaded from an AST file.
100 unsigned FEChangedAfterLoad : 1;
102 // True if revertTokenIDToIdentifier was called.
103 unsigned RevertedTokenID : 1;
105 // True if there may be additional information about
106 // this identifier stored externally.
107 unsigned OutOfDate : 1;
109 // True if this is the 'import' contextual keyword.
110 unsigned IsModulesImport : 1;
112 // 29 bits left in a 64-bit word.
114 // Managed by the language front-end.
115 void *FETokenInfo = nullptr;
117 llvm::StringMapEntry<IdentifierInfo *> *Entry = nullptr;
120 : TokenID(tok::identifier), ObjCOrBuiltinID(0), HasMacro(false),
121 HadMacro(false), IsExtension(false), IsFutureCompatKeyword(false),
122 IsPoisoned(false), IsCPPOperatorKeyword(false),
123 NeedsHandleIdentifier(false), IsFromAST(false), ChangedAfterLoad(false),
124 FEChangedAfterLoad(false), RevertedTokenID(false), OutOfDate(false),
125 IsModulesImport(false) {}
128 IdentifierInfo(const IdentifierInfo &) = delete;
129 IdentifierInfo &operator=(const IdentifierInfo &) = delete;
130 IdentifierInfo(IdentifierInfo &&) = delete;
131 IdentifierInfo &operator=(IdentifierInfo &&) = delete;
133 /// Return true if this is the identifier for the specified string.
135 /// This is intended to be used for string literals only: II->isStr("foo").
136 template <std::size_t StrLen>
137 bool isStr(const char (&Str)[StrLen]) const {
138 return getLength() == StrLen-1 &&
139 memcmp(getNameStart(), Str, StrLen-1) == 0;
142 /// Return true if this is the identifier for the specified StringRef.
143 bool isStr(llvm::StringRef Str) const {
144 llvm::StringRef ThisStr(getNameStart(), getLength());
145 return ThisStr == Str;
148 /// Return the beginning of the actual null-terminated string for this
150 const char *getNameStart() const { return Entry->getKeyData(); }
152 /// Efficiently return the length of this identifier info.
153 unsigned getLength() const { return Entry->getKeyLength(); }
155 /// Return the actual identifier string.
156 StringRef getName() const {
157 return StringRef(getNameStart(), getLength());
160 /// Return true if this identifier is \#defined to some other value.
161 /// \note The current definition may be in a module and not currently visible.
162 bool hasMacroDefinition() const {
165 void setHasMacroDefinition(bool Val) {
166 if (HasMacro == Val) return;
170 NeedsHandleIdentifier = true;
173 RecomputeNeedsHandleIdentifier();
176 /// Returns true if this identifier was \#defined to some value at any
177 /// moment. In this case there should be an entry for the identifier in the
178 /// macro history table in Preprocessor.
179 bool hadMacroDefinition() const {
183 /// If this is a source-language token (e.g. 'for'), this API
184 /// can be used to cause the lexer to map identifiers to source-language
186 tok::TokenKind getTokenID() const { return (tok::TokenKind)TokenID; }
188 /// True if revertTokenIDToIdentifier() was called.
189 bool hasRevertedTokenIDToIdentifier() const { return RevertedTokenID; }
191 /// Revert TokenID to tok::identifier; used for GNU libstdc++ 4.2
194 /// TokenID is normally read-only but there are 2 instances where we revert it
195 /// to tok::identifier for libstdc++ 4.2. Keep track of when this happens
196 /// using this method so we can inform serialization about it.
197 void revertTokenIDToIdentifier() {
198 assert(TokenID != tok::identifier && "Already at tok::identifier");
199 TokenID = tok::identifier;
200 RevertedTokenID = true;
202 void revertIdentifierToTokenID(tok::TokenKind TK) {
203 assert(TokenID == tok::identifier && "Should be at tok::identifier");
205 RevertedTokenID = false;
208 /// Return the preprocessor keyword ID for this identifier.
210 /// For example, "define" will return tok::pp_define.
211 tok::PPKeywordKind getPPKeywordID() const;
213 /// Return the Objective-C keyword ID for the this identifier.
215 /// For example, 'class' will return tok::objc_class if ObjC is enabled.
216 tok::ObjCKeywordKind getObjCKeywordID() const {
217 if (ObjCOrBuiltinID < tok::NUM_OBJC_KEYWORDS)
218 return tok::ObjCKeywordKind(ObjCOrBuiltinID);
220 return tok::objc_not_keyword;
222 void setObjCKeywordID(tok::ObjCKeywordKind ID) { ObjCOrBuiltinID = ID; }
224 /// True if setNotBuiltin() was called.
225 bool hasRevertedBuiltin() const {
226 return ObjCOrBuiltinID == tok::NUM_OBJC_KEYWORDS;
229 /// Revert the identifier to a non-builtin identifier. We do this if
230 /// the name of a known builtin library function is used to declare that
231 /// function, but an unexpected type is specified.
232 void revertBuiltin() {
236 /// Return a value indicating whether this is a builtin function.
238 /// 0 is not-built-in. 1+ are specific builtin functions.
239 unsigned getBuiltinID() const {
240 if (ObjCOrBuiltinID >= tok::NUM_OBJC_KEYWORDS)
241 return ObjCOrBuiltinID - tok::NUM_OBJC_KEYWORDS;
245 void setBuiltinID(unsigned ID) {
246 ObjCOrBuiltinID = ID + tok::NUM_OBJC_KEYWORDS;
247 assert(ObjCOrBuiltinID - unsigned(tok::NUM_OBJC_KEYWORDS) == ID
248 && "ID too large for field!");
251 unsigned getObjCOrBuiltinID() const { return ObjCOrBuiltinID; }
252 void setObjCOrBuiltinID(unsigned ID) { ObjCOrBuiltinID = ID; }
254 /// get/setExtension - Initialize information about whether or not this
255 /// language token is an extension. This controls extension warnings, and is
256 /// only valid if a custom token ID is set.
257 bool isExtensionToken() const { return IsExtension; }
258 void setIsExtensionToken(bool Val) {
261 NeedsHandleIdentifier = true;
263 RecomputeNeedsHandleIdentifier();
266 /// is/setIsFutureCompatKeyword - Initialize information about whether or not
267 /// this language token is a keyword in a newer or proposed Standard. This
268 /// controls compatibility warnings, and is only true when not parsing the
269 /// corresponding Standard. Once a compatibility problem has been diagnosed
270 /// with this keyword, the flag will be cleared.
271 bool isFutureCompatKeyword() const { return IsFutureCompatKeyword; }
272 void setIsFutureCompatKeyword(bool Val) {
273 IsFutureCompatKeyword = Val;
275 NeedsHandleIdentifier = true;
277 RecomputeNeedsHandleIdentifier();
280 /// setIsPoisoned - Mark this identifier as poisoned. After poisoning, the
281 /// Preprocessor will emit an error every time this token is used.
282 void setIsPoisoned(bool Value = true) {
285 NeedsHandleIdentifier = true;
287 RecomputeNeedsHandleIdentifier();
290 /// Return true if this token has been poisoned.
291 bool isPoisoned() const { return IsPoisoned; }
293 /// isCPlusPlusOperatorKeyword/setIsCPlusPlusOperatorKeyword controls whether
294 /// this identifier is a C++ alternate representation of an operator.
295 void setIsCPlusPlusOperatorKeyword(bool Val = true) {
296 IsCPPOperatorKeyword = Val;
298 bool isCPlusPlusOperatorKeyword() const { return IsCPPOperatorKeyword; }
300 /// Return true if this token is a keyword in the specified language.
301 bool isKeyword(const LangOptions &LangOpts) const;
303 /// Return true if this token is a C++ keyword in the specified
305 bool isCPlusPlusKeyword(const LangOptions &LangOpts) const;
307 /// Get and set FETokenInfo. The language front-end is allowed to associate
308 /// arbitrary metadata with this token.
309 void *getFETokenInfo() const { return FETokenInfo; }
310 void setFETokenInfo(void *T) { FETokenInfo = T; }
312 /// Return true if the Preprocessor::HandleIdentifier must be called
313 /// on a token of this identifier.
315 /// If this returns false, we know that HandleIdentifier will not affect
317 bool isHandleIdentifierCase() const { return NeedsHandleIdentifier; }
319 /// Return true if the identifier in its current state was loaded
320 /// from an AST file.
321 bool isFromAST() const { return IsFromAST; }
323 void setIsFromAST() { IsFromAST = true; }
325 /// Determine whether this identifier has changed since it was loaded
326 /// from an AST file.
327 bool hasChangedSinceDeserialization() const {
328 return ChangedAfterLoad;
331 /// Note that this identifier has changed since it was loaded from
333 void setChangedSinceDeserialization() {
334 ChangedAfterLoad = true;
337 /// Determine whether the frontend token information for this
338 /// identifier has changed since it was loaded from an AST file.
339 bool hasFETokenInfoChangedSinceDeserialization() const {
340 return FEChangedAfterLoad;
343 /// Note that the frontend token information for this identifier has
344 /// changed since it was loaded from an AST file.
345 void setFETokenInfoChangedSinceDeserialization() {
346 FEChangedAfterLoad = true;
349 /// Determine whether the information for this identifier is out of
350 /// date with respect to the external source.
351 bool isOutOfDate() const { return OutOfDate; }
353 /// Set whether the information for this identifier is out of
354 /// date with respect to the external source.
355 void setOutOfDate(bool OOD) {
358 NeedsHandleIdentifier = true;
360 RecomputeNeedsHandleIdentifier();
363 /// Determine whether this is the contextual keyword \c import.
364 bool isModulesImport() const { return IsModulesImport; }
366 /// Set whether this identifier is the contextual keyword \c import.
367 void setModulesImport(bool I) {
370 NeedsHandleIdentifier = true;
372 RecomputeNeedsHandleIdentifier();
375 /// Return true if this identifier is an editor placeholder.
377 /// Editor placeholders are produced by the code-completion engine and are
378 /// represented as characters between '<#' and '#>' in the source code. An
379 /// example of auto-completed call with a placeholder parameter is shown
382 /// function(<#int x#>);
384 bool isEditorPlaceholder() const {
385 return getName().startswith("<#") && getName().endswith("#>");
388 /// Provide less than operator for lexicographical sorting.
389 bool operator<(const IdentifierInfo &RHS) const {
390 return getName() < RHS.getName();
394 /// The Preprocessor::HandleIdentifier does several special (but rare)
395 /// things to identifiers of various sorts. For example, it changes the
396 /// \c for keyword token from tok::identifier to tok::for.
398 /// This method is very tied to the definition of HandleIdentifier. Any
399 /// change to it should be reflected here.
400 void RecomputeNeedsHandleIdentifier() {
401 NeedsHandleIdentifier = isPoisoned() || hasMacroDefinition() ||
402 isExtensionToken() || isFutureCompatKeyword() ||
403 isOutOfDate() || isModulesImport();
407 /// An RAII object for [un]poisoning an identifier within a scope.
409 /// \p II is allowed to be null, in which case objects of this type have
411 class PoisonIdentifierRAIIObject {
412 IdentifierInfo *const II;
416 PoisonIdentifierRAIIObject(IdentifierInfo *II, bool NewValue)
417 : II(II), OldValue(II ? II->isPoisoned() : false) {
419 II->setIsPoisoned(NewValue);
422 ~PoisonIdentifierRAIIObject() {
424 II->setIsPoisoned(OldValue);
428 /// An iterator that walks over all of the known identifiers
429 /// in the lookup table.
431 /// Since this iterator uses an abstract interface via virtual
432 /// functions, it uses an object-oriented interface rather than the
433 /// more standard C++ STL iterator interface. In this OO-style
434 /// iteration, the single function \c Next() provides dereference,
435 /// advance, and end-of-sequence checking in a single
436 /// operation. Subclasses of this iterator type will provide the
437 /// actual functionality.
438 class IdentifierIterator {
440 IdentifierIterator() = default;
443 IdentifierIterator(const IdentifierIterator &) = delete;
444 IdentifierIterator &operator=(const IdentifierIterator &) = delete;
446 virtual ~IdentifierIterator();
448 /// Retrieve the next string in the identifier table and
449 /// advances the iterator for the following string.
451 /// \returns The next string in the identifier table. If there is
452 /// no such string, returns an empty \c StringRef.
453 virtual StringRef Next() = 0;
456 /// Provides lookups to, and iteration over, IdentiferInfo objects.
457 class IdentifierInfoLookup {
459 virtual ~IdentifierInfoLookup();
461 /// Return the IdentifierInfo for the specified named identifier.
463 /// Unlike the version in IdentifierTable, this returns a pointer instead
464 /// of a reference. If the pointer is null then the IdentifierInfo cannot
466 virtual IdentifierInfo* get(StringRef Name) = 0;
468 /// Retrieve an iterator into the set of all identifiers
469 /// known to this identifier lookup source.
471 /// This routine provides access to all of the identifiers known to
472 /// the identifier lookup, allowing access to the contents of the
473 /// identifiers without introducing the overhead of constructing
474 /// IdentifierInfo objects for each.
476 /// \returns A new iterator into the set of known identifiers. The
477 /// caller is responsible for deleting this iterator.
478 virtual IdentifierIterator *getIdentifiers();
481 /// Implements an efficient mapping from strings to IdentifierInfo nodes.
483 /// This has no other purpose, but this is an extremely performance-critical
484 /// piece of the code, as each occurrence of every identifier goes through
486 class IdentifierTable {
487 // Shark shows that using MallocAllocator is *much* slower than using this
489 using HashTableTy = llvm::StringMap<IdentifierInfo *, llvm::BumpPtrAllocator>;
490 HashTableTy HashTable;
492 IdentifierInfoLookup* ExternalLookup;
495 /// Create the identifier table.
496 explicit IdentifierTable(IdentifierInfoLookup *ExternalLookup = nullptr);
498 /// Create the identifier table, populating it with info about the
499 /// language keywords for the language specified by \p LangOpts.
500 explicit IdentifierTable(const LangOptions &LangOpts,
501 IdentifierInfoLookup *ExternalLookup = nullptr);
503 /// Set the external identifier lookup mechanism.
504 void setExternalIdentifierLookup(IdentifierInfoLookup *IILookup) {
505 ExternalLookup = IILookup;
508 /// Retrieve the external identifier lookup object, if any.
509 IdentifierInfoLookup *getExternalIdentifierLookup() const {
510 return ExternalLookup;
513 llvm::BumpPtrAllocator& getAllocator() {
514 return HashTable.getAllocator();
517 /// Return the identifier token info for the specified named
519 IdentifierInfo &get(StringRef Name) {
520 auto &Entry = *HashTable.insert(std::make_pair(Name, nullptr)).first;
522 IdentifierInfo *&II = Entry.second;
525 // No entry; if we have an external lookup, look there first.
526 if (ExternalLookup) {
527 II = ExternalLookup->get(Name);
532 // Lookups failed, make a new IdentifierInfo.
533 void *Mem = getAllocator().Allocate<IdentifierInfo>();
534 II = new (Mem) IdentifierInfo();
536 // Make sure getName() knows how to find the IdentifierInfo
543 IdentifierInfo &get(StringRef Name, tok::TokenKind TokenCode) {
544 IdentifierInfo &II = get(Name);
545 II.TokenID = TokenCode;
546 assert(II.TokenID == (unsigned) TokenCode && "TokenCode too large");
550 /// Gets an IdentifierInfo for the given name without consulting
551 /// external sources.
553 /// This is a version of get() meant for external sources that want to
554 /// introduce or modify an identifier. If they called get(), they would
555 /// likely end up in a recursion.
556 IdentifierInfo &getOwn(StringRef Name) {
557 auto &Entry = *HashTable.insert(std::make_pair(Name, nullptr)).first;
559 IdentifierInfo *&II = Entry.second;
563 // Lookups failed, make a new IdentifierInfo.
564 void *Mem = getAllocator().Allocate<IdentifierInfo>();
565 II = new (Mem) IdentifierInfo();
567 // Make sure getName() knows how to find the IdentifierInfo
571 // If this is the 'import' contextual keyword, mark it as such.
572 if (Name.equals("import"))
573 II->setModulesImport(true);
578 using iterator = HashTableTy::const_iterator;
579 using const_iterator = HashTableTy::const_iterator;
581 iterator begin() const { return HashTable.begin(); }
582 iterator end() const { return HashTable.end(); }
583 unsigned size() const { return HashTable.size(); }
585 /// Print some statistics to stderr that indicate how well the
586 /// hashing is doing.
587 void PrintStats() const;
589 /// Populate the identifier table with info about the language keywords
590 /// for the language specified by \p LangOpts.
591 void AddKeywords(const LangOptions &LangOpts);
594 /// A family of Objective-C methods.
596 /// These families have no inherent meaning in the language, but are
597 /// nonetheless central enough in the existing implementations to
598 /// merit direct AST support. While, in theory, arbitrary methods can
599 /// be considered to form families, we focus here on the methods
600 /// involving allocation and retain-count management, as these are the
601 /// most "core" and the most likely to be useful to diverse clients
602 /// without extra information.
604 /// Both selectors and actual method declarations may be classified
605 /// into families. Method families may impose additional restrictions
606 /// beyond their selector name; for example, a method called '_init'
607 /// that returns void is not considered to be in the 'init' family
608 /// (but would be if it returned 'id'). It is also possible to
609 /// explicitly change or remove a method's family. Therefore the
610 /// method's family should be considered the single source of truth.
611 enum ObjCMethodFamily {
612 /// No particular method family.
615 // Selectors in these families may have arbitrary arity, may be
616 // written with arbitrary leading underscores, and may have
617 // additional CamelCase "words" in their first selector chunk
618 // following the family name.
625 // These families are singletons consisting only of the nullary
626 // selector with the given name.
636 // performSelector families
640 /// Enough bits to store any enumerator in ObjCMethodFamily or
641 /// InvalidObjCMethodFamily.
642 enum { ObjCMethodFamilyBitWidth = 4 };
644 /// An invalid value of ObjCMethodFamily.
645 enum { InvalidObjCMethodFamily = (1 << ObjCMethodFamilyBitWidth) - 1 };
647 /// A family of Objective-C methods.
649 /// These are family of methods whose result type is initially 'id', but
650 /// but are candidate for the result type to be changed to 'instancetype'.
651 enum ObjCInstanceTypeFamily {
660 enum ObjCStringFormatFamily {
666 /// Smart pointer class that efficiently represents Objective-C method
669 /// This class will either point to an IdentifierInfo or a
670 /// MultiKeywordSelector (which is private). This enables us to optimize
671 /// selectors that take no arguments and selectors that take 1 argument, which
672 /// accounts for 78% of all selectors in Cocoa.h.
674 friend class Diagnostic;
675 friend class SelectorTable; // only the SelectorTable can create these
676 friend class DeclarationName; // and the AST's DeclarationName.
678 enum IdentifierInfoFlag {
679 // Empty selector = 0. Note that these enumeration values must
680 // correspond to the enumeration values of DeclarationName::StoredNameKind
687 /// A pointer to the MultiKeywordSelector or IdentifierInfo. We use the low
688 /// three bits of InfoPtr to store an IdentifierInfoFlag. Note that in any
689 /// case IdentifierInfo and MultiKeywordSelector are already aligned to
690 /// 8 bytes even on 32 bits archs because of DeclarationName.
691 uintptr_t InfoPtr = 0;
693 Selector(IdentifierInfo *II, unsigned nArgs) {
694 InfoPtr = reinterpret_cast<uintptr_t>(II);
695 assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo");
696 assert(nArgs < 2 && "nArgs not equal to 0/1");
700 Selector(MultiKeywordSelector *SI) {
701 InfoPtr = reinterpret_cast<uintptr_t>(SI);
702 assert((InfoPtr & ArgFlags) == 0 &&"Insufficiently aligned IdentifierInfo");
706 IdentifierInfo *getAsIdentifierInfo() const {
707 if (getIdentifierInfoFlag() < MultiArg)
708 return reinterpret_cast<IdentifierInfo *>(InfoPtr & ~ArgFlags);
712 MultiKeywordSelector *getMultiKeywordSelector() const {
713 return reinterpret_cast<MultiKeywordSelector *>(InfoPtr & ~ArgFlags);
716 unsigned getIdentifierInfoFlag() const {
717 return InfoPtr & ArgFlags;
720 static ObjCMethodFamily getMethodFamilyImpl(Selector sel);
722 static ObjCStringFormatFamily getStringFormatFamilyImpl(Selector sel);
725 /// The default ctor should only be used when creating data structures that
726 /// will contain selectors.
727 Selector() = default;
728 explicit Selector(uintptr_t V) : InfoPtr(V) {}
730 /// operator==/!= - Indicate whether the specified selectors are identical.
731 bool operator==(Selector RHS) const {
732 return InfoPtr == RHS.InfoPtr;
734 bool operator!=(Selector RHS) const {
735 return InfoPtr != RHS.InfoPtr;
738 void *getAsOpaquePtr() const {
739 return reinterpret_cast<void*>(InfoPtr);
742 /// Determine whether this is the empty selector.
743 bool isNull() const { return InfoPtr == 0; }
745 // Predicates to identify the selector type.
746 bool isKeywordSelector() const {
747 return getIdentifierInfoFlag() != ZeroArg;
750 bool isUnarySelector() const {
751 return getIdentifierInfoFlag() == ZeroArg;
754 unsigned getNumArgs() const;
756 /// Retrieve the identifier at a given position in the selector.
758 /// Note that the identifier pointer returned may be NULL. Clients that only
759 /// care about the text of the identifier string, and not the specific,
760 /// uniqued identifier pointer, should use \c getNameForSlot(), which returns
761 /// an empty string when the identifier pointer would be NULL.
763 /// \param argIndex The index for which we want to retrieve the identifier.
764 /// This index shall be less than \c getNumArgs() unless this is a keyword
765 /// selector, in which case 0 is the only permissible value.
767 /// \returns the uniqued identifier for this slot, or NULL if this slot has
768 /// no corresponding identifier.
769 IdentifierInfo *getIdentifierInfoForSlot(unsigned argIndex) const;
771 /// Retrieve the name at a given position in the selector.
773 /// \param argIndex The index for which we want to retrieve the name.
774 /// This index shall be less than \c getNumArgs() unless this is a keyword
775 /// selector, in which case 0 is the only permissible value.
777 /// \returns the name for this slot, which may be the empty string if no
778 /// name was supplied.
779 StringRef getNameForSlot(unsigned argIndex) const;
781 /// Derive the full selector name (e.g. "foo:bar:") and return
782 /// it as an std::string.
783 std::string getAsString() const;
785 /// Prints the full selector name (e.g. "foo:bar:").
786 void print(llvm::raw_ostream &OS) const;
790 /// Derive the conventional family of this method.
791 ObjCMethodFamily getMethodFamily() const {
792 return getMethodFamilyImpl(*this);
795 ObjCStringFormatFamily getStringFormatFamily() const {
796 return getStringFormatFamilyImpl(*this);
799 static Selector getEmptyMarker() {
800 return Selector(uintptr_t(-1));
803 static Selector getTombstoneMarker() {
804 return Selector(uintptr_t(-2));
807 static ObjCInstanceTypeFamily getInstTypeMethodFamily(Selector sel);
810 /// This table allows us to fully hide how we implement
811 /// multi-keyword caching.
812 class SelectorTable {
813 // Actually a SelectorTableImpl
818 SelectorTable(const SelectorTable &) = delete;
819 SelectorTable &operator=(const SelectorTable &) = delete;
822 /// Can create any sort of selector.
824 /// \p NumArgs indicates whether this is a no argument selector "foo", a
825 /// single argument selector "foo:" or multi-argument "foo:bar:".
826 Selector getSelector(unsigned NumArgs, IdentifierInfo **IIV);
828 Selector getUnarySelector(IdentifierInfo *ID) {
829 return Selector(ID, 1);
832 Selector getNullarySelector(IdentifierInfo *ID) {
833 return Selector(ID, 0);
836 /// Return the total amount of memory allocated for managing selectors.
837 size_t getTotalMemory() const;
839 /// Return the default setter name for the given identifier.
841 /// This is "set" + \p Name where the initial character of \p Name
842 /// has been capitalized.
843 static SmallString<64> constructSetterName(StringRef Name);
845 /// Return the default setter selector for the given identifier.
847 /// This is "set" + \p Name where the initial character of \p Name
848 /// has been capitalized.
849 static Selector constructSetterSelector(IdentifierTable &Idents,
850 SelectorTable &SelTable,
851 const IdentifierInfo *Name);
853 /// Return the property name for the given setter selector.
854 static std::string getPropertyNameFromSetterSelector(Selector Sel);
859 /// DeclarationNameExtra is used as a base of various uncommon special names.
860 /// This class is needed since DeclarationName has not enough space to store
861 /// the kind of every possible names. Therefore the kind of common names is
862 /// stored directly in DeclarationName, and the kind of uncommon names is
863 /// stored in DeclarationNameExtra. It is aligned to 8 bytes because
864 /// DeclarationName needs the lower 3 bits to store the kind of common names.
865 /// DeclarationNameExtra is tightly coupled to DeclarationName and any change
866 /// here is very likely to require changes in DeclarationName(Table).
867 class alignas(IdentifierInfoAlignment) DeclarationNameExtra {
868 friend class clang::DeclarationName;
869 friend class clang::DeclarationNameTable;
872 /// The kind of "extra" information stored in the DeclarationName. See
873 /// @c ExtraKindOrNumArgs for an explanation of how these enumerator values
874 /// are used. Note that DeclarationName depends on the numerical values
875 /// of the enumerators in this enum. See DeclarationName::StoredNameKind
878 CXXDeductionGuideName,
879 CXXLiteralOperatorName,
884 /// ExtraKindOrNumArgs has one of the following meaning:
885 /// * The kind of an uncommon C++ special name. This DeclarationNameExtra
886 /// is in this case in fact either a CXXDeductionGuideNameExtra or
887 /// a CXXLiteralOperatorIdName.
889 /// * It may be also name common to C++ using-directives (CXXUsingDirective),
891 /// * Otherwise it is ObjCMultiArgSelector+NumArgs, where NumArgs is
892 /// the number of arguments in the Objective-C selector, in which
893 /// case the DeclarationNameExtra is also a MultiKeywordSelector.
894 unsigned ExtraKindOrNumArgs;
896 DeclarationNameExtra(ExtraKind Kind) : ExtraKindOrNumArgs(Kind) {}
897 DeclarationNameExtra(unsigned NumArgs)
898 : ExtraKindOrNumArgs(ObjCMultiArgSelector + NumArgs) {}
900 /// Return the corresponding ExtraKind.
901 ExtraKind getKind() const {
902 return static_cast<ExtraKind>(ExtraKindOrNumArgs >
903 (unsigned)ObjCMultiArgSelector
904 ? (unsigned)ObjCMultiArgSelector
905 : ExtraKindOrNumArgs);
908 /// Return the number of arguments in an ObjC selector. Only valid when this
909 /// is indeed an ObjCMultiArgSelector.
910 unsigned getNumArgs() const {
911 assert(ExtraKindOrNumArgs >= (unsigned)ObjCMultiArgSelector &&
912 "getNumArgs called but this is not an ObjC selector!");
913 return ExtraKindOrNumArgs - (unsigned)ObjCMultiArgSelector;
917 } // namespace detail
923 /// Define DenseMapInfo so that Selectors can be used as keys in DenseMap and
926 struct DenseMapInfo<clang::Selector> {
927 static clang::Selector getEmptyKey() {
928 return clang::Selector::getEmptyMarker();
931 static clang::Selector getTombstoneKey() {
932 return clang::Selector::getTombstoneMarker();
935 static unsigned getHashValue(clang::Selector S);
937 static bool isEqual(clang::Selector LHS, clang::Selector RHS) {
943 struct isPodLike<clang::Selector> { static const bool value = true; };
946 struct PointerLikeTypeTraits<clang::Selector> {
947 static const void *getAsVoidPointer(clang::Selector P) {
948 return P.getAsOpaquePtr();
951 static clang::Selector getFromVoidPointer(const void *P) {
952 return clang::Selector(reinterpret_cast<uintptr_t>(P));
955 enum { NumLowBitsAvailable = 0 };
958 // Provide PointerLikeTypeTraits for IdentifierInfo pointers, which
959 // are not guaranteed to be 8-byte aligned.
961 struct PointerLikeTypeTraits<clang::IdentifierInfo*> {
962 static void *getAsVoidPointer(clang::IdentifierInfo* P) {
966 static clang::IdentifierInfo *getFromVoidPointer(void *P) {
967 return static_cast<clang::IdentifierInfo*>(P);
970 enum { NumLowBitsAvailable = 1 };
974 struct PointerLikeTypeTraits<const clang::IdentifierInfo*> {
975 static const void *getAsVoidPointer(const clang::IdentifierInfo* P) {
979 static const clang::IdentifierInfo *getFromVoidPointer(const void *P) {
980 return static_cast<const clang::IdentifierInfo*>(P);
983 enum { NumLowBitsAvailable = 1 };
988 #endif // LLVM_CLANG_BASIC_IDENTIFIERTABLE_H