IdentifierTable.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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. #include "clang/Basic/IdentifierTable.h"
  14. #include "clang/Basic/CharInfo.h"
  15. #include "clang/Basic/LangOptions.h"
  16. #include "clang/Basic/OperatorKinds.h"
  17. #include "clang/Basic/Specifiers.h"
  18. #include "clang/Basic/TokenKinds.h"
  19. #include "llvm/ADT/DenseMapInfo.h"
  20. #include "llvm/ADT/FoldingSet.h"
  21. #include "llvm/ADT/SmallString.h"
  22. #include "llvm/ADT/StringMap.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/Support/Allocator.h"
  25. #include "llvm/Support/ErrorHandling.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include <cassert>
  28. #include <cstdio>
  29. #include <cstring>
  30. #include <string>
  31. using namespace clang;
  32. //===----------------------------------------------------------------------===//
  33. // IdentifierTable Implementation
  34. //===----------------------------------------------------------------------===//
  35. IdentifierIterator::~IdentifierIterator() = default;
  36. IdentifierInfoLookup::~IdentifierInfoLookup() = default;
  37. namespace {
  38. /// A simple identifier lookup iterator that represents an
  39. /// empty sequence of identifiers.
  40. class EmptyLookupIterator : public IdentifierIterator
  41. {
  42. public:
  43. StringRef Next() override { return StringRef(); }
  44. };
  45. } // namespace
  46. IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
  47. return new EmptyLookupIterator();
  48. }
  49. IdentifierTable::IdentifierTable(IdentifierInfoLookup *ExternalLookup)
  50. : HashTable(8192), // Start with space for 8K identifiers.
  51. ExternalLookup(ExternalLookup) {}
  52. IdentifierTable::IdentifierTable(const LangOptions &LangOpts,
  53. IdentifierInfoLookup *ExternalLookup)
  54. : IdentifierTable(ExternalLookup) {
  55. // Populate the identifier table with info about keywords for the current
  56. // language.
  57. AddKeywords(LangOpts);
  58. }
  59. //===----------------------------------------------------------------------===//
  60. // Language Keyword Implementation
  61. //===----------------------------------------------------------------------===//
  62. // Constants for TokenKinds.def
  63. namespace {
  64. enum {
  65. KEYC99 = 0x1,
  66. KEYCXX = 0x2,
  67. KEYCXX11 = 0x4,
  68. KEYGNU = 0x8,
  69. KEYMS = 0x10,
  70. BOOLSUPPORT = 0x20,
  71. KEYALTIVEC = 0x40,
  72. KEYNOCXX = 0x80,
  73. KEYBORLAND = 0x100,
  74. KEYOPENCLC = 0x200,
  75. KEYC11 = 0x400,
  76. KEYNOMS18 = 0x800,
  77. KEYNOOPENCL = 0x1000,
  78. WCHARSUPPORT = 0x2000,
  79. HALFSUPPORT = 0x4000,
  80. CHAR8SUPPORT = 0x8000,
  81. KEYCONCEPTS = 0x10000,
  82. KEYOBJC = 0x20000,
  83. KEYZVECTOR = 0x40000,
  84. KEYCOROUTINES = 0x80000,
  85. KEYMODULES = 0x100000,
  86. KEYCXX2A = 0x200000,
  87. KEYOPENCLCXX = 0x400000,
  88. KEYMSCOMPAT = 0x800000,
  89. KEYALLCXX = KEYCXX | KEYCXX11 | KEYCXX2A,
  90. KEYALL = (0xffffff & ~KEYNOMS18 &
  91. ~KEYNOOPENCL) // KEYNOMS18 and KEYNOOPENCL are used to exclude.
  92. };
  93. /// How a keyword is treated in the selected standard.
  94. enum KeywordStatus {
  95. KS_Disabled, // Disabled
  96. KS_Extension, // Is an extension
  97. KS_Enabled, // Enabled
  98. KS_Future // Is a keyword in future standard
  99. };
  100. } // namespace
  101. /// Translates flags as specified in TokenKinds.def into keyword status
  102. /// in the given language standard.
  103. static KeywordStatus getKeywordStatus(const LangOptions &LangOpts,
  104. unsigned Flags) {
  105. if (Flags == KEYALL) return KS_Enabled;
  106. if (LangOpts.CPlusPlus && (Flags & KEYCXX)) return KS_Enabled;
  107. if (LangOpts.CPlusPlus11 && (Flags & KEYCXX11)) return KS_Enabled;
  108. if (LangOpts.CPlusPlus2a && (Flags & KEYCXX2A)) return KS_Enabled;
  109. if (LangOpts.C99 && (Flags & KEYC99)) return KS_Enabled;
  110. if (LangOpts.GNUKeywords && (Flags & KEYGNU)) return KS_Extension;
  111. if (LangOpts.MicrosoftExt && (Flags & KEYMS)) return KS_Extension;
  112. if (LangOpts.MSVCCompat && (Flags & KEYMSCOMPAT)) return KS_Enabled;
  113. if (LangOpts.Borland && (Flags & KEYBORLAND)) return KS_Extension;
  114. if (LangOpts.Bool && (Flags & BOOLSUPPORT)) return KS_Enabled;
  115. if (LangOpts.Half && (Flags & HALFSUPPORT)) return KS_Enabled;
  116. if (LangOpts.WChar && (Flags & WCHARSUPPORT)) return KS_Enabled;
  117. if (LangOpts.Char8 && (Flags & CHAR8SUPPORT)) return KS_Enabled;
  118. if (LangOpts.AltiVec && (Flags & KEYALTIVEC)) return KS_Enabled;
  119. if (LangOpts.ZVector && (Flags & KEYZVECTOR)) return KS_Enabled;
  120. if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLC))
  121. return KS_Enabled;
  122. if (LangOpts.OpenCLCPlusPlus && (Flags & KEYOPENCLCXX)) return KS_Enabled;
  123. if (!LangOpts.CPlusPlus && (Flags & KEYNOCXX)) return KS_Enabled;
  124. if (LangOpts.C11 && (Flags & KEYC11)) return KS_Enabled;
  125. // We treat bridge casts as objective-C keywords so we can warn on them
  126. // in non-arc mode.
  127. if (LangOpts.ObjC && (Flags & KEYOBJC)) return KS_Enabled;
  128. if (LangOpts.ConceptsTS && (Flags & KEYCONCEPTS)) return KS_Enabled;
  129. if (LangOpts.Coroutines && (Flags & KEYCOROUTINES)) return KS_Enabled;
  130. if (LangOpts.ModulesTS && (Flags & KEYMODULES)) return KS_Enabled;
  131. if (LangOpts.CPlusPlus && (Flags & KEYALLCXX)) return KS_Future;
  132. return KS_Disabled;
  133. }
  134. /// AddKeyword - This method is used to associate a token ID with specific
  135. /// identifiers because they are language keywords. This causes the lexer to
  136. /// automatically map matching identifiers to specialized token codes.
  137. static void AddKeyword(StringRef Keyword,
  138. tok::TokenKind TokenCode, unsigned Flags,
  139. const LangOptions &LangOpts, IdentifierTable &Table) {
  140. KeywordStatus AddResult = getKeywordStatus(LangOpts, Flags);
  141. // Don't add this keyword under MSVCCompat.
  142. if (LangOpts.MSVCCompat && (Flags & KEYNOMS18) &&
  143. !LangOpts.isCompatibleWithMSVC(LangOptions::MSVC2015))
  144. return;
  145. // Don't add this keyword under OpenCL.
  146. if (LangOpts.OpenCL && (Flags & KEYNOOPENCL))
  147. return;
  148. // Don't add this keyword if disabled in this language.
  149. if (AddResult == KS_Disabled) return;
  150. IdentifierInfo &Info =
  151. Table.get(Keyword, AddResult == KS_Future ? tok::identifier : TokenCode);
  152. Info.setIsExtensionToken(AddResult == KS_Extension);
  153. Info.setIsFutureCompatKeyword(AddResult == KS_Future);
  154. }
  155. /// AddCXXOperatorKeyword - Register a C++ operator keyword alternative
  156. /// representations.
  157. static void AddCXXOperatorKeyword(StringRef Keyword,
  158. tok::TokenKind TokenCode,
  159. IdentifierTable &Table) {
  160. IdentifierInfo &Info = Table.get(Keyword, TokenCode);
  161. Info.setIsCPlusPlusOperatorKeyword();
  162. }
  163. /// AddObjCKeyword - Register an Objective-C \@keyword like "class" "selector"
  164. /// or "property".
  165. static void AddObjCKeyword(StringRef Name,
  166. tok::ObjCKeywordKind ObjCID,
  167. IdentifierTable &Table) {
  168. Table.get(Name).setObjCKeywordID(ObjCID);
  169. }
  170. /// AddKeywords - Add all keywords to the symbol table.
  171. ///
  172. void IdentifierTable::AddKeywords(const LangOptions &LangOpts) {
  173. // Add keywords and tokens for the current language.
  174. #define KEYWORD(NAME, FLAGS) \
  175. AddKeyword(StringRef(#NAME), tok::kw_ ## NAME, \
  176. FLAGS, LangOpts, *this);
  177. #define ALIAS(NAME, TOK, FLAGS) \
  178. AddKeyword(StringRef(NAME), tok::kw_ ## TOK, \
  179. FLAGS, LangOpts, *this);
  180. #define CXX_KEYWORD_OPERATOR(NAME, ALIAS) \
  181. if (LangOpts.CXXOperatorNames) \
  182. AddCXXOperatorKeyword(StringRef(#NAME), tok::ALIAS, *this);
  183. #define OBJC_AT_KEYWORD(NAME) \
  184. if (LangOpts.ObjC) \
  185. AddObjCKeyword(StringRef(#NAME), tok::objc_##NAME, *this);
  186. #define TESTING_KEYWORD(NAME, FLAGS)
  187. #include "clang/Basic/TokenKinds.def"
  188. if (LangOpts.ParseUnknownAnytype)
  189. AddKeyword("__unknown_anytype", tok::kw___unknown_anytype, KEYALL,
  190. LangOpts, *this);
  191. if (LangOpts.DeclSpecKeyword)
  192. AddKeyword("__declspec", tok::kw___declspec, KEYALL, LangOpts, *this);
  193. // Add the 'import' contextual keyword.
  194. get("import").setModulesImport(true);
  195. }
  196. /// Checks if the specified token kind represents a keyword in the
  197. /// specified language.
  198. /// \returns Status of the keyword in the language.
  199. static KeywordStatus getTokenKwStatus(const LangOptions &LangOpts,
  200. tok::TokenKind K) {
  201. switch (K) {
  202. #define KEYWORD(NAME, FLAGS) \
  203. case tok::kw_##NAME: return getKeywordStatus(LangOpts, FLAGS);
  204. #include "clang/Basic/TokenKinds.def"
  205. default: return KS_Disabled;
  206. }
  207. }
  208. /// Returns true if the identifier represents a keyword in the
  209. /// specified language.
  210. bool IdentifierInfo::isKeyword(const LangOptions &LangOpts) const {
  211. switch (getTokenKwStatus(LangOpts, getTokenID())) {
  212. case KS_Enabled:
  213. case KS_Extension:
  214. return true;
  215. default:
  216. return false;
  217. }
  218. }
  219. /// Returns true if the identifier represents a C++ keyword in the
  220. /// specified language.
  221. bool IdentifierInfo::isCPlusPlusKeyword(const LangOptions &LangOpts) const {
  222. if (!LangOpts.CPlusPlus || !isKeyword(LangOpts))
  223. return false;
  224. // This is a C++ keyword if this identifier is not a keyword when checked
  225. // using LangOptions without C++ support.
  226. LangOptions LangOptsNoCPP = LangOpts;
  227. LangOptsNoCPP.CPlusPlus = false;
  228. LangOptsNoCPP.CPlusPlus11 = false;
  229. LangOptsNoCPP.CPlusPlus2a = false;
  230. return !isKeyword(LangOptsNoCPP);
  231. }
  232. tok::PPKeywordKind IdentifierInfo::getPPKeywordID() const {
  233. // We use a perfect hash function here involving the length of the keyword,
  234. // the first and third character. For preprocessor ID's there are no
  235. // collisions (if there were, the switch below would complain about duplicate
  236. // case values). Note that this depends on 'if' being null terminated.
  237. #define HASH(LEN, FIRST, THIRD) \
  238. (LEN << 5) + (((FIRST-'a') + (THIRD-'a')) & 31)
  239. #define CASE(LEN, FIRST, THIRD, NAME) \
  240. case HASH(LEN, FIRST, THIRD): \
  241. return memcmp(Name, #NAME, LEN) ? tok::pp_not_keyword : tok::pp_ ## NAME
  242. unsigned Len = getLength();
  243. if (Len < 2) return tok::pp_not_keyword;
  244. const char *Name = getNameStart();
  245. switch (HASH(Len, Name[0], Name[2])) {
  246. default: return tok::pp_not_keyword;
  247. CASE( 2, 'i', '\0', if);
  248. CASE( 4, 'e', 'i', elif);
  249. CASE( 4, 'e', 's', else);
  250. CASE( 4, 'l', 'n', line);
  251. CASE( 4, 's', 'c', sccs);
  252. CASE( 5, 'e', 'd', endif);
  253. CASE( 5, 'e', 'r', error);
  254. CASE( 5, 'i', 'e', ident);
  255. CASE( 5, 'i', 'd', ifdef);
  256. CASE( 5, 'u', 'd', undef);
  257. CASE( 6, 'a', 's', assert);
  258. CASE( 6, 'd', 'f', define);
  259. CASE( 6, 'i', 'n', ifndef);
  260. CASE( 6, 'i', 'p', import);
  261. CASE( 6, 'p', 'a', pragma);
  262. CASE( 7, 'd', 'f', defined);
  263. CASE( 7, 'i', 'c', include);
  264. CASE( 7, 'w', 'r', warning);
  265. CASE( 8, 'u', 'a', unassert);
  266. CASE(12, 'i', 'c', include_next);
  267. CASE(14, '_', 'p', __public_macro);
  268. CASE(15, '_', 'p', __private_macro);
  269. CASE(16, '_', 'i', __include_macros);
  270. #undef CASE
  271. #undef HASH
  272. }
  273. }
  274. //===----------------------------------------------------------------------===//
  275. // Stats Implementation
  276. //===----------------------------------------------------------------------===//
  277. /// PrintStats - Print statistics about how well the identifier table is doing
  278. /// at hashing identifiers.
  279. void IdentifierTable::PrintStats() const {
  280. unsigned NumBuckets = HashTable.getNumBuckets();
  281. unsigned NumIdentifiers = HashTable.getNumItems();
  282. unsigned NumEmptyBuckets = NumBuckets-NumIdentifiers;
  283. unsigned AverageIdentifierSize = 0;
  284. unsigned MaxIdentifierLength = 0;
  285. // TODO: Figure out maximum times an identifier had to probe for -stats.
  286. for (llvm::StringMap<IdentifierInfo*, llvm::BumpPtrAllocator>::const_iterator
  287. I = HashTable.begin(), E = HashTable.end(); I != E; ++I) {
  288. unsigned IdLen = I->getKeyLength();
  289. AverageIdentifierSize += IdLen;
  290. if (MaxIdentifierLength < IdLen)
  291. MaxIdentifierLength = IdLen;
  292. }
  293. fprintf(stderr, "\n*** Identifier Table Stats:\n");
  294. fprintf(stderr, "# Identifiers: %d\n", NumIdentifiers);
  295. fprintf(stderr, "# Empty Buckets: %d\n", NumEmptyBuckets);
  296. fprintf(stderr, "Hash density (#identifiers per bucket): %f\n",
  297. NumIdentifiers/(double)NumBuckets);
  298. fprintf(stderr, "Ave identifier length: %f\n",
  299. (AverageIdentifierSize/(double)NumIdentifiers));
  300. fprintf(stderr, "Max identifier length: %d\n", MaxIdentifierLength);
  301. // Compute statistics about the memory allocated for identifiers.
  302. HashTable.getAllocator().PrintStats();
  303. }
  304. //===----------------------------------------------------------------------===//
  305. // SelectorTable Implementation
  306. //===----------------------------------------------------------------------===//
  307. unsigned llvm::DenseMapInfo<clang::Selector>::getHashValue(clang::Selector S) {
  308. return DenseMapInfo<void*>::getHashValue(S.getAsOpaquePtr());
  309. }
  310. namespace clang {
  311. /// One of these variable length records is kept for each
  312. /// selector containing more than one keyword. We use a folding set
  313. /// to unique aggregate names (keyword selectors in ObjC parlance). Access to
  314. /// this class is provided strictly through Selector.
  315. class alignas(IdentifierInfoAlignment) MultiKeywordSelector
  316. : public detail::DeclarationNameExtra,
  317. public llvm::FoldingSetNode {
  318. MultiKeywordSelector(unsigned nKeys) : DeclarationNameExtra(nKeys) {}
  319. public:
  320. // Constructor for keyword selectors.
  321. MultiKeywordSelector(unsigned nKeys, IdentifierInfo **IIV)
  322. : DeclarationNameExtra(nKeys) {
  323. assert((nKeys > 1) && "not a multi-keyword selector");
  324. // Fill in the trailing keyword array.
  325. IdentifierInfo **KeyInfo = reinterpret_cast<IdentifierInfo **>(this + 1);
  326. for (unsigned i = 0; i != nKeys; ++i)
  327. KeyInfo[i] = IIV[i];
  328. }
  329. // getName - Derive the full selector name and return it.
  330. std::string getName() const;
  331. using DeclarationNameExtra::getNumArgs;
  332. using keyword_iterator = IdentifierInfo *const *;
  333. keyword_iterator keyword_begin() const {
  334. return reinterpret_cast<keyword_iterator>(this + 1);
  335. }
  336. keyword_iterator keyword_end() const {
  337. return keyword_begin() + getNumArgs();
  338. }
  339. IdentifierInfo *getIdentifierInfoForSlot(unsigned i) const {
  340. assert(i < getNumArgs() && "getIdentifierInfoForSlot(): illegal index");
  341. return keyword_begin()[i];
  342. }
  343. static void Profile(llvm::FoldingSetNodeID &ID, keyword_iterator ArgTys,
  344. unsigned NumArgs) {
  345. ID.AddInteger(NumArgs);
  346. for (unsigned i = 0; i != NumArgs; ++i)
  347. ID.AddPointer(ArgTys[i]);
  348. }
  349. void Profile(llvm::FoldingSetNodeID &ID) {
  350. Profile(ID, keyword_begin(), getNumArgs());
  351. }
  352. };
  353. } // namespace clang.
  354. bool Selector::isKeywordSelector(ArrayRef<StringRef> Names) const {
  355. assert(!Names.empty() && "must have >= 1 selector slots");
  356. if (getNumArgs() != Names.size())
  357. return false;
  358. for (unsigned I = 0, E = Names.size(); I != E; ++I) {
  359. if (getNameForSlot(I) != Names[I])
  360. return false;
  361. }
  362. return true;
  363. }
  364. bool Selector::isUnarySelector(StringRef Name) const {
  365. return isUnarySelector() && getNameForSlot(0) == Name;
  366. }
  367. unsigned Selector::getNumArgs() const {
  368. unsigned IIF = getIdentifierInfoFlag();
  369. if (IIF <= ZeroArg)
  370. return 0;
  371. if (IIF == OneArg)
  372. return 1;
  373. // We point to a MultiKeywordSelector.
  374. MultiKeywordSelector *SI = getMultiKeywordSelector();
  375. return SI->getNumArgs();
  376. }
  377. IdentifierInfo *Selector::getIdentifierInfoForSlot(unsigned argIndex) const {
  378. if (getIdentifierInfoFlag() < MultiArg) {
  379. assert(argIndex == 0 && "illegal keyword index");
  380. return getAsIdentifierInfo();
  381. }
  382. // We point to a MultiKeywordSelector.
  383. MultiKeywordSelector *SI = getMultiKeywordSelector();
  384. return SI->getIdentifierInfoForSlot(argIndex);
  385. }
  386. StringRef Selector::getNameForSlot(unsigned int argIndex) const {
  387. IdentifierInfo *II = getIdentifierInfoForSlot(argIndex);
  388. return II ? II->getName() : StringRef();
  389. }
  390. std::string MultiKeywordSelector::getName() const {
  391. SmallString<256> Str;
  392. llvm::raw_svector_ostream OS(Str);
  393. for (keyword_iterator I = keyword_begin(), E = keyword_end(); I != E; ++I) {
  394. if (*I)
  395. OS << (*I)->getName();
  396. OS << ':';
  397. }
  398. return OS.str();
  399. }
  400. std::string Selector::getAsString() const {
  401. if (InfoPtr == 0)
  402. return "<null selector>";
  403. if (getIdentifierInfoFlag() < MultiArg) {
  404. IdentifierInfo *II = getAsIdentifierInfo();
  405. if (getNumArgs() == 0) {
  406. assert(II && "If the number of arguments is 0 then II is guaranteed to "
  407. "not be null.");
  408. return II->getName();
  409. }
  410. if (!II)
  411. return ":";
  412. return II->getName().str() + ":";
  413. }
  414. // We have a multiple keyword selector.
  415. return getMultiKeywordSelector()->getName();
  416. }
  417. void Selector::print(llvm::raw_ostream &OS) const {
  418. OS << getAsString();
  419. }
  420. LLVM_DUMP_METHOD void Selector::dump() const { print(llvm::errs()); }
  421. /// Interpreting the given string using the normal CamelCase
  422. /// conventions, determine whether the given string starts with the
  423. /// given "word", which is assumed to end in a lowercase letter.
  424. static bool startsWithWord(StringRef name, StringRef word) {
  425. if (name.size() < word.size()) return false;
  426. return ((name.size() == word.size() || !isLowercase(name[word.size()])) &&
  427. name.startswith(word));
  428. }
  429. ObjCMethodFamily Selector::getMethodFamilyImpl(Selector sel) {
  430. IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  431. if (!first) return OMF_None;
  432. StringRef name = first->getName();
  433. if (sel.isUnarySelector()) {
  434. if (name == "autorelease") return OMF_autorelease;
  435. if (name == "dealloc") return OMF_dealloc;
  436. if (name == "finalize") return OMF_finalize;
  437. if (name == "release") return OMF_release;
  438. if (name == "retain") return OMF_retain;
  439. if (name == "retainCount") return OMF_retainCount;
  440. if (name == "self") return OMF_self;
  441. if (name == "initialize") return OMF_initialize;
  442. }
  443. if (name == "performSelector" || name == "performSelectorInBackground" ||
  444. name == "performSelectorOnMainThread")
  445. return OMF_performSelector;
  446. // The other method families may begin with a prefix of underscores.
  447. while (!name.empty() && name.front() == '_')
  448. name = name.substr(1);
  449. if (name.empty()) return OMF_None;
  450. switch (name.front()) {
  451. case 'a':
  452. if (startsWithWord(name, "alloc")) return OMF_alloc;
  453. break;
  454. case 'c':
  455. if (startsWithWord(name, "copy")) return OMF_copy;
  456. break;
  457. case 'i':
  458. if (startsWithWord(name, "init")) return OMF_init;
  459. break;
  460. case 'm':
  461. if (startsWithWord(name, "mutableCopy")) return OMF_mutableCopy;
  462. break;
  463. case 'n':
  464. if (startsWithWord(name, "new")) return OMF_new;
  465. break;
  466. default:
  467. break;
  468. }
  469. return OMF_None;
  470. }
  471. ObjCInstanceTypeFamily Selector::getInstTypeMethodFamily(Selector sel) {
  472. IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  473. if (!first) return OIT_None;
  474. StringRef name = first->getName();
  475. if (name.empty()) return OIT_None;
  476. switch (name.front()) {
  477. case 'a':
  478. if (startsWithWord(name, "array")) return OIT_Array;
  479. break;
  480. case 'd':
  481. if (startsWithWord(name, "default")) return OIT_ReturnsSelf;
  482. if (startsWithWord(name, "dictionary")) return OIT_Dictionary;
  483. break;
  484. case 's':
  485. if (startsWithWord(name, "shared")) return OIT_ReturnsSelf;
  486. if (startsWithWord(name, "standard")) return OIT_Singleton;
  487. break;
  488. case 'i':
  489. if (startsWithWord(name, "init")) return OIT_Init;
  490. break;
  491. default:
  492. break;
  493. }
  494. return OIT_None;
  495. }
  496. ObjCStringFormatFamily Selector::getStringFormatFamilyImpl(Selector sel) {
  497. IdentifierInfo *first = sel.getIdentifierInfoForSlot(0);
  498. if (!first) return SFF_None;
  499. StringRef name = first->getName();
  500. switch (name.front()) {
  501. case 'a':
  502. if (name == "appendFormat") return SFF_NSString;
  503. break;
  504. case 'i':
  505. if (name == "initWithFormat") return SFF_NSString;
  506. break;
  507. case 'l':
  508. if (name == "localizedStringWithFormat") return SFF_NSString;
  509. break;
  510. case 's':
  511. if (name == "stringByAppendingFormat" ||
  512. name == "stringWithFormat") return SFF_NSString;
  513. break;
  514. }
  515. return SFF_None;
  516. }
  517. namespace {
  518. struct SelectorTableImpl {
  519. llvm::FoldingSet<MultiKeywordSelector> Table;
  520. llvm::BumpPtrAllocator Allocator;
  521. };
  522. } // namespace
  523. static SelectorTableImpl &getSelectorTableImpl(void *P) {
  524. return *static_cast<SelectorTableImpl*>(P);
  525. }
  526. SmallString<64>
  527. SelectorTable::constructSetterName(StringRef Name) {
  528. SmallString<64> SetterName("set");
  529. SetterName += Name;
  530. SetterName[3] = toUppercase(SetterName[3]);
  531. return SetterName;
  532. }
  533. Selector
  534. SelectorTable::constructSetterSelector(IdentifierTable &Idents,
  535. SelectorTable &SelTable,
  536. const IdentifierInfo *Name) {
  537. IdentifierInfo *SetterName =
  538. &Idents.get(constructSetterName(Name->getName()));
  539. return SelTable.getUnarySelector(SetterName);
  540. }
  541. std::string SelectorTable::getPropertyNameFromSetterSelector(Selector Sel) {
  542. StringRef Name = Sel.getNameForSlot(0);
  543. assert(Name.startswith("set") && "invalid setter name");
  544. return (Twine(toLowercase(Name[3])) + Name.drop_front(4)).str();
  545. }
  546. size_t SelectorTable::getTotalMemory() const {
  547. SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
  548. return SelTabImpl.Allocator.getTotalMemory();
  549. }
  550. Selector SelectorTable::getSelector(unsigned nKeys, IdentifierInfo **IIV) {
  551. if (nKeys < 2)
  552. return Selector(IIV[0], nKeys);
  553. SelectorTableImpl &SelTabImpl = getSelectorTableImpl(Impl);
  554. // Unique selector, to guarantee there is one per name.
  555. llvm::FoldingSetNodeID ID;
  556. MultiKeywordSelector::Profile(ID, IIV, nKeys);
  557. void *InsertPos = nullptr;
  558. if (MultiKeywordSelector *SI =
  559. SelTabImpl.Table.FindNodeOrInsertPos(ID, InsertPos))
  560. return Selector(SI);
  561. // MultiKeywordSelector objects are not allocated with new because they have a
  562. // variable size array (for parameter types) at the end of them.
  563. unsigned Size = sizeof(MultiKeywordSelector) + nKeys*sizeof(IdentifierInfo *);
  564. MultiKeywordSelector *SI =
  565. (MultiKeywordSelector *)SelTabImpl.Allocator.Allocate(
  566. Size, alignof(MultiKeywordSelector));
  567. new (SI) MultiKeywordSelector(nKeys, IIV);
  568. SelTabImpl.Table.InsertNode(SI, InsertPos);
  569. return Selector(SI);
  570. }
  571. SelectorTable::SelectorTable() {
  572. Impl = new SelectorTableImpl();
  573. }
  574. SelectorTable::~SelectorTable() {
  575. delete &getSelectorTableImpl(Impl);
  576. }
  577. const char *clang::getOperatorSpelling(OverloadedOperatorKind Operator) {
  578. switch (Operator) {
  579. case OO_None:
  580. case NUM_OVERLOADED_OPERATORS:
  581. return nullptr;
  582. #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
  583. case OO_##Name: return Spelling;
  584. #include "clang/Basic/OperatorKinds.def"
  585. }
  586. llvm_unreachable("Invalid OverloadedOperatorKind!");
  587. }
  588. StringRef clang::getNullabilitySpelling(NullabilityKind kind,
  589. bool isContextSensitive) {
  590. switch (kind) {
  591. case NullabilityKind::NonNull:
  592. return isContextSensitive ? "nonnull" : "_Nonnull";
  593. case NullabilityKind::Nullable:
  594. return isContextSensitive ? "nullable" : "_Nullable";
  595. case NullabilityKind::Unspecified:
  596. return isContextSensitive ? "null_unspecified" : "_Null_unspecified";
  597. }
  598. llvm_unreachable("Unknown nullability kind.");
  599. }