mangler.cpp 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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. #include "toolchain/lower/mangler.h"
  5. #include <string>
  6. #include "common/raw_string_ostream.h"
  7. #include "toolchain/base/kind_switch.h"
  8. #include "toolchain/lower/clang_global_decl.h"
  9. #include "toolchain/sem_ir/entry_point.h"
  10. #include "toolchain/sem_ir/ids.h"
  11. #include "toolchain/sem_ir/pattern.h"
  12. namespace Carbon::Lower {
  13. auto Mangler::MangleNameId(llvm::raw_ostream& os, SemIR::NameId name_id)
  14. -> void {
  15. CARBON_CHECK(name_id.AsIdentifierId().has_value(),
  16. "Mangling non-identifier name {0}", name_id);
  17. os << names().GetAsStringIfIdentifier(name_id);
  18. }
  19. auto Mangler::MangleInverseQualifiedNameScope(llvm::raw_ostream& os,
  20. SemIR::NameScopeId name_scope_id)
  21. -> void {
  22. // Maintain a stack of names for delayed rendering of interface impls.
  23. struct NameEntry {
  24. SemIR::NameScopeId name_scope_id;
  25. // The prefix emitted before this name component. If '\0', no prefix will be
  26. // emitted.
  27. // - Namespace components are separated by '.'.
  28. // - The two components of an interface are separated by ':'.
  29. char prefix;
  30. };
  31. llvm::SmallVector<NameEntry> names_to_render;
  32. names_to_render.push_back({.name_scope_id = name_scope_id, .prefix = '.'});
  33. while (!names_to_render.empty()) {
  34. auto [name_scope_id, prefix] = names_to_render.pop_back_val();
  35. if (prefix) {
  36. os << prefix;
  37. }
  38. if (name_scope_id == SemIR::NameScopeId::Package) {
  39. auto package_id = sem_ir().package_id();
  40. if (auto ident_id = package_id.AsIdentifierId(); ident_id.has_value()) {
  41. os << sem_ir().identifiers().Get(ident_id);
  42. } else {
  43. // TODO: Handle name conflicts between special package names and raw
  44. // identifier package names. Note that any change here will also require
  45. // a change to namespace mangling for imported packages.
  46. os << package_id.AsSpecialName();
  47. }
  48. continue;
  49. }
  50. const auto& name_scope = sem_ir().name_scopes().Get(name_scope_id);
  51. CARBON_KIND_SWITCH(sem_ir().insts().Get(name_scope.inst_id())) {
  52. case CARBON_KIND(SemIR::ImplDecl impl_decl): {
  53. const auto& impl = sem_ir().impls().Get(impl_decl.impl_id);
  54. auto facet_type = insts().GetAs<SemIR::FacetType>(
  55. constant_values().GetConstantInstId(impl.constraint_id));
  56. const auto& facet_type_info =
  57. sem_ir().facet_types().Get(facet_type.facet_type_id);
  58. CARBON_CHECK(facet_type_info.extend_constraints.size() == 1,
  59. "Mangling of an impl of something other than a single "
  60. "interface is not yet supported.");
  61. auto interface_type = facet_type_info.extend_constraints.front();
  62. const auto& interface =
  63. sem_ir().interfaces().Get(interface_type.interface_id);
  64. names_to_render.push_back(
  65. {.name_scope_id = interface.scope_id, .prefix = ':'});
  66. auto self_const_inst_id =
  67. constant_values().GetConstantInstId(impl.self_id);
  68. auto self_inst = insts().Get(self_const_inst_id);
  69. CARBON_KIND_SWITCH(self_inst) {
  70. case CARBON_KIND(SemIR::ClassType class_type): {
  71. auto next_name_scope_id =
  72. sem_ir().classes().Get(class_type.class_id).scope_id;
  73. names_to_render.push_back(
  74. {.name_scope_id = next_name_scope_id, .prefix = '\0'});
  75. break;
  76. }
  77. case SemIR::AutoType::Kind:
  78. case SemIR::BoolType::Kind:
  79. case SemIR::BoundMethodType::Kind:
  80. case SemIR::IntLiteralType::Kind:
  81. case SemIR::LegacyFloatType::Kind:
  82. case SemIR::NamespaceType::Kind:
  83. case SemIR::SpecificFunctionType::Kind:
  84. case SemIR::StringType::Kind:
  85. case SemIR::TypeType::Kind:
  86. case SemIR::VtableType::Kind:
  87. case SemIR::WitnessType::Kind: {
  88. os << self_inst.kind().ir_name();
  89. break;
  90. }
  91. case CARBON_KIND(SemIR::IntType int_type): {
  92. os << (int_type.int_kind == SemIR::IntKind::Signed ? "i" : "u")
  93. << sem_ir().ints().Get(
  94. sem_ir()
  95. .insts()
  96. .GetAs<SemIR::IntValue>(int_type.bit_width_id)
  97. .int_id);
  98. break;
  99. }
  100. default: {
  101. // Fall back to including a fingerprint.
  102. llvm::write_hex(
  103. os, fingerprinter_.GetOrCompute(&sem_ir(), self_const_inst_id),
  104. llvm::HexPrintStyle::Lower, 16);
  105. break;
  106. }
  107. }
  108. // Skip the tail of the loop that adds the parent name scope to the
  109. // stack - the scope in which the impl was defined is not part of the
  110. // mangling, the constraint and interface alone uniquelify identify an
  111. // impl.
  112. continue;
  113. }
  114. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  115. MangleNameId(os, sem_ir().classes().Get(class_decl.class_id).name_id);
  116. break;
  117. }
  118. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  119. MangleNameId(
  120. os, sem_ir().interfaces().Get(interface_decl.interface_id).name_id);
  121. break;
  122. }
  123. case SemIR::Namespace::Kind: {
  124. os << names().GetIRBaseName(name_scope.name_id());
  125. break;
  126. }
  127. default:
  128. CARBON_FATAL("Attempting to mangle unsupported SemIR.");
  129. break;
  130. }
  131. if (!name_scope.is_imported_package()) {
  132. names_to_render.push_back(
  133. {.name_scope_id = name_scope.parent_scope_id(), .prefix = '.'});
  134. }
  135. }
  136. }
  137. auto Mangler::Mangle(SemIR::FunctionId function_id,
  138. SemIR::SpecificId specific_id) -> std::string {
  139. const auto& function = sem_ir().functions().Get(function_id);
  140. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  141. CARBON_CHECK(!specific_id.has_value(), "entry point should not be generic");
  142. return "main";
  143. }
  144. if (function.clang_decl_id.has_value()) {
  145. return MangleCppClang(dyn_cast<clang::NamedDecl>(
  146. sem_ir().clang_decls().Get(function.clang_decl_id).decl));
  147. }
  148. RawStringOstream os;
  149. os << "_C";
  150. MangleNameId(os, function.name_id);
  151. // For a special function, add a marker to disambiguate.
  152. switch (function.special_function_kind) {
  153. case SemIR::Function::SpecialFunctionKind::None:
  154. break;
  155. case SemIR::Function::SpecialFunctionKind::Builtin:
  156. CARBON_FATAL("Attempting to mangle declaration of builtin function {0}",
  157. function.builtin_function_kind());
  158. case SemIR::Function::SpecialFunctionKind::Thunk:
  159. os << ":thunk";
  160. break;
  161. case SemIR::Function::SpecialFunctionKind::HasCppThunk:
  162. CARBON_FATAL("C++ functions should have been handled earlier");
  163. }
  164. // TODO: If the function is private, also include the library name as part of
  165. // the mangling.
  166. MangleInverseQualifiedNameScope(os, function.parent_scope_id);
  167. MangleSpecificId(os, specific_id);
  168. return os.TakeStr();
  169. }
  170. auto Mangler::MangleSpecificId(llvm::raw_ostream& os,
  171. SemIR::SpecificId specific_id) -> void {
  172. // TODO: Add proper support for mangling generic entities. For now we use a
  173. // fingerprint of the specific arguments, which should be stable across files,
  174. // but isn't necessarily stable across toolchain changes.
  175. if (specific_id.has_value()) {
  176. os << ".";
  177. llvm::write_hex(
  178. os,
  179. fingerprinter_.GetOrCompute(
  180. &sem_ir(), sem_ir().specifics().Get(specific_id).args_id),
  181. llvm::HexPrintStyle::Lower, 16);
  182. }
  183. }
  184. auto Mangler::MangleGlobalVariable(SemIR::InstId pattern_id) -> std::string {
  185. // Use the name of the first binding in the variable as its mangled name.
  186. auto var_name_id =
  187. SemIR::GetFirstBindingNameFromPatternId(sem_ir(), pattern_id);
  188. if (!var_name_id.has_value()) {
  189. return std::string();
  190. }
  191. RawStringOstream os;
  192. os << "_C";
  193. auto var_name = sem_ir().entity_names().Get(var_name_id);
  194. MangleNameId(os, var_name.name_id);
  195. // TODO: If the variable is private, also include the library name as part of
  196. // the mangling.
  197. MangleInverseQualifiedNameScope(os, var_name.parent_scope_id);
  198. return os.TakeStr();
  199. }
  200. auto Mangler::MangleCppClang(const clang::NamedDecl* decl) -> std::string {
  201. return file_context_.cpp_code_generator()
  202. .GetMangledName(CreateGlobalDecl(decl))
  203. .str();
  204. }
  205. auto Mangler::MangleVTable(const SemIR::Class& class_info,
  206. SemIR::SpecificId specific_id) -> std::string {
  207. RawStringOstream os;
  208. os << "_C";
  209. MangleNameId(os, class_info.name_id);
  210. // TODO: If the class is private, also include the library name as part of the
  211. // mangling.
  212. MangleInverseQualifiedNameScope(os, class_info.parent_scope_id);
  213. os << ".$vtable";
  214. MangleSpecificId(os, specific_id);
  215. return os.TakeStr();
  216. }
  217. } // namespace Carbon::Lower