1 //===- IdentifierTable.cpp - Hash table for identifier lookup -------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements the IdentifierInfo, IdentifierVisitor, and
10 // IdentifierTable interfaces.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Basic/IdentifierTable.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/LangOptions.h"
17 #include "clang/Basic/OperatorKinds.h"
18 #include "clang/Basic/Specifiers.h"
19 #include "clang/Basic/TargetBuiltins.h"
20 #include "clang/Basic/TokenKinds.h"
21 #include "llvm/ADT/DenseMapInfo.h"
22 #include "llvm/ADT/FoldingSet.h"
23 #include "llvm/ADT/SmallString.h"
24 #include "llvm/ADT/StringMap.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/Support/Allocator.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/raw_ostream.h"
29 #include <cassert>
30 #include <cstdio>
31 #include <cstring>
32 #include <string>
33
34 using namespace clang;
35
36 // A check to make sure the ObjCOrBuiltinID has sufficient room to store the
37 // largest possible target/aux-target combination. If we exceed this, we likely
38 // need to just change the ObjCOrBuiltinIDBits value in IdentifierTable.h.
39 static_assert(2 * LargestBuiltinID < (2 << (ObjCOrBuiltinIDBits - 1)),
40 "Insufficient ObjCOrBuiltinID Bits");
41
42 //===----------------------------------------------------------------------===//
43 // IdentifierTable Implementation
44 //===----------------------------------------------------------------------===//
45
46 IdentifierIterator::~IdentifierIterator() = default;
47
48 IdentifierInfoLookup::~IdentifierInfoLookup() = default;
49
50 namespace {
51
52 /// A simple identifier lookup iterator that represents an
53 /// empty sequence of identifiers.
54 class EmptyLookupIterator : public IdentifierIterator
55 {
56 public:
Next()57 StringRef Next() override { return StringRef(); }
58 };
59
60 } // namespace
61
getIdentifiers()62 IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
63 return new EmptyLookupIterator();
64 }
65
IdentifierTable(IdentifierInfoLookup * ExternalLookup)66 IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
67 : HashTable(8192), // Start with space for 8K identifiers.
68 ExternalLookup(ExternalLookup) {}
69
IdentifierTable(const LangOptions & LangOpts,IdentifierInfoLookup * ExternalLookup)70 IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
71 IdentifierInfoLookup *ExternalLookup)
72 : IdentifierTable(ExternalLookup) {
73 // Populate the identifier table with info about keywords for the current
74 // language.
75 AddKeywords(LangOpts);
76 }
77
78 //===----------------------------------------------------------------------===//
79 // Language Keyword Implementation
80 //===----------------------------------------------------------------------===//
81
82 // Constants for TokenKinds.def
83 namespace {
84
85 enum {
86 KEYC99 = 0x1,
87 KEYCXX = 0x2,
88 KEYCXX11 = 0x4,
89 KEYGNU = 0x8,
90 KEYMS = 0x10,
91 BOOLSUPPORT = 0x20,
92 KEYALTIVEC = 0x40,
93 KEYNOCXX = 0x80,
94 KEYBORLAND = 0x100,
95 KEYOPENCLC = 0x200,
96 KEYC11 = 0x400,
97 KEYNOMS18 = 0x800,
98 KEYNOOPENCL = 0x1000,
99 WCHARSUPPORT = 0x2000,
100 HALFSUPPORT = 0x4000,
101 CHAR8SUPPORT = 0x8000,
102 KEYCONCEPTS = 0x10000,
103 KEYOBJC = 0x20000,
104 KEYZVECTOR = 0x40000,
105 KEYCOROUTINES = 0x80000,
106 KEYMODULES = 0x100000,
107 KEYCXX20 = 0x200000,
108 KEYOPENCLCXX = 0x400000,
109 KEYMSCOMPAT = 0x800000,
110 KEYSYCL = 0x1000000,
111 KEYCUDA = 0x2000000,
112 KEYMAX = KEYCUDA, // The maximum key
113 KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX20,
114 KEYALL = (KEYMAX | (KEYMAX-1)) & ~KEYNOMS18 &
115 ~KEYNOOPENCL // KEYNOMS18 and KEYNOOPENCL are used to exclude.
116 };
117
118 /// How a keyword is treated in the selected standard.
119 enum KeywordStatus {
120 KS_Disabled, // Disabled
121 KS_Extension, // Is an extension
122 KS_Enabled, // Enabled
123 KS_Future // Is a keyword in future standard
124 };
125
126 } // namespace
127
128 /// Translates flags as specified in TokenKinds.def into keyword status
129 /// in the given language standard.
getKeywordStatus(const LangOptions & LangOpts,unsigned Flags)130 static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
131 unsigned Flags) {
132 if (Flags == KEYALL) return KS_Enabled;
133 if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
134 if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
135 if (LangOpts.CPlusPlus20 && (Flags & KEYCXX20)) return KS_Enabled;
136 if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
137 if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
138 if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
139 if (LangOpts.MSVCCompat && (Flags & KEYMSCOMPAT)) return KS_Enabled;
140 if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
141 if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
142 if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
143 if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
144 if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
145 if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
146 if (LangOpts.ZVector && (Flags & KEYZVECTOR)) return KS_Enabled;
147 if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLC))
148 return KS_Enabled;
149 if (LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLCXX)) return KS_Enabled;
150 if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
151 if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
152 // We treat bridge casts as objective-C keywords so we can warn on them
153 // in non-arc mode.
154 if (LangOpts.ObjC && (Flags & KEYOBJC)) return KS_Enabled;
155 if (LangOpts.CPlusPlus20 && (Flags & KEYCONCEPTS)) return KS_Enabled;
156 if (LangOpts.Coroutines && (Flags & KEYCOROUTINES)) return KS_Enabled;
157 if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
158 if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
159 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus20 && (Flags & CHAR8SUPPORT))
160 return KS_Future;
161 if (LangOpts.isSYCL() && (Flags & KEYSYCL))
162 return KS_Enabled;
163 if (LangOpts.CUDA && (Flags & KEYCUDA))
164 return KS_Enabled;
165 return KS_Disabled;
166 }
167
168 /// AddKeyword - This method is used to associate a token ID with specific
169 /// identifiers because they are language keywords. This causes the lexer to
170 /// automatically map matching identifiers to specialized token codes.
AddKeyword(StringRef Keyword,tok::TokenKind TokenCode,unsigned Flags,const LangOptions & LangOpts,IdentifierTable & Table)171 static void AddKeyword(StringRef Keyword,
172 tok::TokenKind TokenCode, unsigned Flags,
173 const LangOptions &LangOpts, IdentifierTable &Table) {
174 KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
175
176 // Don't add this keyword under MSVCCompat.
177 if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
178 !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
179 return;
180
181 // Don't add this keyword under OpenCL.
182 if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
183 return;
184
185 // Don't add this keyword if disabled in this language.
186 if (AddResult == KS_Disabled) return;
187
188 IdentifierInfo &Info =
189 Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
190 Info.setIsExtensionToken(AddResult == KS_Extension);
191 Info.setIsFutureCompatKeyword(AddResult == KS_Future);
192 }
193
194 /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
195 /// representations.
AddCXXOperatorKeyword(StringRef Keyword,tok::TokenKind TokenCode,IdentifierTable & Table)196 static void AddCXXOperatorKeyword(StringRef Keyword,
197 tok::TokenKind TokenCode,
198 IdentifierTable &Table) {
199 IdentifierInfo &Info = Table.get(Keyword, TokenCode);
200 Info.setIsCPlusPlusOperatorKeyword();
201 }
202
203 /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
204 /// or "property".
AddObjCKeyword(StringRef Name,tok::ObjCKeywordKind ObjCID,IdentifierTable & Table)205 static void AddObjCKeyword(StringRef Name,
206 tok::ObjCKeywordKind ObjCID,
207 IdentifierTable &Table) {
208 Table.get(Name).setObjCKeywordID(ObjCID);
209 }
210
211 /// AddKeywords - Add all keywords to the symbol table.
212 ///
AddKeywords(const LangOptions & LangOpts)213 void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
214 // Add keywords and tokens for the current language.
215 #define KEYWORD(NAME, FLAGS) \
216 AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
217 FLAGS, LangOpts, *this);
218 #define ALIAS(NAME, TOK, FLAGS) \
219 AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
220 FLAGS, LangOpts, *this);
221 #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
222 if (LangOpts.CXXOperatorNames) \
223 AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
224 #define OBJC_AT_KEYWORD(NAME) \
225 if (LangOpts.ObjC) \
226 AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
227 #define TESTING_KEYWORD(NAME, FLAGS)
228 #include "clang/Basic/TokenKinds.def"
229
230 if (LangOpts.ParseUnknownAnytype)
231 AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
232 LangOpts, *this);
233
234 if (LangOpts.DeclSpecKeyword)
235 AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
236
237 if (LangOpts.IEEE128)
238 AddKeyword("__ieee128", tok::kw___float128, KEYALL, LangOpts, *this);
239
240 // Add the 'import' contextual keyword.
241 get("import").setModulesImport(true);
242 }
243
244 /// Checks if the specified token kind represents a keyword in the
245 /// specified language.
246 /// \returns Status of the keyword in the language.
getTokenKwStatus(const LangOptions & LangOpts,tok::TokenKind K)247 static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
248 tok::TokenKind K) {
249 switch (K) {
250 #define KEYWORD(NAME, FLAGS) \
251 case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
252 #include "clang/Basic/TokenKinds.def"
253 default: return KS_Disabled;
254 }
255 }
256
257 /// Returns true if the identifier represents a keyword in the
258 /// specified language.
isKeyword(const LangOptions & LangOpts) const259 bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
260 switch (getTokenKwStatus(LangOpts, getTokenID())) {
261 case KS_Enabled:
262 case KS_Extension:
263 return true;
264 default:
265 return false;
266 }
267 }
268
269 /// Returns true if the identifier represents a C++ keyword in the
270 /// specified language.
isCPlusPlusKeyword(const LangOptions & LangOpts) const271 bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
272 if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
273 return false;
274 // This is a C++ keyword if this identifier is not a keyword when checked
275 // using LangOptions without C++ support.
276 LangOptions LangOptsNoCPP = LangOpts;
277 LangOptsNoCPP.CPlusPlus = false;
278 LangOptsNoCPP.CPlusPlus11 = false;
279 LangOptsNoCPP.CPlusPlus20 = false;
280 return !isKeyword(LangOptsNoCPP);
281 }
282
283 ReservedIdentifierStatus
isReserved(const LangOptions & LangOpts) const284 IdentifierInfo::isReserved(const LangOptions &LangOpts) const {
285 StringRef Name = getName();
286
287 // '_' is a reserved identifier, but its use is so common (e.g. to store
288 // ignored values) that we don't warn on it.
289 if (Name.size() <= 1)
290 return ReservedIdentifierStatus::NotReserved;
291
292 // [lex.name] p3
293 if (Name[0] == '_') {
294
295 // Each name that begins with an underscore followed by an uppercase letter
296 // or another underscore is reserved.
297 if (Name[1] == '_')
298 return ReservedIdentifierStatus::StartsWithDoubleUnderscore;
299
300 if ('A' <= Name[1] && Name[1] <= 'Z')
301 return ReservedIdentifierStatus::
302 StartsWithUnderscoreFollowedByCapitalLetter;
303
304 // This is a bit misleading: it actually means it's only reserved if we're
305 // at global scope because it starts with an underscore.
306 return ReservedIdentifierStatus::StartsWithUnderscoreAtGlobalScope;
307 }
308
309 // Each name that contains a double underscore (__) is reserved.
310 if (LangOpts.CPlusPlus && Name.contains("__"))
311 return ReservedIdentifierStatus::ContainsDoubleUnderscore;
312
313 return ReservedIdentifierStatus::NotReserved;
314 }
315
deuglifiedName() const316 StringRef IdentifierInfo::deuglifiedName() const {
317 StringRef Name = getName();
318 if (Name.size() >= 2 && Name.front() == '_' &&
319 (Name[1] == '_' || (Name[1] >= 'A' && Name[1] <= 'Z')))
320 return Name.ltrim('_');
321 return Name;
322 }
323
getPPKeywordID() const324 tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
325 // We use a perfect hash function here involving the length of the keyword,
326 // the first and third character. For preprocessor ID's there are no
327 // collisions (if there were, the switch below would complain about duplicate
328 // case values). Note that this depends on 'if' being null terminated.
329
330 #define HASH(LEN, FIRST, THIRD) \
331 (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
332 #define CASE(LEN, FIRST, THIRD, NAME) \
333 case HASH(LEN, FIRST, THIRD): \
334 return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
335
336 unsigned Len = getLength();
337 if (Len < 2) return tok::pp_not_keyword;
338 const char *Name = getNameStart();
339 switch (HASH(Len, Name[0], Name[2])) {
340 default: return tok::pp_not_keyword;
341 CASE( 2, 'i', '\0', if);
342 CASE( 4, 'e', 'i', elif);
343 CASE( 4, 'e', 's', else);
344 CASE( 4, 'l', 'n', line);
345 CASE( 4, 's', 'c', sccs);
346 CASE( 5, 'e', 'd', endif);
347 CASE( 5, 'e', 'r', error);
348 CASE( 5, 'i', 'e', ident);
349 CASE( 5, 'i', 'd', ifdef);
350 CASE( 5, 'u', 'd', undef);
351
352 CASE( 6, 'a', 's', assert);
353 CASE( 6, 'd', 'f', define);
354 CASE( 6, 'i', 'n', ifndef);
355 CASE( 6, 'i', 'p', import);
356 CASE( 6, 'p', 'a', pragma);
357
358 CASE( 7, 'd', 'f', defined);
359 CASE( 7, 'e', 'i', elifdef);
360 CASE( 7, 'i', 'c', include);
361 CASE( 7, 'w', 'r', warning);
362
363 CASE( 8, 'e', 'i', elifndef);
364 CASE( 8, 'u', 'a', unassert);
365 CASE(12, 'i', 'c', include_next);
366
367 CASE(14, '_', 'p', __public_macro);
368
369 CASE(15, '_', 'p', __private_macro);
370
371 CASE(16, '_', 'i', __include_macros);
372 #undef CASE
373 #undef HASH
374 }
375 }
376
377 //===----------------------------------------------------------------------===//
378 // Stats Implementation
379 //===----------------------------------------------------------------------===//
380
381 /// PrintStats - Print statistics about how well the identifier table is doing
382 /// at hashing identifiers.
PrintStats() const383 void IdentifierTable::PrintStats() const {
384 unsigned NumBuckets = HashTable.getNumBuckets();
385 unsigned NumIdentifiers = HashTable.getNumItems();
386 unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
387 unsigned AverageIdentifierSize = 0;
388 unsigned MaxIdentifierLength = 0;
389
390 // TODO: Figure out maximum times an identifier had to probe for -stats.
391 for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
392 I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
393 unsigned IdLen = I->getKeyLength();
394 AverageIdentifierSize += IdLen;
395 if (MaxIdentifierLength < IdLen)
396 MaxIdentifierLength = IdLen;
397 }
398
399 fprintf(stderr, "\n*** Identifier Table Stats:\n");
400 fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
401 fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
402 fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
403 NumIdentifiers/(double)NumBuckets);
404 fprintf(stderr, "Ave identifier length: %f\n",
405 (AverageIdentifierSize/(double)NumIdentifiers));
406 fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
407
408 // Compute statistics about the memory allocated for identifiers.
409 HashTable.getAllocator().PrintStats();
410 }
411
412 //===----------------------------------------------------------------------===//
413 // SelectorTable Implementation
414 //===----------------------------------------------------------------------===//
415
getHashValue(clang::Selector S)416 unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
417 return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
418 }
419
420 namespace clang {
421
422 /// One of these variable length records is kept for each
423 /// selector containing more than one keyword. We use a folding set
424 /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
425 /// this class is provided strictly through Selector.
426 class alignas(IdentifierInfoAlignment) MultiKeywordSelector
427 : public detail::DeclarationNameExtra,
428 public llvm::FoldingSetNode {
MultiKeywordSelector(unsigned nKeys)429 MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
430
431 public:
432 // Constructor for keyword selectors.
MultiKeywordSelector(unsigned nKeys,IdentifierInfo ** IIV)433 MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
434 : DeclarationNameExtra(nKeys) {
435 assert((nKeys > 1) && "not a multi-keyword selector");
436
437 // Fill in the trailing keyword array.
438 IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1);
439 for (unsigned i = 0; i != nKeys; ++i)
440 KeyInfo[i] = IIV[i];
441 }
442
443 // getName - Derive the full selector name and return it.
444 std::string getName() const;
445
446 using DeclarationNameExtra::getNumArgs;
447
448 using keyword_iterator = IdentifierInfo *const *;
449
keyword_begin() const450 keyword_iterator keyword_begin() const {
451 return reinterpret_cast<keyword_iterator>(this + 1);
452 }
453
keyword_end() const454 keyword_iterator keyword_end() const {
455 return keyword_begin() + getNumArgs();
456 }
457
getIdentifierInfoForSlot(unsigned i) const458 IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
459 assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
460 return keyword_begin()[i];
461 }
462
Profile(llvm::FoldingSetNodeID & ID,keyword_iterator ArgTys,unsigned NumArgs)463 static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
464 unsigned NumArgs) {
465 ID.AddInteger(NumArgs);
466 for (unsigned i = 0; i != NumArgs; ++i)
467 ID.AddPointer(ArgTys[i]);
468 }
469
Profile(llvm::FoldingSetNodeID & ID)470 void Profile(llvm::FoldingSetNodeID &ID) {
471 Profile(ID, keyword_begin(), getNumArgs());
472 }
473 };
474
475 } // namespace clang.
476
isKeywordSelector(ArrayRef<StringRef> Names) const477 bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const {
478 assert(!Names.empty() && "must have >= 1 selector slots");
479 if (getNumArgs() != Names.size())
480 return false;
481 for (unsigned I = 0, E = Names.size(); I != E; ++I) {
482 if (getNameForSlot(I) != Names[I])
483 return false;
484 }
485 return true;
486 }
487
isUnarySelector(StringRef Name) const488 bool Selector::isUnarySelector(StringRef Name) const {
489 return isUnarySelector() && getNameForSlot(0) == Name;
490 }
491
getNumArgs() const492 unsigned Selector::getNumArgs() const {
493 unsigned IIF = getIdentifierInfoFlag();
494 if (IIF <= ZeroArg)
495 return 0;
496 if (IIF == OneArg)
497 return 1;
498 // We point to a MultiKeywordSelector.
499 MultiKeywordSelector *SI = getMultiKeywordSelector();
500 return SI->getNumArgs();
501 }
502
getIdentifierInfoForSlot(unsigned argIndex) const503 IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
504 if (getIdentifierInfoFlag() < MultiArg) {
505 assert(argIndex == 0 && "illegal keyword index");
506 return getAsIdentifierInfo();
507 }
508
509 // We point to a MultiKeywordSelector.
510 MultiKeywordSelector *SI = getMultiKeywordSelector();
511 return SI->getIdentifierInfoForSlot(argIndex);
512 }
513
getNameForSlot(unsigned int argIndex) const514 StringRef Selector::getNameForSlot(unsigned int argIndex) const {
515 IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
516 return II ? II->getName() : StringRef();
517 }
518
getName() const519 std::string MultiKeywordSelector::getName() const {
520 SmallString<256> Str;
521 llvm::raw_svector_ostream OS(Str);
522 for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
523 if (*I)
524 OS << (*I)->getName();
525 OS << ':';
526 }
527
528 return std::string(OS.str());
529 }
530
getAsString() const531 std::string Selector::getAsString() const {
532 if (InfoPtr == 0)
533 return "<null selector>";
534
535 if (getIdentifierInfoFlag() < MultiArg) {
536 IdentifierInfo *II = getAsIdentifierInfo();
537
538 if (getNumArgs() == 0) {
539 assert(II && "If the number of arguments is 0 then II is guaranteed to "
540 "not be null.");
541 return std::string(II->getName());
542 }
543
544 if (!II)
545 return ":";
546
547 return II->getName().str() + ":";
548 }
549
550 // We have a multiple keyword selector.
551 return getMultiKeywordSelector()->getName();
552 }
553
print(llvm::raw_ostream & OS) const554 void Selector::print(llvm::raw_ostream &OS) const {
555 OS << getAsString();
556 }
557
dump() const558 LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); }
559
560 /// Interpreting the given string using the normal CamelCase
561 /// conventions, determine whether the given string starts with the
562 /// given "word", which is assumed to end in a lowercase letter.
startsWithWord(StringRef name,StringRef word)563 static bool startsWithWord(StringRef name, StringRef word) {
564 if (name.size() < word.size()) return false;
565 return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
566 name.startswith(word));
567 }
568
getMethodFamilyImpl(Selector sel)569 ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
570 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
571 if (!first) return OMF_None;
572
573 StringRef name = first->getName();
574 if (sel.isUnarySelector()) {
575 if (name == "autorelease") return OMF_autorelease;
576 if (name == "dealloc") return OMF_dealloc;
577 if (name == "finalize") return OMF_finalize;
578 if (name == "release") return OMF_release;
579 if (name == "retain") return OMF_retain;
580 if (name == "retainCount") return OMF_retainCount;
581 if (name == "self") return OMF_self;
582 if (name == "initialize") return OMF_initialize;
583 }
584
585 if (name == "performSelector" || name == "performSelectorInBackground" ||
586 name == "performSelectorOnMainThread")
587 return OMF_performSelector;
588
589 // The other method families may begin with a prefix of underscores.
590 while (!name.empty() && name.front() == '_')
591 name = name.substr(1);
592
593 if (name.empty()) return OMF_None;
594 switch (name.front()) {
595 case 'a':
596 if (startsWithWord(name, "alloc")) return OMF_alloc;
597 break;
598 case 'c':
599 if (startsWithWord(name, "copy")) return OMF_copy;
600 break;
601 case 'i':
602 if (startsWithWord(name, "init")) return OMF_init;
603 break;
604 case 'm':
605 if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
606 break;
607 case 'n':
608 if (startsWithWord(name, "new")) return OMF_new;
609 break;
610 default:
611 break;
612 }
613
614 return OMF_None;
615 }
616
getInstTypeMethodFamily(Selector sel)617 ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
618 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
619 if (!first) return OIT_None;
620
621 StringRef name = first->getName();
622
623 if (name.empty()) return OIT_None;
624 switch (name.front()) {
625 case 'a':
626 if (startsWithWord(name, "array")) return OIT_Array;
627 break;
628 case 'd':
629 if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
630 if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
631 break;
632 case 's':
633 if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
634 if (startsWithWord(name, "standard")) return OIT_Singleton;
635 break;
636 case 'i':
637 if (startsWithWord(name, "init")) return OIT_Init;
638 break;
639 default:
640 break;
641 }
642 return OIT_None;
643 }
644
getStringFormatFamilyImpl(Selector sel)645 ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
646 IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
647 if (!first) return SFF_None;
648
649 StringRef name = first->getName();
650
651 switch (name.front()) {
652 case 'a':
653 if (name == "appendFormat") return SFF_NSString;
654 break;
655
656 case 'i':
657 if (name == "initWithFormat") return SFF_NSString;
658 break;
659
660 case 'l':
661 if (name == "localizedStringWithFormat") return SFF_NSString;
662 break;
663
664 case 's':
665 if (name == "stringByAppendingFormat" ||
666 name == "stringWithFormat") return SFF_NSString;
667 break;
668 }
669 return SFF_None;
670 }
671
672 namespace {
673
674 struct SelectorTableImpl {
675 llvm::FoldingSet<MultiKeywordSelector> Table;
676 llvm::BumpPtrAllocator Allocator;
677 };
678
679 } // namespace
680
getSelectorTableImpl(void * P)681 static SelectorTableImpl &getSelectorTableImpl(void *P) {
682 return *static_cast<SelectorTableImpl*>(P);
683 }
684
685 SmallString<64>
constructSetterName(StringRef Name)686 SelectorTable::constructSetterName(StringRef Name) {
687 SmallString<64> SetterName("set");
688 SetterName += Name;
689 SetterName[3] = toUppercase(SetterName[3]);
690 return SetterName;
691 }
692
693 Selector
constructSetterSelector(IdentifierTable & Idents,SelectorTable & SelTable,const IdentifierInfo * Name)694 SelectorTable::constructSetterSelector(IdentifierTable &Idents,
695 SelectorTable &SelTable,
696 const IdentifierInfo *Name) {
697 IdentifierInfo *SetterName =
698 &Idents.get(constructSetterName(Name->getName()));
699 return SelTable.getUnarySelector(SetterName);
700 }
701
getPropertyNameFromSetterSelector(Selector Sel)702 std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) {
703 StringRef Name = Sel.getNameForSlot(0);
704 assert(Name.startswith("set") && "invalid setter name");
705 return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str();
706 }
707
getTotalMemory() const708 size_t SelectorTable::getTotalMemory() const {
709 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
710 return SelTabImpl.Allocator.getTotalMemory();
711 }
712
getSelector(unsigned nKeys,IdentifierInfo ** IIV)713 Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
714 if (nKeys < 2)
715 return Selector(IIV[0], nKeys);
716
717 SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
718
719 // Unique selector, to guarantee there is one per name.
720 llvm::FoldingSetNodeID ID;
721 MultiKeywordSelector::Profile(ID, IIV, nKeys);
722
723 void *InsertPos = nullptr;
724 if (MultiKeywordSelector *SI =
725 SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
726 return Selector(SI);
727
728 // MultiKeywordSelector objects are not allocated with new because they have a
729 // variable size array (for parameter types) at the end of them.
730 unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
731 MultiKeywordSelector *SI =
732 (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
733 Size, alignof(MultiKeywordSelector));
734 new (SI) MultiKeywordSelector(nKeys, IIV);
735 SelTabImpl.Table.InsertNode(SI, InsertPos);
736 return Selector(SI);
737 }
738
SelectorTable()739 SelectorTable::SelectorTable() {
740 Impl = new SelectorTableImpl();
741 }
742
~SelectorTable()743 SelectorTable::~SelectorTable() {
744 delete &getSelectorTableImpl(Impl);
745 }
746
getOperatorSpelling(OverloadedOperatorKind Operator)747 const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
748 switch (Operator) {
749 case OO_None:
750 case NUM_OVERLOADED_OPERATORS:
751 return nullptr;
752
753 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
754 case OO_##Name: return Spelling;
755 #include "clang/Basic/OperatorKinds.def"
756 }
757
758 llvm_unreachable("Invalid OverloadedOperatorKind!");
759 }
760
getNullabilitySpelling(NullabilityKind kind,bool isContextSensitive)761 StringRef clang::getNullabilitySpelling(NullabilityKind kind,
762 bool isContextSensitive) {
763 switch (kind) {
764 case NullabilityKind::NonNull:
765 return isContextSensitive ? "nonnull" : "_Nonnull";
766
767 case NullabilityKind::Nullable:
768 return isContextSensitive ? "nullable" : "_Nullable";
769
770 case NullabilityKind::NullableResult:
771 assert(!isContextSensitive &&
772 "_Nullable_result isn't supported as context-sensitive keyword");
773 return "_Nullable_result";
774
775 case NullabilityKind::Unspecified:
776 return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
777 }
778 llvm_unreachable("Unknown nullability kind.");
779 }
780