llvmorg-github-actions[bot] wrote:

<!--LLVM PR SUMMARY COMMENT-->
@llvm/pr-subscribers-lldb

@llvm/pr-subscribers-clang-modules

Author: Jan Svoboda (jansvoboda11)

<details>
<summary>Changes</summary>

Every compilation used to create an identifier for each builtin of its target 
and language upfront, in `Builtin::Context::initializeBuiltins()`. That's 
~12,000 identifiers for AArch64 (mostly NEON, SVE and SME) and ~3,400 for 
x86-64, for every `CompilerInstance`, including every implicit module build, 
while a translation unit typically uses a few dozen of them.

Now the `IdentifierTable` assigns the builtin ID when it creates an identifier: 
it asks `Builtin::Context::lookupBuiltinID()` whether the name is a builtin 
that its `LangOptions` support. So the `LangOptions` must not change after 
`Preprocessor::Initialize()`. An empty AArch64 C file now creates 874 
identifiers instead of 12,896.

To answer that quickly, the new `Builtin::TargetBuiltins` holds the builtin 
shards of a target and an optional aux target together with a hash table from 
builtin name to ID. It doesn't depend on the `LangOptions`: whether a builtin 
is supported, which of several builtins with the same name wins, and 
-fno-builtin-* are checked at lookup time, which only matters for the few names 
that are builtins. That makes `TargetBuiltins` immutable and shareable by any 
compilation for the same targets. Building it takes ~0.3 ms and 256 KB for 
AArch64; a lookup adds ~13 ns to the creation of a new identifier.

`Builtin::Context` no longer has a two-step setup: it's constructed from the 
targets (or from existing `TargetBuiltins`), and `InitializeTarget()` is gone, 
which breaks out-of-tree callers of it.
`Preprocessor::Initialize()` creates it and installs the lookup in its 
identifier table before any AST file is read, which covers every path, 
including PCH consumers and preprocessors created outside of `FrontendAction`. 
`CompilerInstance` passes its `TargetBuiltins` to the module builds it 
requests, so a compilation builds them once however many modules it builds. The 
existing calls to `initializeBuiltins()` keep working but are now redundant.

Other changes in behavior:
- Typo correction used to find builtins by iterating the identifier table; it 
now also enumerates the supported builtin names.
- Builtin IDs come from the importing compilation's target and language 
options, for PCHs as for modules. `ASTReader` no longer restores them from a 
PCH, which now only contains the builtins it used.
- The `IdentifierTable` starts with space for 2K identifiers instead of 8K, 
saving 144 KB per compilation.

A throwaway check comparing the old and new builtin IDs name by name across 29 
targets, 7 aux-target choices and 9 language/flag configurations found no 
difference; `BuiltinsConsistencyTest` checks a subset of these.

clang-scan-deps on the macOS SDK (400 translation units, 2,960 modules, -j 14), 
mean difference with 95% CI:
- clean scan: -10.9% +- 1.7% time, -11.4% +- 0.5% CPU
- incremental scan: -2.7% +- 6.0% time (n.s.), -13 MB +- 3 peak footprint

Alternatives considered:
- Generating the name index at Clang's build time: many shards come from `.def` 
files or from `NeonEmitter`/`SveEmitter`, and the index for a combination of 
target and aux target would still have to be merged at run time.
- Applying the `LangOptions` when building the index: lookups wouldn't get 
measurably faster, and the index couldn't be shared between compilations with 
different `LangOptions`.
- A process-wide cache of `TargetBuiltins` in `clang/Basic`: it needs global 
state and a lock in a library whose clients mostly don't run compilations 
concurrently. For now only the module builds of one compilation share them; 
sharing them between compilations is left for later.

---

Patch is 53.57 KiB, truncated to 20.00 KiB below, full version: 
https://github.com/llvm/llvm-project/pull/243274.diff


20 Files Affected:

