cpp_global_var.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Part of the Carbon Language project, under the Apache License v2.0 with LLVM
  2. // Exceptions. See /LICENSE for license information.
  3. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. #ifndef CARBON_TOOLCHAIN_SEM_IR_CPP_GLOBAL_VAR_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_CPP_GLOBAL_VAR_H_
  6. #include "common/hashing.h"
  7. #include "common/ostream.h"
  8. #include "toolchain/sem_ir/clang_decl.h"
  9. #include "toolchain/sem_ir/ids.h"
  10. namespace Carbon::SemIR {
  11. // A key describing a C++ global variable imported into Carbon, identified by
  12. // its entity name.
  13. struct CppGlobalVarKey : public Printable<CppGlobalVarKey> {
  14. auto Print(llvm::raw_ostream& out) const -> void {
  15. out << "{entity_name_id: " << entity_name_id << "}";
  16. }
  17. // TODO: Use default when `Printable` supports it.
  18. friend auto operator==(const CppGlobalVarKey& lhs, const CppGlobalVarKey& rhs)
  19. -> bool {
  20. return lhs.entity_name_id == rhs.entity_name_id;
  21. }
  22. // The name of the variable.
  23. EntityNameId entity_name_id;
  24. };
  25. // A C++ global variable imported into Carbon. This is used to map the entity
  26. // name to the Clang declaration so we can use Clang mangling.
  27. struct CppGlobalVar : public Printable<CppGlobalVar> {
  28. auto Print(llvm::raw_ostream& out) const -> void {
  29. out << "{key: " << key << ", clang_decl_id: " << clang_decl_id << "}";
  30. }
  31. // Comparison against `CppGlobalVarKey`, required by `CanonicalValueStore`.
  32. friend auto operator==(const CppGlobalVar& lhs, const CppGlobalVarKey& rhs)
  33. -> bool {
  34. return lhs.key == rhs;
  35. }
  36. friend auto operator==(const CppGlobalVar& lhs, const CppGlobalVar& rhs)
  37. -> bool {
  38. return lhs.key == rhs.key;
  39. }
  40. // Hashing for `CppGlobalVar`. See common/hashing.h.
  41. friend auto CarbonHashValue(const CppGlobalVar& value, uint64_t seed)
  42. -> HashCode {
  43. return HashValue(value.key, seed);
  44. }
  45. // The key by which this variable can be looked up.
  46. CppGlobalVarKey key;
  47. // The Clang declaration for this variable, if any.
  48. // This is ignored for equality and hashing, since it's always unique for a
  49. // given key, in order to store it in `CanonicalValueStore` and allow lookup
  50. // by `CppGlobalVarKey`.
  51. ClangDeclId clang_decl_id;
  52. };
  53. // Use the name of a C++ global variable when doing `Lookup` to find an ID.
  54. using CppGlobalVarStore =
  55. CanonicalValueStore<CppGlobalVarId, CppGlobalVarKey, CppGlobalVar>;
  56. } // namespace Carbon::SemIR
  57. #endif // CARBON_TOOLCHAIN_SEM_IR_CPP_GLOBAL_VAR_H_