- (modified) clang/include/clang/Basic/Builtins.h (+84-16) 
- (modified) clang/include/clang/Basic/IdentifierTable.h (+25) 
- (modified) clang/include/clang/Frontend/CompilerInstance.h (+8) 
- (modified) clang/include/clang/Lex/Preprocessor.h (+8-3) 
- (modified) clang/lib/Basic/Builtins.cpp (+145-81) 
- (modified) clang/lib/Basic/IdentifierTable.cpp (+10-1) 
- (modified) clang/lib/Frontend/ChainedIncludesSource.cpp (+1-5) 
- (modified) clang/lib/Frontend/CompilerInstance.cpp (+9-1) 
- (modified) clang/lib/Frontend/FrontendAction.cpp (+3-21) 
- (modified) clang/lib/Lex/Preprocessor.cpp (+35-4) 
- (modified) clang/lib/Sema/SemaLookup.cpp (+3) 
- (modified) clang/lib/Serialization/ASTReader.cpp (+15-3) 
- (modified) clang/lib/Serialization/ASTWriter.cpp (+3) 
- (added) clang/test/Modules/builtins-unused-in-module.c (+29) 
- (added) clang/test/PCH/builtins-no-builtin-flags.c (+46) 
- (added) clang/test/PCH/builtins-unused-in-pch.c (+45) 
- (added) clang/test/Preprocessor/builtins-not-in-identifier-table.c (+11) 
- (added) clang/unittests/Basic/BuiltinsTest.cpp (+344) 
- (modified) clang/unittests/Basic/CMakeLists.txt (+1) 
- (modified) 
lldb/source/Plugins/ExpressionParser/Clang/ClangExpressionParser.cpp (-5) 


``````````diff
diff --git a/clang/include/clang/Basic/Builtins.h 
b/clang/include/clang/Basic/Builtins.h
index 0420b5547a5682..08b0c4d1ae6cfa 100644
--- a/clang/include/clang/Basic/Builtins.h
+++ b/clang/include/clang/Basic/Builtins.h
@@ -16,12 +16,14 @@
 #define LLVM_CLANG_BASIC_BUILTINS_H
 
 #include "llvm/ADT/ArrayRef.h"
+#include "llvm/ADT/STLFunctionalExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringMap.h"
 #include "llvm/ADT/StringRef.h"
 #include "llvm/ADT/StringTable.h"
 #include "llvm/TargetParser/Triple.h"
 #include <cstring>
+#include <memory>
 
 // VC++ defines 'alloca' as an object-like macro, which interferes with our
 // builtins.
@@ -29,7 +31,6 @@
 
 namespace clang {
 class TargetInfo;
-class IdentifierTable;
 class LangOptions;
 
 enum LanguageID : uint16_t {
@@ -229,32 +230,99 @@ struct InfosShard {
       CLANG_TARGET_BUILTIN_DETAIL_STR_OFFSETS(ID, TYPE, ATTRS, FEATURE),       
\
       HeaderDesc::HEADER, LANG},
 
+/// The builtins of a target and an optional aux target: their shards, and a
+/// hash table from their names to their builtin IDs.
+///
+/// It contains every builtin of the targets, whether or not it's supported by
+/// some language options; \c Context checks that when looking a name up. It's
+/// immutable, so any number of contexts for the same targets can use it, also
+/// concurrently.
+class TargetBuiltins {
+  /// Open addressing with linear probing. A slot holds the hash of the name in
+  /// the upper 32 bits and the builtin ID in the lower 32 bits, or zero if
+  /// it's empty (zero is \c NotBuiltin).
+  std::unique_ptr<uint64_t[]> Slots;
+  size_t Mask = 0;
+
+  /// The target-independent shard, then the target's and the aux target's
+  /// shards: the order of their builtin IDs.
+  llvm::SmallVector<InfosShard, 16> Shards;
+  unsigned NumTargetShards = 0;
+
+  unsigned NumTargetBuiltins = 0;
+  unsigned NumAuxTargetBuiltins = 0;
+
+  /// Whether the builtin with \p ID is named \p Name.
+  bool hasName(unsigned ID, llvm::StringRef Name) const;
+
+public:
+  /// Collect the builtins of \p Target and \p AuxTarget, which may be null.
+  TargetBuiltins(const TargetInfo &Target, const TargetInfo *AuxTarget);
+
+  /// The shards of the target's builtins.
+  llvm::ArrayRef<InfosShard> getTargetShards() const {
+    return llvm::ArrayRef(Shards).slice(1, NumTargetShards);
+  }
+
+  /// The shards of the aux target's builtins.
+  llvm::ArrayRef<InfosShard> getAuxTargetShards() const {
+    return llvm::ArrayRef(Shards).drop_front(1 + NumTargetShards);
+  }
+
+  unsigned getNumTargetBuiltins() const { return NumTargetBuiltins; }
+  unsigned getNumAuxTargetBuiltins() const { return NumAuxTargetBuiltins; }
+
+  /// Return the shard of the builtin with \p ID and its info.
+  std::pair<const InfosShard &, const Info &>
+  getShardAndInfo(unsigned ID) const;
+
+  /// Return the IDs of all builtins named \p Name, in no particular order.
+  llvm::SmallVector<unsigned, 2> lookup(llvm::StringRef Name) const;
+};
+
 /// Holds information about both target-independent and
 /// target-specific builtins, allowing easy queries by clients.
 ///
-/// Builtins from an optional auxiliary target are stored in
-/// AuxTSRecords. Their IDs are shifted up by TSRecords.size() and need to
-/// be translated back with getAuxBuiltinID() before use.
+/// Builtins from an optional auxiliary target follow the target's builtins.
+/// Their IDs are shifted up by the number of target builtins and need to be
+/// translated back with getAuxBuiltinID() before use.
 class Context {
-  llvm::SmallVector<InfosShard> BuiltinShards;
-
-  llvm::SmallVector<InfosShard> TargetShards;
-  llvm::SmallVector<InfosShard> AuxTargetShards;
+  /// The builtins of the target and the aux target. Null for a context without
+  /// a target, which only has the target-independent builtins.
+  std::shared_ptr<const TargetBuiltins> Builtins;
 
+  /// Copies of the counts in Builtins, so that the inline isAuxBuiltinID() and
+  /// getAuxBuiltinID() don't need to go through it.
   unsigned NumTargetBuiltins = 0;
   unsigned NumAuxTargetBuiltins = 0;
 
 public:
+  /// Create a context with only the target-independent builtins. It doesn't
+  /// know any builtin names: \c lookupBuiltinID() always returns
+  /// \c NotBuiltin.
   Context();
 
-  /// Perform target-specific initialization
-  /// \param AuxTarget Target info to incorporate builtins from. May be 
nullptr.
-  void InitializeTarget(const TargetInfo &Target, const TargetInfo *AuxTarget);
-
-  /// Mark the identifiers for all the builtins with their
-  /// appropriate builtin ID # and mark any non-portable builtin identifiers as
-  /// such.
-  void initializeBuiltins(IdentifierTable &Table, const LangOptions& LangOpts);
+  /// Create a context with the builtins of \p Target and \p AuxTarget, which
+  /// may be null.
+  Context(const TargetInfo &Target, const TargetInfo *AuxTarget);
+
+  /// Create a context with \p Builtins, which can be shared with other
+  /// contexts for the same targets.
+  explicit Context(std::shared_ptr<const TargetBuiltins> Builtins);
+
+  /// Return the ID of the builtin named \p Name, or \c NotBuiltin if there's
+  /// none, \p LangOpts doesn't support it, or -fno-builtin-* disables it.
+  /// \c IdentifierTable::setBuiltinInfo() makes the table call this for each
+  /// identifier it creates.
+  unsigned lookupBuiltinID(llvm::StringRef Name,
+                           const LangOptions &LangOpts) const;
+
+  /// Call \p Fn with the name of every builtin supported by \p LangOpts,
+  /// whether or not the identifier table contains an identifier for it. Does
+  /// nothing for a context without a target. The order is unspecified, and
+  /// names might repeat.
+  void forEachBuiltinName(const LangOptions &LangOpts,
+                          llvm::function_ref<void(llvm::StringRef)> Fn) const;
 
   /// Return the identifier name for the specified builtin,
   /// e.g. "__builtin_abs".
diff --git a/clang/include/clang/Basic/IdentifierTable.h 
b/clang/include/clang/Basic/IdentifierTable.h
index ac1acb7ddac61b..a9e77001bce748 100644
--- a/clang/include/clang/Basic/IdentifierTable.h
+++ b/clang/include/clang/Basic/IdentifierTable.h
@@ -699,6 +699,19 @@ class IdentifierTable {
 
   IdentifierInfoLookup* ExternalLookup;
 
+  /// Assigns builtin IDs to identifiers as they get created, for the builtins
+  /// that BuiltinLangOpts supports.
+  const Builtin::Context *Builtins = nullptr;
+  const LangOptions *BuiltinLangOpts = nullptr;
+
+  /// Set the builtin ID of a new identifier if it names a builtin.
+  void assignBuiltinID(IdentifierInfo &II) {
+    if (Builtins)
+      if (unsigned ID =
+              Builtins->lookupBuiltinID(II.getName(), *BuiltinLangOpts))
+        II.setBuiltinID(ID);
+  }
+
 public:
   /// Create the identifier table.
   explicit IdentifierTable(IdentifierInfoLookup *ExternalLookup = nullptr);
@@ -718,6 +731,14 @@ class IdentifierTable {
     return ExternalLookup;
   }
 
+  /// Assign builtin IDs from \p Builtins to the identifiers in the table, and
+  /// to every identifier that gets created from now on, for the builtins
+  /// supported by \p LangOpts. This lets the table avoid creating identifiers
+  /// for all builtins upfront. \p Builtins and \p LangOpts must outlive the
+  /// table, and \p LangOpts must not change afterwards.
+  void setBuiltinInfo(const Builtin::Context &Builtins,
+                      const LangOptions &LangOpts);
+
   llvm::BumpPtrAllocator& getAllocator() {
     return HashTable.getAllocator();
   }
@@ -745,6 +766,8 @@ class IdentifierTable {
     // contents.
     II->Entry = &Entry;
 
+    assignBuiltinID(*II);
+
     return *II;
   }
 
@@ -776,6 +799,8 @@ class IdentifierTable {
     // contents.
     II->Entry = &Entry;
 
+    assignBuiltinID(*II);
+
     // If this is the 'import' or 'module' contextual keyword, mark it as such.
     if (Name == "import")
       II->setKeywordImport(true);
diff --git a/clang/include/clang/Frontend/CompilerInstance.h 
b/clang/include/clang/Frontend/CompilerInstance.h
index c001229eea7fd8..62f099d666c9c8 100644
--- a/clang/include/clang/Frontend/CompilerInstance.h
+++ b/clang/include/clang/Frontend/CompilerInstance.h
@@ -64,6 +64,10 @@ class SourceManager;
 class TargetInfo;
 enum class DisableValidationForModuleKind;
 
+namespace Builtin {
+class TargetBuiltins;
+} // namespace Builtin
+
 /// CompilerInstance - Helper class for managing a single instance of the Clang
 /// compiler.
 ///
@@ -113,6 +117,10 @@ class CompilerInstance : public ModuleLoader {
   /// The cache of PCM files.
   std::shared_ptr<ModuleCache> ModCache;
 
+  /// The builtins of the instance's target and aux target, shared with the
+  /// module builds it requests, which have the same targets.
+  std::shared_ptr<const Builtin::TargetBuiltins> SharedBuiltins;
+
   /// Directory dependencies from the instance that requested this module 
build.
   /// An inferred framework is built from printed module map text rather than 
by
   /// repeating the inference, so its \c Frameworks listing is only seen there.
diff --git a/clang/include/clang/Lex/Preprocessor.h 
b/clang/include/clang/Lex/Preprocessor.h
index 8d15ed7e8afd85..bd7bd08aa546dc 100644
--- a/clang/include/clang/Lex/Preprocessor.h
+++ b/clang/include/clang/Lex/Preprocessor.h
@@ -88,7 +88,8 @@ class NoTrivialPPDirectiveTracer;
 
 namespace Builtin {
 class Context;
-}
+class TargetBuiltins;
+} // namespace Builtin
 
 /// Stores token information for comparing actual tokens with
 /// predefined values.  Only handles simple tokens and identifiers.
@@ -1252,8 +1253,12 @@ class Preprocessor {
   /// lifetime of the preprocessor.
   /// \param AuxTarget is owned by the caller and must remain valid for
   /// the lifetime of the preprocessor.
-  void Initialize(const TargetInfo &Target,
-                  const TargetInfo *AuxTarget = nullptr);
+  /// \param SharedBuiltins are the builtins of \p Target and \p AuxTarget.
+  /// They must have been collected for exactly these targets (or targets with
+  /// the same builtins). If null, the preprocessor collects them.
+  void Initialize(
+      const TargetInfo &Target, const TargetInfo *AuxTarget = nullptr,
+      std::shared_ptr<const Builtin::TargetBuiltins> SharedBuiltins = nullptr);
 
   /// Initialize the preprocessor to parse a model file
   ///
diff --git a/clang/lib/Basic/Builtins.cpp b/clang/lib/Basic/Builtins.cpp
index 7ea55b268cf8f8..7e05045046be2d 100644
--- a/clang/lib/Basic/Builtins.cpp
+++ b/clang/lib/Basic/Builtins.cpp
@@ -12,11 +12,14 @@
 
 #include "clang/Basic/Builtins.h"
 #include "BuiltinTargetFeatures.h"
-#include "clang/Basic/IdentifierTable.h"
 #include "clang/Basic/LangOptions.h"
 #include "clang/Basic/TargetInfo.h"
+#include "llvm/ADT/STLExtras.h"
 #include "llvm/ADT/SmallString.h"
 #include "llvm/ADT/StringRef.h"
+#include "llvm/Support/MathExtras.h"
+#include "llvm/Support/xxhash.h"
+#include <memory>
 using namespace clang;
 
 const char *HeaderDesc::getName() const {
@@ -44,32 +47,16 @@ static constexpr Builtin::Info BuiltinInfos[] = {
 };
 static_assert(std::size(BuiltinInfos) == NumBuiltins);
 
+/// The shard of the target-independent builtins, which every context has.
+static const Builtin::InfosShard TargetIndependentShards[] = {
+    {&BuiltinStrings, BuiltinInfos}};
+
 std::pair<const Builtin::InfosShard &, const Builtin::Info &>
 Builtin::Context::getShardAndInfo(unsigned ID) const {
-  assert((ID < (Builtin::FirstTSBuiltin + NumTargetBuiltins +
-                NumAuxTargetBuiltins)) &&
-         "Invalid builtin ID!");
-
-  ArrayRef<InfosShard> Shards = BuiltinShards;
-  if (isAuxBuiltinID(ID)) {
-    Shards = AuxTargetShards;
-    ID = getAuxBuiltinID(ID) - Builtin::FirstTSBuiltin;
-  } else if (ID >= Builtin::FirstTSBuiltin) {
-    Shards = TargetShards;
-    ID -= Builtin::FirstTSBuiltin;
-  }
-
-  // Loop over the shards to find the one matching this ID. We don't expect to
-  // have many shards and so its better to search linearly than with a binary
-  // search.
-  for (const auto &Shard : Shards) {
-    if (ID < Shard.Infos.size()) {
-      return {Shard, Shard.Infos[ID]};
-    }
-
-    ID -= Shard.Infos.size();
-  }
-  llvm_unreachable("Invalid target builtin shard structure!");
+  if (Builtins)
+    return Builtins->getShardAndInfo(ID);
+  assert(ID < Builtin::FirstTSBuiltin && "Invalid builtin ID!");
+  return {TargetIndependentShards[0], BuiltinInfos[ID]};
 }
 
 /// Return a non-owning StringRef of the builtin's name, reconstructed into 
Buf.
@@ -120,25 +107,19 @@ const char 
*Builtin::Context::getRequiredFeatures(unsigned ID) const {
   return (*Shard.Strings)[I.Offsets.Features].data();
 }
 
-Builtin::Context::Context() : BuiltinShards{{&BuiltinStrings, BuiltinInfos}} {}
+Builtin::Context::Context() = default;
 
-void Builtin::Context::InitializeTarget(const TargetInfo &Target,
-                                        const TargetInfo *AuxTarget) {
-  assert(TargetShards.empty() && "Already initialized target?");
-  assert(NumTargetBuiltins == 0 && "Already initialized target?");
-  TargetShards = Target.getTargetBuiltins();
-  for (const auto &Shard : TargetShards)
-    NumTargetBuiltins += Shard.Infos.size();
-  if (AuxTarget) {
-    AuxTargetShards = AuxTarget->getTargetBuiltins();
-    for (const auto &Shard : AuxTargetShards)
-      NumAuxTargetBuiltins += Shard.Infos.size();
-  }
-}
+Builtin::Context::Context(const TargetInfo &Target, const TargetInfo 
*AuxTarget)
+    : Context(std::make_shared<const TargetBuiltins>(Target, AuxTarget)) {}
+
+Builtin::Context::Context(std::shared_ptr<const TargetBuiltins> Builtins)
+    : Builtins(std::move(Builtins)),
+      NumTargetBuiltins(this->Builtins->getNumTargetBuiltins()),
+      NumAuxTargetBuiltins(this->Builtins->getNumAuxTargetBuiltins()) {}
 
 bool Builtin::Context::isBuiltinFunc(llvm::StringRef FuncName) {
   bool InStdNamespace = FuncName.consume_front("std-");
-  for (const auto &Shard : {InfosShard{&BuiltinStrings, BuiltinInfos}})
+  for (const auto &Shard : TargetIndependentShards)
     if (llvm::StringRef FuncNameSuffix = FuncName;
         FuncNameSuffix.consume_front(Shard.NamePrefix))
       for (const auto &I : Shard.Infos)
@@ -309,52 +290,135 @@ bool Builtin::Context::shouldGenerateFPMathIntrinsic(
   return GenerateIntrinsics;
 }
 
-/// initializeBuiltins - Mark the identifiers for all the builtins with their
-/// appropriate builtin ID # and mark any non-portable builtin identifiers as
-/// such.
-void Builtin::Context::initializeBuiltins(IdentifierTable &Table,
-                                          const LangOptions &LangOpts) {
-  {
-    unsigned ID = 0;
-    llvm::SmallString<256> NameBuf;
-    // Step #1: mark all target-independent builtins with their ID's.
-    for (const auto &Shard : BuiltinShards)
-      for (const auto &I : Shard.Infos) {
-        // If this is a real builtin (ID != 0) and is supported, add it.
-        if (ID != 0 && builtinIsSupported(*Shard.Strings, I, LangOpts))
-          Table.get(getBuiltinNameInto(Shard, I, NameBuf)).setBuiltinID(ID);
-        ++ID;
-      }
-    assert(ID == FirstTSBuiltin && "Should have added all non-target IDs!");
-
-    // Step #2: Register target-specific builtins.
-    for (const auto &Shard : TargetShards)
-      for (const auto &I : Shard.Infos) {
-        if (builtinIsSupported(*Shard.Strings, I, LangOpts))
-          Table.get(getBuiltinNameInto(Shard, I, NameBuf)).setBuiltinID(ID);
-        ++ID;
-      }
+static uint32_t hashBuiltinName(StringRef Name) {
+  return static_cast<uint32_t>(llvm::xxh3_64bits(Name));
+}
 
-    // Step #3: Register target-specific builtins for AuxTarget.
-    for (const auto &Shard : AuxTargetShards)
-      for (const auto &I : Shard.Infos) {
-        Table.get(getBuiltinNameInto(Shard, I, NameBuf)).setBuiltinID(ID);
-        ++ID;
+Builtin::TargetBuiltins::TargetBuiltins(const TargetInfo &Target,
+                                        const TargetInfo *AuxTarget) {
+  llvm::append_range(Shards, TargetIndependentShards);
+  llvm::append_range(Shards, Target.getTargetBuiltins());
+  NumTargetShards = Shards.size() - 1;
+  if (AuxTarget)
+    llvm::append_range(Shards, AuxTarget->getTargetBuiltins());
+  for (const InfosShard &Shard : getTargetShards())
+    NumTargetBuiltins += Shard.Infos.size();
+  for (const InfosShard &Shard : getAuxTargetShards())
+    NumAuxTargetBuiltins += Shard.Infos.size();
+
+  size_t NumNames = 0;
+  for (const InfosShard &Shard : Shards)
+    NumNames += Shard.Infos.size();
+  // Keep the load factor at or below 1/2.
+  size_t NumSlots = llvm::PowerOf2Ceil(NumNames * 2);
+  Slots = std::make_unique<uint64_t[]>(NumSlots);
+  Mask = NumSlots - 1;
+  unsigned ID = 0;
+  SmallString<256> NameBuf;
+  for (const InfosShard &Shard : Shards) {
+    for (const Info &I : Shard.Infos) {
+      // Skip the "not a builtin" entry.
+      if (ID != NotBuiltin) {
+        uint32_t Hash = hashBuiltinName(getBuiltinNameInto(Shard, I, NameBuf));
+        size_t Slot = Hash & Mask;
+        while (Slots[Slot])
+          Slot = (Slot + 1) & Mask;
+        Slots[Slot] = (uint64_t(Hash) << 32) | ID;
       }
+      ++ID;
+    }
   }
+}
 
-  // Step #4: Unregister any builtins specified by -fno-builtin-foo.
-  for (llvm::StringRef Name : LangOpts.NoBuiltinFuncs) {
-    bool InStdNamespace = Name.consume_front("std-");
-    auto NameIt = Table.find(Name);
-    if (NameIt != Table.end()) {
-      unsigned ID = NameIt->second->getBuiltinID();
-      if (ID != Builtin::NotBuiltin && isPredefinedLibFunction(ID) &&
-          isInStdNamespace(ID) == InStdNamespace) {
-        NameIt->second->clearBuiltinID();
-      }
-    }
+std::pair<const Builtin::InfosShard &, const Builtin::Info &>
+Builtin::TargetBuiltins::getShardAndInfo(unsigned ID) const {
+  assert(ID < FirstTSBuiltin + NumTargetBuiltins + NumAuxTargetBuiltins &&
+         "Invalid builtin ID!");
+  // Find the group of shards from the ID, then loop over the shards of the
+  // group to find the one matching this ID. We don't expect to have many
+  // shards and so its better to search linearly than with a binary search.
+  ArrayRef<InfosShard> Group = ArrayRef(Shards).take_front(1);
+  if (ID >= FirstTSBuiltin + NumTargetBuiltins) {
+    Group = getAuxTargetShards();
+    ID -= FirstTSBuiltin + NumTargetBuiltins;
+  } else if (ID >= FirstTSBuiltin) {
+    Group = getTargetShards();
+    ID -= FirstTSBuiltin;
+  }
+  for (const InfosShard &Shard : Group) {
+    if (ID < Shard.Infos.size())
+      return {Shard, Shard.Infos[ID]};
+    ID -= Shard.Infos.size();
+  }
+  llvm_unreachable("Invalid target builtin shard structure!");
+}
+
+bool Builtin::TargetBuiltins::hasName(unsigned ID, StringRef Name) const {
+  const auto &[Shard, I] = getShardAndInfo(ID);
+  return Name.consume_front(Shard.NamePrefix) &&
+         Name == (*Shard.Strings)[I.Offsets.Name];
+}
+
+SmallVector<unsigned, 2> Builtin::TargetBuiltins::lookup(StringRef Name) const 
{
+  SmallVector<unsigned, 2> IDs;
+  uint32_t Hash = hashBuiltinName(Name);
+  for (size_t Slot = Hash & Mask; uint64_t Entry = Slots[Slot];
+       Slot = (Slot + 1) & Mask) {
+    unsigned ID = static_cast<uint32_t>(Entry);
+    if (Entry >> 32 == Hash && hasName(ID, Name))
+      IDs.push_back(ID);
+  }
+  return IDs;
+}
+
+unsigned Builtin::Context::lookupBuiltinID(StringRef Name,
+                                           const LangOptions &LangOpts) const {
+  // This needs to behave as if the builtins were registered in the order of
+  // their IDs, with later registrations overriding earlier ones: aux target
+  // builtins win over target builtins, which win over target-independent
+  // ones. Aux target builtins are registered even if unsupported.
+  if (!Builtins)
+    return NotBuiltin;
+  unsigned Result = NotBuiltin;
+  for (unsigned ID : Builtins->lookup(Name)) {
+    if (ID <= Result)
+      continue;
+    const auto &[Shard, I] = getShardAndInfo(ID);
+    if (isAuxBuiltinID(ID) || builtinIsSupported(*Shard.Strings, I, LangOpts))
+      Result = ID;
   }
+  if (Result == NotBuiltin)
+    return NotBuiltin;
+
+  // Library builtins can be disabled with -fno-builtin-foo, or with
+  // -fno-builtin-std-foo for those in namespace std.
+  if (isPredefinedLibFunction(Result)) {
+    bool InStdNamespace = isInStdNamespace(Result);
+    for (StringRef NoBuiltin : LangOpts.NoBuiltinFuncs)
+      if (NoBuiltin.consume_front("std-") == InStdNamespace &&
+       ...
[truncated]

``````````

</details>


https://github.com/llvm/llvm-project/pull/243274
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to