import.cpp 95 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323
  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/check/cpp/import.h"
  5. #include <algorithm>
  6. #include <memory>
  7. #include <optional>
  8. #include <string>
  9. #include <tuple>
  10. #include <utility>
  11. #include "clang/AST/ASTContext.h"
  12. #include "clang/AST/RecordLayout.h"
  13. #include "clang/AST/UnresolvedSet.h"
  14. #include "clang/AST/VTableBuilder.h"
  15. #include "clang/Frontend/CompilerInvocation.h"
  16. #include "clang/Sema/Lookup.h"
  17. #include "clang/Sema/Overload.h"
  18. #include "common/check.h"
  19. #include "common/ostream.h"
  20. #include "common/raw_string_ostream.h"
  21. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  22. #include "llvm/ADT/ScopeExit.h"
  23. #include "llvm/ADT/StringRef.h"
  24. #include "llvm/Support/raw_ostream.h"
  25. #include "toolchain/base/int.h"
  26. #include "toolchain/base/kind_switch.h"
  27. #include "toolchain/base/value_ids.h"
  28. #include "toolchain/check/call.h"
  29. #include "toolchain/check/class.h"
  30. #include "toolchain/check/context.h"
  31. #include "toolchain/check/control_flow.h"
  32. #include "toolchain/check/convert.h"
  33. #include "toolchain/check/core_identifier.h"
  34. #include "toolchain/check/cpp/access.h"
  35. #include "toolchain/check/cpp/custom_type_mapping.h"
  36. #include "toolchain/check/cpp/generate_ast.h"
  37. #include "toolchain/check/cpp/location.h"
  38. #include "toolchain/check/cpp/macros.h"
  39. #include "toolchain/check/cpp/thunk.h"
  40. #include "toolchain/check/diagnostic_helpers.h"
  41. #include "toolchain/check/eval.h"
  42. #include "toolchain/check/function.h"
  43. #include "toolchain/check/import.h"
  44. #include "toolchain/check/inst.h"
  45. #include "toolchain/check/literal.h"
  46. #include "toolchain/check/member_access.h"
  47. #include "toolchain/check/name_lookup.h"
  48. #include "toolchain/check/operator.h"
  49. #include "toolchain/check/pattern.h"
  50. #include "toolchain/check/pattern_match.h"
  51. #include "toolchain/check/type.h"
  52. #include "toolchain/check/type_completion.h"
  53. #include "toolchain/parse/node_ids.h"
  54. #include "toolchain/sem_ir/clang_decl.h"
  55. #include "toolchain/sem_ir/class.h"
  56. #include "toolchain/sem_ir/cpp_file.h"
  57. #include "toolchain/sem_ir/cpp_overload_set.h"
  58. #include "toolchain/sem_ir/function.h"
  59. #include "toolchain/sem_ir/ids.h"
  60. #include "toolchain/sem_ir/inst.h"
  61. #include "toolchain/sem_ir/name_scope.h"
  62. #include "toolchain/sem_ir/typed_insts.h"
  63. namespace Carbon::Check {
  64. // Adds the name to the scope with the given `access_kind` and `inst_id`.
  65. // `inst_id` must have a value.
  66. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  67. SemIR::NameId name_id, SemIR::AccessKind access_kind,
  68. SemIR::InstId inst_id) -> void {
  69. CARBON_CHECK(inst_id.has_value());
  70. context.name_scopes().Get(scope_id).AddRequired(
  71. {.name_id = name_id,
  72. .result = SemIR::ScopeLookupResult::MakeFound(inst_id, access_kind)});
  73. }
  74. // Maps a Clang name to a Carbon `NameId`.
  75. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  76. -> SemIR::NameId {
  77. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  78. }
  79. // Adds the given source location and an `ImportIRInst` referring to it in
  80. // `ImportIRId::Cpp`.
  81. static auto AddImportIRInst(SemIR::File& file,
  82. clang::SourceLocation clang_source_loc)
  83. -> SemIR::ImportIRInstId {
  84. SemIR::ClangSourceLocId clang_source_loc_id =
  85. file.clang_source_locs().Add(clang_source_loc);
  86. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  87. }
  88. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  89. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  90. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  91. -> SemIR::NameScopeId {
  92. return AddImportNamespaceToScope(
  93. context,
  94. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  95. SemIR::NameId::ForPackageName(cpp_package_id),
  96. SemIR::NameScopeId::Package,
  97. /*diagnose_duplicate_namespace=*/false,
  98. [&]() {
  99. return AddInst<SemIR::ImportCppDecl>(
  100. context,
  101. context.parse_tree().As<Parse::ImportDeclId>(
  102. imports.front().node_id),
  103. {});
  104. })
  105. .add_result.name_scope_id;
  106. }
  107. auto ImportCpp(Context& context,
  108. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  109. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  110. llvm::LLVMContext* llvm_context,
  111. std::shared_ptr<clang::CompilerInvocation> invocation) -> void {
  112. if (imports.empty()) {
  113. // TODO: Consider always having a (non-null) AST even if there are no Cpp
  114. // imports.
  115. return;
  116. }
  117. PackageNameId package_id = imports.front().package_id;
  118. CARBON_CHECK(
  119. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  120. return import.package_id == package_id;
  121. }));
  122. auto name_scope_id = AddNamespace(context, package_id, imports);
  123. bool ast_has_error =
  124. !GenerateAst(context, imports, fs, llvm_context, std::move(invocation));
  125. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  126. name_scope.set_is_closed_import(true);
  127. name_scope.set_clang_decl_context_id(context.clang_decls().Add(
  128. {.key =
  129. SemIR::ClangDeclKey(context.ast_context().getTranslationUnitDecl()),
  130. .inst_id = name_scope.inst_id()}));
  131. if (ast_has_error) {
  132. name_scope.set_has_error();
  133. }
  134. }
  135. // Returns the Clang `DeclContext` for the given name scope. Return the
  136. // translation unit decl if no scope is provided.
  137. static auto GetDeclContext(Context& context, SemIR::NameScopeId scope_id)
  138. -> clang::DeclContext* {
  139. if (!scope_id.has_value()) {
  140. return context.ast_context().getTranslationUnitDecl();
  141. }
  142. auto scope_clang_decl_context_id =
  143. context.name_scopes().Get(scope_id).clang_decl_context_id();
  144. return dyn_cast<clang::DeclContext>(
  145. context.clang_decls().Get(scope_clang_decl_context_id).key.decl);
  146. }
  147. // Returns true if the given Clang declaration is the implicit injected class
  148. // name within the class.
  149. static auto IsDeclInjectedClassName(Context& context,
  150. SemIR::NameScopeId scope_id,
  151. SemIR::NameId name_id,
  152. const clang::NamedDecl* named_decl)
  153. -> bool {
  154. if (!named_decl->isImplicit()) {
  155. return false;
  156. }
  157. const auto* record_decl = dyn_cast<clang::CXXRecordDecl>(named_decl);
  158. if (!record_decl) {
  159. return false;
  160. }
  161. const SemIR::ClangDecl& clang_decl = context.clang_decls().Get(
  162. context.name_scopes().Get(scope_id).clang_decl_context_id());
  163. const auto* scope_record_decl =
  164. cast<clang::CXXRecordDecl>(clang_decl.key.decl);
  165. const clang::ASTContext& ast_context = context.ast_context();
  166. CARBON_CHECK(ast_context.getCanonicalTagType(scope_record_decl) ==
  167. ast_context.getCanonicalTagType(record_decl));
  168. auto class_decl = context.insts().GetAs<SemIR::ClassDecl>(clang_decl.inst_id);
  169. CARBON_CHECK(name_id == context.classes().Get(class_decl.class_id).name_id);
  170. return true;
  171. }
  172. // Performs a qualified name lookup of the identifier in the given scope.
  173. // Returns the lookup result if lookup was successful.
  174. static auto ClangLookupName(Context& context, SemIR::NameScopeId scope_id,
  175. clang::IdentifierInfo* identifier_name)
  176. -> std::optional<clang::LookupResult> {
  177. CARBON_CHECK(identifier_name, "Identifier name is empty");
  178. clang::Sema& sema = context.clang_sema();
  179. // TODO: Map the LocId of the lookup to a clang SourceLocation and provide it
  180. // here so that clang's diagnostics can point into the carbon code that uses
  181. // the name.
  182. clang::LookupResult lookup(
  183. sema,
  184. clang::DeclarationNameInfo(clang::DeclarationName(identifier_name),
  185. clang::SourceLocation()),
  186. clang::Sema::LookupNameKind::LookupOrdinaryName);
  187. bool found =
  188. sema.LookupQualifiedName(lookup, GetDeclContext(context, scope_id));
  189. if (!found) {
  190. return std::nullopt;
  191. }
  192. return lookup;
  193. }
  194. // Returns whether `decl` already mapped to an instruction.
  195. static auto IsClangDeclImported(Context& context, SemIR::ClangDeclKey key)
  196. -> bool {
  197. return context.clang_decls().Lookup(key).has_value();
  198. }
  199. // If `decl` already mapped to an instruction, returns that instruction.
  200. // Otherwise returns `None`.
  201. static auto LookupClangDeclInstId(Context& context, SemIR::ClangDeclKey key)
  202. -> SemIR::InstId {
  203. const auto& clang_decls = context.clang_decls();
  204. if (auto context_clang_decl_id = clang_decls.Lookup(key);
  205. context_clang_decl_id.has_value()) {
  206. return clang_decls.Get(context_clang_decl_id).inst_id;
  207. }
  208. return SemIR::InstId::None;
  209. }
  210. // Returns the parent of the given declaration. Skips declaration types we
  211. // ignore.
  212. static auto GetParentDecl(clang::Decl* clang_decl) -> clang::Decl* {
  213. auto* parent_dc = clang_decl->getDeclContext();
  214. while (!parent_dc->isLookupContext()) {
  215. parent_dc = parent_dc->getParent();
  216. }
  217. return cast<clang::Decl>(parent_dc);
  218. }
  219. // Returns the given declaration's parent scope. Assumes the parent declaration
  220. // was already imported.
  221. static auto GetParentNameScopeId(Context& context, clang::Decl* clang_decl)
  222. -> SemIR::NameScopeId {
  223. auto* parent_decl = GetParentDecl(clang_decl);
  224. if (auto* tag_decl = dyn_cast<clang::TagDecl>(parent_decl)) {
  225. auto class_inst_id =
  226. LookupClangDeclInstId(context, SemIR::ClangDeclKey(tag_decl));
  227. CARBON_CHECK(class_inst_id.has_value());
  228. auto class_inst = context.insts().Get(class_inst_id);
  229. auto class_id = SemIR::ClassId::None;
  230. if (auto class_decl = class_inst.TryAs<SemIR::ClassDecl>()) {
  231. // Common case: the tag was imported as a new Carbon class.
  232. class_id = class_decl->class_id;
  233. } else {
  234. // Rare case: the tag was imported as an existing Carbon class. This
  235. // happens for C++ classes that get mapped to Carbon prelude types, such
  236. // as `std::string_view`.
  237. // TODO: In this case, should we import the C++ class declaration and use
  238. // it as the parent, rather than using the existing Carbon class?
  239. class_id = class_inst.As<SemIR::ClassType>().class_id;
  240. }
  241. return context.classes().Get(class_id).scope_id;
  242. }
  243. if (isa<clang::NamespaceDecl, clang::TranslationUnitDecl>(parent_decl)) {
  244. auto namespace_inst_id = LookupClangDeclInstId(
  245. context, SemIR::ClangDeclKey::ForNonFunctionDecl(parent_decl));
  246. CARBON_CHECK(namespace_inst_id.has_value());
  247. return context.insts()
  248. .GetAs<SemIR::Namespace>(namespace_inst_id)
  249. .name_scope_id;
  250. }
  251. CARBON_FATAL("Unexpected kind of parent {0}", parent_decl->getDeclKindName());
  252. }
  253. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  254. // the new Carbon namespace declaration `InstId`. If the declaration was already
  255. // imported, returns the mapped instruction.
  256. static auto ImportNamespaceDecl(Context& context,
  257. clang::NamespaceDecl* clang_decl)
  258. -> SemIR::InstId {
  259. auto key = SemIR::ClangDeclKey(clang_decl);
  260. // Check if the declaration is already mapped.
  261. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, key);
  262. existing_inst_id.has_value()) {
  263. return existing_inst_id;
  264. }
  265. auto result = AddImportNamespace(
  266. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  267. AddIdentifierName(context, clang_decl->getName()),
  268. GetParentNameScopeId(context, clang_decl),
  269. /*import_id=*/SemIR::InstId::None);
  270. context.name_scopes()
  271. .Get(result.name_scope_id)
  272. .set_clang_decl_context_id(
  273. context.clang_decls().Add({.key = key, .inst_id = result.inst_id}));
  274. return result.inst_id;
  275. }
  276. // Creates a class declaration for the given class name in the given scope.
  277. // Returns the `InstId` for the declaration.
  278. static auto BuildClassDecl(Context& context,
  279. SemIR::ImportIRInstId import_ir_inst_id,
  280. SemIR::NameScopeId parent_scope_id,
  281. SemIR::NameId name_id)
  282. -> std::tuple<SemIR::ClassId, SemIR::TypeInstId> {
  283. // Add the class declaration.
  284. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  285. .class_id = SemIR::ClassId::None,
  286. .decl_block_id = SemIR::InstBlockId::None};
  287. auto class_decl_id = AddPlaceholderImportedInstInNoBlock(
  288. context,
  289. MakeImportedLocIdAndInst(context, import_ir_inst_id, class_decl));
  290. SemIR::Class class_info = {
  291. {.name_id = name_id,
  292. .parent_scope_id = parent_scope_id,
  293. .generic_id = SemIR::GenericId::None,
  294. .first_param_node_id = Parse::NodeId::None,
  295. .last_param_node_id = Parse::NodeId::None,
  296. .pattern_block_id = SemIR::InstBlockId::None,
  297. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  298. .param_patterns_id = SemIR::InstBlockId::None,
  299. .is_extern = false,
  300. .extern_library_id = SemIR::LibraryNameId::None,
  301. .non_owning_decl_id = SemIR::InstId::None,
  302. .first_owning_decl_id = class_decl_id},
  303. {// `.self_type_id` depends on the ClassType, so is set below.
  304. .self_type_id = SemIR::TypeId::None,
  305. // TODO: Support Dynamic classes.
  306. // TODO: Support Final classes.
  307. .inheritance_kind = SemIR::Class::Base}};
  308. class_decl.class_id = context.classes().Add(class_info);
  309. // Write the class ID into the ClassDecl.
  310. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  311. SetClassSelfType(context, class_decl.class_id);
  312. return {class_decl.class_id, context.types().GetAsTypeInstId(class_decl_id)};
  313. }
  314. // Imports a tag declaration from Clang to Carbon. This covers classes (which
  315. // includes structs and unions) as well as enums. If successful, returns the new
  316. // Carbon class declaration `InstId`.
  317. static auto ImportTagDecl(Context& context, clang::TagDecl* clang_decl)
  318. -> SemIR::InstId {
  319. auto import_ir_inst_id =
  320. AddImportIRInst(context.sem_ir(), clang_decl->getLocation());
  321. auto [class_id, class_inst_id] = BuildClassDecl(
  322. context, import_ir_inst_id, GetParentNameScopeId(context, clang_decl),
  323. AddIdentifierName(context, clang_decl->getName()));
  324. // TODO: The caller does the same lookup. Avoid doing it twice.
  325. auto key = SemIR::ClangDeclKey(clang_decl);
  326. auto clang_decl_id =
  327. context.clang_decls().Add({.key = key, .inst_id = class_inst_id});
  328. // Name lookup into the Carbon class looks in the C++ class definition.
  329. auto& class_info = context.classes().Get(class_id);
  330. class_info.scope_id = context.name_scopes().Add(
  331. class_inst_id, SemIR::NameId::None, class_info.parent_scope_id);
  332. context.name_scopes()
  333. .Get(class_info.scope_id)
  334. .set_clang_decl_context_id(clang_decl_id);
  335. return class_inst_id;
  336. }
  337. // Determines the Carbon inheritance kind to use for a C++ class definition.
  338. static auto GetInheritanceKind(clang::CXXRecordDecl* class_def)
  339. -> SemIR::Class::InheritanceKind {
  340. if (class_def->isUnion()) {
  341. // Treat all unions as final classes to match their C++ semantics. While we
  342. // could support this, the author of a C++ union has no way to mark their
  343. // type as `final` to prevent it, and so we assume the intent was to
  344. // disallow inheritance.
  345. return SemIR::Class::Final;
  346. }
  347. if (class_def->hasAttr<clang::FinalAttr>()) {
  348. // The class is final in C++; don't allow Carbon types to derive from it.
  349. // Note that such a type might also be abstract in C++; we treat final as
  350. // taking precedence.
  351. //
  352. // We could also treat classes with a final destructor as being final, as
  353. // Clang does when determining whether a class is "effectively final", but
  354. // to keep our rules simpler we do not.
  355. return SemIR::Class::Final;
  356. }
  357. if (class_def->getNumVBases()) {
  358. // TODO: We treat classes with virtual bases as final for now. We use the
  359. // layout of the class including its virtual bases as its Carbon type
  360. // layout, so we wouldn't behave correctly if we derived from it.
  361. return SemIR::Class::Final;
  362. }
  363. if (class_def->isAbstract()) {
  364. // If the class has any abstract members, it's abstract.
  365. return SemIR::Class::Abstract;
  366. }
  367. // Allow inheritance from any other C++ class type.
  368. return SemIR::Class::Base;
  369. }
  370. // Checks that the specified finished class definition is valid and builds and
  371. // returns a corresponding complete type witness instruction.
  372. static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id,
  373. SemIR::ImportIRInstId import_ir_inst_id,
  374. SemIR::TypeInstId class_type_inst_id,
  375. const clang::CXXRecordDecl* clang_def)
  376. -> SemIR::TypeInstId {
  377. if (clang_def->isInvalidDecl()) {
  378. // Clang already diagnosed this error.
  379. return SemIR::ErrorInst::TypeInstId;
  380. }
  381. // For now, if the class is empty, produce an empty struct as the object
  382. // representation. This allows our tests to continue to pass while we don't
  383. // properly support initializing imported C++ classes.
  384. // TODO: Remove this.
  385. if (clang_def->isEmpty() && !clang_def->getNumBases()) {
  386. return context.types().GetAsTypeInstId(AddInst(
  387. context,
  388. MakeImportedLocIdAndInst(
  389. context, import_ir_inst_id,
  390. SemIR::StructType{.type_id = SemIR::TypeType::TypeId,
  391. .fields_id = SemIR::StructTypeFieldsId::Empty})));
  392. }
  393. const auto& clang_layout =
  394. context.ast_context().getASTRecordLayout(clang_def);
  395. llvm::SmallVector<uint64_t> layout;
  396. llvm::SmallVector<SemIR::StructTypeField> fields;
  397. static_assert(SemIR::CustomLayoutId::SizeIndex == 0);
  398. layout.push_back(clang_layout.getSize().getQuantity());
  399. static_assert(SemIR::CustomLayoutId::AlignIndex == 1);
  400. layout.push_back(clang_layout.getAlignment().getQuantity());
  401. static_assert(SemIR::CustomLayoutId::FirstFieldIndex == 2);
  402. // TODO: Import vptr(s).
  403. // The kind of base class we've picked so far. These are ordered in increasing
  404. // preference order.
  405. enum class BaseKind {
  406. None,
  407. Empty,
  408. NonEmpty,
  409. Polymorphic,
  410. };
  411. BaseKind base_kind = BaseKind::None;
  412. // Import bases.
  413. for (const auto& base : clang_def->bases()) {
  414. if (base.isVirtual()) {
  415. // If the base is virtual, skip it from the layout. We don't know where it
  416. // will actually appear within the complete object layout, as a pointer to
  417. // this class might point to a derived type that puts the vbase in a
  418. // different place.
  419. // TODO: Track that the virtual base existed. Support derived-to-vbase
  420. // conversions by generating a clang AST fragment.
  421. continue;
  422. }
  423. auto [base_type_inst_id, base_type_id] =
  424. ImportCppType(context, import_ir_inst_id, base.getType());
  425. if (!base_type_id.has_value()) {
  426. // TODO: If the base class's type can't be mapped, skip it.
  427. continue;
  428. }
  429. auto base_decl_id = AddInst(
  430. context,
  431. MakeImportedLocIdAndInst(
  432. context, import_ir_inst_id,
  433. SemIR::BaseDecl{.type_id = GetUnboundElementType(
  434. context, class_type_inst_id, base_type_inst_id),
  435. .base_type_inst_id = base_type_inst_id,
  436. .index = SemIR::ElementIndex(fields.size())}));
  437. auto* base_class = base.getType()->getAsCXXRecordDecl();
  438. CARBON_CHECK(base_class, "Base class {0} is not a class",
  439. base.getType().getAsString());
  440. // If there's a unique "best" base class, treat it as a Carbon base class
  441. // too.
  442. // TODO: Improve handling for the case where the class has multiple base
  443. // classes.
  444. BaseKind kind = base_class->isPolymorphic() ? BaseKind::Polymorphic
  445. : base_class->isEmpty() ? BaseKind::Empty
  446. : BaseKind::NonEmpty;
  447. auto& class_info = context.classes().Get(class_id);
  448. if (kind > base_kind) {
  449. // This base is better than the previous best.
  450. class_info.base_id = base_decl_id;
  451. base_kind = kind;
  452. } else if (kind == base_kind) {
  453. // Multiple base classes of this kind: no unique best.
  454. class_info.base_id = SemIR::InstId::None;
  455. }
  456. // TODO: If the base class has virtual bases, the size of the type that we
  457. // add to the layout here will be the full size of the class (including
  458. // virtual bases), whereas the size actually occupied by this base class is
  459. // only the nvsize (excluding virtual bases).
  460. auto base_offset = base.isVirtual()
  461. ? clang_layout.getVBaseClassOffset(base_class)
  462. : clang_layout.getBaseClassOffset(base_class);
  463. layout.push_back(base_offset.getQuantity());
  464. fields.push_back(
  465. {.name_id = SemIR::NameId::Base, .type_inst_id = base_type_inst_id});
  466. }
  467. // Import fields.
  468. for (auto* decl : clang_def->decls()) {
  469. auto* field = dyn_cast<clang::FieldDecl>(decl);
  470. // Track the chain of fields from the class to this field. This chain is
  471. // only one element long unless the field is a member of an anonymous struct
  472. // or union.
  473. clang::NamedDecl* single_field_chain[1] = {field};
  474. llvm::ArrayRef<clang::NamedDecl*> chain = single_field_chain;
  475. // If this isn't a field, it might be an indirect field in an anonymous
  476. // struct or union.
  477. if (!field) {
  478. auto* indirect_field = dyn_cast<clang::IndirectFieldDecl>(decl);
  479. if (!indirect_field) {
  480. continue;
  481. }
  482. chain = indirect_field->chain();
  483. field = indirect_field->getAnonField();
  484. }
  485. if (field->isBitField()) {
  486. // TODO: Add a representation for named bitfield members.
  487. continue;
  488. }
  489. if (field->isAnonymousStructOrUnion()) {
  490. // Fields within an anonymous structure or union will be added via their
  491. // IndirectFieldDecls.
  492. continue;
  493. }
  494. auto field_name_id = AddIdentifierName(context, field->getName());
  495. auto [field_type_inst_id, field_type_id] =
  496. ImportCppType(context, import_ir_inst_id, field->getType());
  497. if (!field_type_inst_id.has_value()) {
  498. // TODO: For now, just skip over fields whose types we can't map.
  499. continue;
  500. }
  501. // Create a field now, as we know the index to use.
  502. // TODO: Consider doing this lazily instead.
  503. auto field_decl_id = AddInst(
  504. context, MakeImportedLocIdAndInst(
  505. context, import_ir_inst_id,
  506. SemIR::FieldDecl{
  507. .type_id = GetUnboundElementType(
  508. context, class_type_inst_id, field_type_inst_id),
  509. .name_id = field_name_id,
  510. .index = SemIR::ElementIndex(fields.size())}));
  511. // The imported SemIR::FieldDecl represents the original declaration `decl`,
  512. // which is either the field or the indirect field declaration.
  513. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(decl);
  514. context.clang_decls().Add({.key = key, .inst_id = field_decl_id});
  515. // Compute the offset to the field that appears directly in the class.
  516. uint64_t offset = clang_layout.getFieldOffset(
  517. cast<clang::FieldDecl>(chain.front())->getFieldIndex());
  518. // If this is an indirect field, walk the path and accumulate the offset to
  519. // the named field.
  520. for (auto* inner_decl : chain.drop_front()) {
  521. auto* inner_field = cast<clang::FieldDecl>(inner_decl);
  522. const auto& inner_layout =
  523. context.ast_context().getASTRecordLayout(inner_field->getParent());
  524. offset += inner_layout.getFieldOffset(inner_field->getFieldIndex());
  525. }
  526. layout.push_back(
  527. context.ast_context().toCharUnitsFromBits(offset).getQuantity());
  528. fields.push_back(
  529. {.name_id = field_name_id, .type_inst_id = field_type_inst_id});
  530. }
  531. // TODO: Add a field to prevent tail padding reuse if necessary.
  532. return AddTypeInst(context,
  533. MakeImportedLocIdAndInst<SemIR::CustomLayoutType>(
  534. context, import_ir_inst_id,
  535. {.type_id = SemIR::TypeType::TypeId,
  536. .fields_id = context.struct_type_fields().Add(fields),
  537. .layout_id = context.custom_layouts().Add(layout)}));
  538. }
  539. // Creates a Carbon class definition based on the information in the given Clang
  540. // class declaration, which is assumed to be for a class definition.
  541. static auto BuildClassDefinition(Context& context,
  542. SemIR::ImportIRInstId import_ir_inst_id,
  543. SemIR::ClassId class_id,
  544. SemIR::TypeInstId class_inst_id,
  545. clang::CXXRecordDecl* clang_def) -> void {
  546. auto& class_info = context.classes().Get(class_id);
  547. CARBON_CHECK(!class_info.has_definition_started());
  548. class_info.definition_id = class_inst_id;
  549. context.inst_block_stack().Push();
  550. class_info.inheritance_kind = GetInheritanceKind(clang_def);
  551. // Compute the class's object representation.
  552. auto object_repr_id = ImportClassObjectRepr(
  553. context, class_id, import_ir_inst_id, class_inst_id, clang_def);
  554. class_info.complete_type_witness_id = AddInst(
  555. context,
  556. MakeImportedLocIdAndInst<SemIR::CompleteTypeWitness>(
  557. context, import_ir_inst_id,
  558. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  559. .object_repr_type_inst_id = object_repr_id}));
  560. class_info.body_block_id = context.inst_block_stack().Pop();
  561. }
  562. // Computes and returns the Carbon type to use as the object representation of
  563. // the given C++ enum type. This is a builtin int type matching the enum's
  564. // representation.
  565. static auto ImportEnumObjectRepresentation(
  566. Context& context, SemIR::ImportIRInstId import_ir_inst_id,
  567. clang::EnumDecl* enum_decl) -> SemIR::TypeInstId {
  568. auto int_type = enum_decl->getIntegerType();
  569. CARBON_CHECK(!int_type.isNull(), "incomplete enum type {0}",
  570. enum_decl->getNameAsString());
  571. auto int_kind = int_type->isSignedIntegerType() ? SemIR::IntKind::Signed
  572. : SemIR::IntKind::Unsigned;
  573. auto bit_width_id = GetOrAddInst(
  574. context, MakeImportedLocIdAndInst<SemIR::IntValue>(
  575. context, import_ir_inst_id,
  576. {.type_id = GetSingletonType(
  577. context, SemIR::IntLiteralType::TypeInstId),
  578. .int_id = context.ints().AddUnsigned(llvm::APInt(
  579. 64, context.ast_context().getIntWidth(int_type)))}));
  580. return context.types().GetAsTypeInstId(
  581. GetOrAddInst(context, SemIR::LocIdAndInst::NoLoc(SemIR::IntType{
  582. .type_id = SemIR::TypeType::TypeId,
  583. .int_kind = int_kind,
  584. .bit_width_id = bit_width_id})));
  585. }
  586. // Creates a Carbon class definition based on the information in the given Clang
  587. // enum declaration.
  588. static auto BuildEnumDefinition(Context& context,
  589. SemIR::ImportIRInstId import_ir_inst_id,
  590. SemIR::ClassId class_id,
  591. SemIR::TypeInstId class_inst_id,
  592. clang::EnumDecl* enum_decl) -> void {
  593. auto& class_info = context.classes().Get(class_id);
  594. CARBON_CHECK(!class_info.has_definition_started());
  595. class_info.definition_id = class_inst_id;
  596. context.inst_block_stack().Push();
  597. // Don't allow inheritance from C++ enums, to match the behavior in C++.
  598. class_info.inheritance_kind = SemIR::Class::Final;
  599. // Compute the enum type's object representation. An enum is an adapter for
  600. // the corresponding builtin integer type.
  601. auto object_repr_id =
  602. ImportEnumObjectRepresentation(context, import_ir_inst_id, enum_decl);
  603. class_info.adapt_id = AddInst(
  604. context, MakeImportedLocIdAndInst(
  605. context, import_ir_inst_id,
  606. SemIR::AdaptDecl{.adapted_type_inst_id = object_repr_id}));
  607. class_info.complete_type_witness_id = AddInst(
  608. context,
  609. MakeImportedLocIdAndInst<SemIR::CompleteTypeWitness>(
  610. context, import_ir_inst_id,
  611. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  612. .object_repr_type_inst_id = object_repr_id}));
  613. class_info.body_block_id = context.inst_block_stack().Pop();
  614. }
  615. // Imports an enumerator declaration from Clang to Carbon.
  616. static auto ImportEnumConstantDecl(Context& context,
  617. clang::EnumConstantDecl* enumerator_decl)
  618. -> SemIR::InstId {
  619. auto key = SemIR::ClangDeclKey(enumerator_decl);
  620. CARBON_CHECK(!IsClangDeclImported(context, key));
  621. // Find the enclosing enum type.
  622. auto enum_key = SemIR::ClangDeclKey(
  623. cast<clang::EnumDecl>(enumerator_decl->getDeclContext()));
  624. auto type_inst_id = LookupClangDeclInstId(context, enum_key);
  625. auto type_id = context.types().GetTypeIdForTypeInstId(type_inst_id);
  626. // Build a corresponding IntValue.
  627. auto int_id = context.ints().Add(enumerator_decl->getInitVal());
  628. auto import_ir_inst_id =
  629. AddImportIRInst(context.sem_ir(), enumerator_decl->getLocation());
  630. auto inst_id = AddInstInNoBlock(
  631. context,
  632. MakeImportedLocIdAndInst<SemIR::IntValue>(
  633. context, import_ir_inst_id, {.type_id = type_id, .int_id = int_id}));
  634. context.imports().push_back(inst_id);
  635. context.clang_decls().Add({.key = key, .inst_id = inst_id});
  636. return inst_id;
  637. }
  638. // Mark the given `key` as failed in `clang_decls`.
  639. static auto MarkFailedDecl(Context& context, SemIR::ClangDeclKey key) {
  640. context.clang_decls().Add({.key = key, .inst_id = SemIR::ErrorInst::InstId});
  641. }
  642. // Creates an integer type of the given size.
  643. static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
  644. -> TypeExpr {
  645. auto type_inst_id = MakeIntTypeLiteral(
  646. context, Parse::NodeId::None,
  647. is_signed ? SemIR::IntKind::Signed : SemIR::IntKind::Unsigned, size_id);
  648. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  649. }
  650. static auto MakeCppCompatType(Context& context, SemIR::LocId loc_id,
  651. CoreIdentifier name) -> TypeExpr {
  652. return ExprAsType(
  653. context, loc_id,
  654. LookupNameInCore(context, loc_id, {CoreIdentifier::CppCompat, name}));
  655. }
  656. // Maps a C++ builtin integer type to a Carbon `Core.CppCompat` type.
  657. static auto MapBuiltinCppCompatIntegerType(Context& context,
  658. unsigned int cpp_width,
  659. unsigned int carbon_width,
  660. CoreIdentifier cpp_compat_name)
  661. -> TypeExpr {
  662. if (cpp_width != carbon_width) {
  663. return TypeExpr::None;
  664. }
  665. return MakeCppCompatType(context, Parse::NodeId::None, cpp_compat_name);
  666. }
  667. // Maps a C++ builtin integer type to a Carbon type.
  668. // TODO: Handle integer types that map to named aliases.
  669. static auto MapBuiltinIntegerType(Context& context, SemIR::LocId loc_id,
  670. clang::QualType qual_type,
  671. const clang::BuiltinType& type) -> TypeExpr {
  672. clang::ASTContext& ast_context = context.ast_context();
  673. unsigned width = ast_context.getIntWidth(qual_type);
  674. bool is_signed = type.isSignedInteger();
  675. auto int_n_type = ast_context.getIntTypeForBitwidth(width, is_signed);
  676. if (clang::ASTContext::hasSameType(qual_type, int_n_type)) {
  677. TypeExpr type_expr =
  678. MakeIntType(context, context.ints().Add(width), is_signed);
  679. // Try to make sure integer types of 32 or 64 bits are complete so we can
  680. // check against them when deciding whether we need to generate a thunk.
  681. if (width == 32 || width == 64) {
  682. SemIR::TypeId type_id = type_expr.type_id;
  683. if (!context.types().IsComplete(type_id)) {
  684. TryToCompleteType(context, type_id, loc_id);
  685. }
  686. }
  687. return type_expr;
  688. }
  689. if (clang::ASTContext::hasSameType(qual_type, ast_context.CharTy)) {
  690. return ExprAsType(context, Parse::NodeId::None,
  691. MakeCharTypeLiteral(context, Parse::NodeId::None));
  692. }
  693. if (clang::ASTContext::hasSameType(qual_type, ast_context.LongTy)) {
  694. return MapBuiltinCppCompatIntegerType(context, width, 32,
  695. CoreIdentifier::Long32);
  696. }
  697. if (clang::ASTContext::hasSameType(qual_type, ast_context.UnsignedLongTy)) {
  698. return MapBuiltinCppCompatIntegerType(context, width, 32,
  699. CoreIdentifier::ULong32);
  700. }
  701. if (clang::ASTContext::hasSameType(qual_type, ast_context.LongLongTy)) {
  702. return MapBuiltinCppCompatIntegerType(context, width, 64,
  703. CoreIdentifier::LongLong64);
  704. }
  705. if (clang::ASTContext::hasSameType(qual_type,
  706. ast_context.UnsignedLongLongTy)) {
  707. return MapBuiltinCppCompatIntegerType(context, width, 64,
  708. CoreIdentifier::ULongLong64);
  709. }
  710. return TypeExpr::None;
  711. }
  712. static auto MapNullptrType(Context& context, SemIR::LocId loc_id) -> TypeExpr {
  713. return MakeCppCompatType(context, loc_id, CoreIdentifier::NullptrT);
  714. }
  715. // Maps a C++ builtin type to a Carbon type.
  716. // TODO: Support more builtin types.
  717. static auto MapBuiltinType(Context& context, SemIR::LocId loc_id,
  718. clang::QualType qual_type,
  719. const clang::BuiltinType& type) -> TypeExpr {
  720. clang::ASTContext& ast_context = context.ast_context();
  721. if (type.isBooleanType()) {
  722. CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.BoolTy));
  723. return ExprAsType(context, Parse::NodeId::None,
  724. context.types().GetTypeInstId(GetSingletonType(
  725. context, SemIR::BoolType::TypeInstId)));
  726. }
  727. if (type.isInteger()) {
  728. return MapBuiltinIntegerType(context, loc_id, qual_type, type);
  729. }
  730. if (type.isFloatingPoint()) {
  731. if (type.isFloat16Type() || type.isFloat32Type() || type.isDoubleType() ||
  732. type.isFloat128Type()) {
  733. return ExprAsType(
  734. context, Parse::NodeId::None,
  735. MakeFloatTypeLiteral(
  736. context, Parse::NodeId::None,
  737. context.ints().Add(ast_context.getTypeSize(qual_type))));
  738. }
  739. // TODO: Handle floating-point types that map to named aliases.
  740. } else if (type.isVoidType()) {
  741. return MakeCppCompatType(context, loc_id, CoreIdentifier::VoidBase);
  742. } else if (type.isNullPtrType()) {
  743. return MapNullptrType(context, loc_id);
  744. }
  745. return TypeExpr::None;
  746. }
  747. // Determines whether record_decl is a C++ class that has a custom mapping into
  748. // Carbon, and if so, returns the corresponding Carbon type. Otherwise returns
  749. // None.
  750. static auto LookupCustomRecordType(Context& context,
  751. const clang::CXXRecordDecl* record_decl)
  752. -> TypeExpr {
  753. switch (GetCustomCppTypeMapping(record_decl)) {
  754. case CustomCppTypeMapping::None:
  755. return TypeExpr::None;
  756. case CustomCppTypeMapping::Str:
  757. return MakeStringType(
  758. context,
  759. AddImportIRInst(context.sem_ir(), record_decl->getLocation()));
  760. }
  761. }
  762. // Maps a C++ tag type (class, struct, union, enum) to a Carbon type.
  763. static auto MapTagType(Context& context, const clang::TagType& type)
  764. -> TypeExpr {
  765. auto* tag_decl = type.getDecl();
  766. CARBON_CHECK(tag_decl);
  767. // Check if the declaration is already mapped.
  768. auto key = SemIR::ClangDeclKey(tag_decl);
  769. SemIR::InstId tag_inst_id = LookupClangDeclInstId(context, key);
  770. if (!tag_inst_id.has_value()) {
  771. if (auto* record_decl = dyn_cast<clang::CXXRecordDecl>(tag_decl)) {
  772. auto custom_type = LookupCustomRecordType(context, record_decl);
  773. if (custom_type.inst_id.has_value()) {
  774. context.clang_decls().Add({.key = key, .inst_id = custom_type.inst_id});
  775. return custom_type;
  776. }
  777. }
  778. tag_inst_id = ImportTagDecl(context, tag_decl);
  779. }
  780. SemIR::TypeInstId record_type_inst_id =
  781. context.types().GetAsTypeInstId(tag_inst_id);
  782. return {
  783. // TODO: inst_id's location should be the location of the usage, not
  784. // the location of the type definition. Possibly we should synthesize a
  785. // NameRef inst, to match how this would work in Carbon code.
  786. .inst_id = record_type_inst_id,
  787. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  788. }
  789. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  790. // type.
  791. // TODO: Support more types.
  792. static auto MapNonWrapperType(Context& context, SemIR::LocId loc_id,
  793. clang::QualType type) -> TypeExpr {
  794. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  795. return MapBuiltinType(context, loc_id, type, *builtin_type);
  796. }
  797. if (const auto* tag_type = type->getAs<clang::TagType>()) {
  798. return MapTagType(context, *tag_type);
  799. }
  800. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  801. "Should not see wrapper types here");
  802. return TypeExpr::None;
  803. }
  804. // Maps a qualified C++ type to a Carbon type.
  805. static auto MapQualifiedType(Context& context, clang::QualType type,
  806. TypeExpr type_expr) -> TypeExpr {
  807. auto quals = type.getQualifiers();
  808. if (quals.hasConst()) {
  809. auto type_id = GetConstType(context, type_expr.inst_id);
  810. type_expr = TypeExpr::ForUnsugared(context, type_id);
  811. quals.removeConst();
  812. }
  813. // TODO: Support other qualifiers.
  814. if (!quals.empty()) {
  815. return TypeExpr::None;
  816. }
  817. return type_expr;
  818. }
  819. // Returns true if the type has the `_Nonnull` attribute.
  820. static auto IsClangTypeNonNull(clang::QualType type) -> bool {
  821. auto nullability = type->getNullability();
  822. return nullability.has_value() &&
  823. *nullability == clang::NullabilityKind::NonNull;
  824. }
  825. // Like `clang::QualType::getUnqualifiedType()`, retrieves the unqualified
  826. // variant of the given type, but preserves `_Nonnull`.
  827. static auto ClangGetUnqualifiedTypePreserveNonNull(
  828. Context& context, clang::QualType original_type) -> clang::QualType {
  829. clang::QualType type = original_type.getUnqualifiedType();
  830. // Preserve non-nullability.
  831. if (IsClangTypeNonNull(original_type) && !IsClangTypeNonNull(type)) {
  832. type = context.ast_context().getAttributedType(
  833. clang::NullabilityKind::NonNull, type, type);
  834. }
  835. return type;
  836. }
  837. // Returns the type `Core.Optional(T)`, where `T` is described by
  838. // `inner_type_inst_id`.
  839. static auto MakeOptionalType(Context& context, SemIR::LocId loc_id,
  840. SemIR::InstId inner_type_inst_id) -> TypeExpr {
  841. auto fn_inst_id = LookupNameInCore(context, loc_id, CoreIdentifier::Optional);
  842. auto call_id = PerformCall(context, loc_id, fn_inst_id, {inner_type_inst_id});
  843. return ExprAsType(context, loc_id, call_id);
  844. }
  845. // Maps a C++ pointer type to a Carbon pointer type.
  846. static auto MapPointerType(Context& context, SemIR::LocId loc_id,
  847. clang::QualType type, TypeExpr pointee_type_expr)
  848. -> TypeExpr {
  849. CARBON_CHECK(type->isPointerType());
  850. bool optional =
  851. !IsClangTypeNonNull(type) &&
  852. // If the type was produced by C++ template substitution, then we assume
  853. // it was deduced from a Carbon pointer type, so it's non-null.
  854. !type->getAs<clang::SubstTemplateTypeParmType>();
  855. TypeExpr pointer_type_expr = TypeExpr::ForUnsugared(
  856. context, GetPointerType(context, pointee_type_expr.inst_id));
  857. if (optional) {
  858. pointer_type_expr =
  859. MakeOptionalType(context, loc_id, pointer_type_expr.inst_id);
  860. }
  861. return pointer_type_expr;
  862. }
  863. // Maps a C++ reference type to a Carbon type. We map all references to
  864. // pointers for now. Note that when mapping function parameters and return
  865. // types, a different rule is used; see MapParameterType for details.
  866. // TODO: Revisit this and decide what we really want to do here.
  867. static auto MapReferenceType(Context& context, clang::QualType type,
  868. TypeExpr referenced_type_expr) -> TypeExpr {
  869. CARBON_CHECK(type->isReferenceType());
  870. SemIR::TypeId pointer_type_id =
  871. GetPointerType(context, referenced_type_expr.inst_id);
  872. pointer_type_id =
  873. GetConstType(context, context.types().GetTypeInstId(pointer_type_id));
  874. return TypeExpr::ForUnsugared(context, pointer_type_id);
  875. }
  876. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  877. // we check for pointer nullability and nullability will be lost by
  878. // canonicalization.
  879. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  880. -> TypeExpr {
  881. // Unwrap any type modifiers and wrappers.
  882. llvm::SmallVector<clang::QualType> wrapper_types;
  883. while (true) {
  884. clang::QualType orig_type = type;
  885. if (type.hasQualifiers()) {
  886. type = ClangGetUnqualifiedTypePreserveNonNull(context, type);
  887. } else if (type->isPointerType()) {
  888. type = type->getPointeeType();
  889. } else if (type->isReferenceType()) {
  890. type = type.getNonReferenceType();
  891. } else {
  892. break;
  893. }
  894. wrapper_types.push_back(orig_type);
  895. }
  896. auto mapped = MapNonWrapperType(context, loc_id, type);
  897. for (auto wrapper : llvm::reverse(wrapper_types)) {
  898. if (!mapped.inst_id.has_value() ||
  899. mapped.type_id == SemIR::ErrorInst::TypeId) {
  900. break;
  901. }
  902. if (wrapper.hasQualifiers()) {
  903. mapped = MapQualifiedType(context, wrapper, mapped);
  904. } else if (wrapper->isPointerType()) {
  905. mapped = MapPointerType(context, loc_id, wrapper, mapped);
  906. } else if (wrapper->isReferenceType()) {
  907. mapped = MapReferenceType(context, wrapper, mapped);
  908. } else {
  909. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  910. }
  911. }
  912. return mapped;
  913. }
  914. namespace {
  915. // Information about how to map a C++ parameter type into Carbon.
  916. struct ParameterTypeInfo {
  917. // The type to use for the Carbon parameter.
  918. TypeExpr type;
  919. // Whether to build a `ref` pattern.
  920. bool want_ref_pattern;
  921. };
  922. } // namespace
  923. // Given the type of a C++ function parameter, returns information about the
  924. // type to use for the corresponding Carbon parameter.
  925. //
  926. // Note that if the parameter has a type for which `IsSimpleAbiType` returns
  927. // true, we must produce a parameter type that has the same calling convention
  928. // as the C++ type.
  929. static auto MapParameterType(Context& context, SemIR::LocId loc_id,
  930. clang::QualType param_type) -> ParameterTypeInfo {
  931. ParameterTypeInfo info = {.type = TypeExpr::None, .want_ref_pattern = false};
  932. // Perform some custom mapping for parameters of reference type:
  933. //
  934. // * `T& x` -> `ref x: T`.
  935. // * `const T& x` -> `x: T`.
  936. // * `T&& x` -> `x: T`.
  937. //
  938. // TODO: For the `&&` mapping, we allow an rvalue reference to bind to a
  939. // durable reference expression. This should not be allowed.
  940. if (param_type->isReferenceType()) {
  941. clang::QualType pointee_type = param_type->getPointeeType();
  942. if (param_type->isLValueReferenceType()) {
  943. if (pointee_type.isConstQualified()) {
  944. // TODO: Consider only doing this if `const` is the only qualifier. For
  945. // now, any other qualifier will fail when mapping the type.
  946. auto split_type = pointee_type.getSplitUnqualifiedType();
  947. split_type.Quals.removeConst();
  948. pointee_type = context.ast_context().getQualifiedType(split_type);
  949. } else {
  950. // The reference will map to a `ref` pattern.
  951. info.want_ref_pattern = true;
  952. }
  953. }
  954. param_type = pointee_type;
  955. }
  956. info.type = MapType(context, loc_id, param_type);
  957. return info;
  958. }
  959. // Returns a block for the implicit parameters of the given function
  960. // declaration. Because function templates are not yet supported, this currently
  961. // only contains the `self` parameter. On error, produces a diagnostic and
  962. // returns None.
  963. static auto MakeImplicitParamPatternsBlockId(
  964. Context& context, SemIR::LocId loc_id,
  965. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  966. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  967. if (!method_decl || method_decl->isStatic() ||
  968. isa<clang::CXXConstructorDecl>(clang_decl)) {
  969. return SemIR::InstBlockId::Empty;
  970. }
  971. // Build a `self` parameter from the object parameter.
  972. BeginSubpattern(context);
  973. clang::QualType param_type =
  974. method_decl->getFunctionObjectParameterReferenceType();
  975. auto param_info = MapParameterType(context, loc_id, param_type);
  976. auto [type_inst_id, type_id] = param_info.type;
  977. SemIR::ExprRegionId type_expr_region_id =
  978. EndSubpatternAsExpr(context, type_inst_id);
  979. if (!type_id.has_value()) {
  980. context.TODO(loc_id,
  981. llvm::formatv("Unsupported: object parameter type: {0}",
  982. param_type.getAsString()));
  983. return SemIR::InstBlockId::None;
  984. }
  985. // TODO: Fill in a location once available.
  986. auto pattern_id = AddParamPattern(context, loc_id, SemIR::NameId::SelfValue,
  987. type_expr_region_id, type_id,
  988. param_info.want_ref_pattern);
  989. return context.inst_blocks().Add({pattern_id});
  990. }
  991. // Returns a block id for the explicit parameters of the given function
  992. // declaration. If the function declaration has no parameters, it returns
  993. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  994. // produces an error and returns `SemIR::InstBlockId::None`. `signature`
  995. // specifies how to convert the C++ signature to the Carbon signature.
  996. // TODO: Consider refactoring to extract and reuse more logic from
  997. // `HandleAnyBindingPattern()`.
  998. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  999. const clang::FunctionDecl& clang_decl,
  1000. SemIR::ClangDeclKey::Signature signature)
  1001. -> SemIR::InstBlockId {
  1002. llvm::SmallVector<SemIR::InstId> param_ids;
  1003. llvm::SmallVector<SemIR::InstId> param_type_ids;
  1004. param_ids.reserve(signature.num_params);
  1005. param_type_ids.reserve(signature.num_params);
  1006. CARBON_CHECK(static_cast<int>(clang_decl.getNumNonObjectParams()) >=
  1007. signature.num_params,
  1008. "Function has fewer parameters than requested: {0} < {1}",
  1009. clang_decl.getNumNonObjectParams(), signature.num_params);
  1010. const auto* function_type =
  1011. clang_decl.getType()->castAs<clang::FunctionProtoType>();
  1012. for (int i : llvm::seq(signature.num_params)) {
  1013. const auto* param = clang_decl.getNonObjectParameter(i);
  1014. clang::QualType orig_param_type = function_type->getParamType(
  1015. clang_decl.hasCXXExplicitFunctionObjectParameter() + i);
  1016. // The parameter type is decayed but hasn't necessarily had its qualifiers
  1017. // removed.
  1018. // TODO: The presence of qualifiers here is probably a Clang bug.
  1019. clang::QualType param_type =
  1020. ClangGetUnqualifiedTypePreserveNonNull(context, orig_param_type);
  1021. // Mark the start of a region of insts, needed for the type expression
  1022. // created later with the call of `EndSubpatternAsExpr()`.
  1023. BeginSubpattern(context);
  1024. auto param_info = MapParameterType(context, loc_id, param_type);
  1025. auto [type_inst_id, type_id] = param_info.type;
  1026. // Type expression of the binding pattern - a single-entry/single-exit
  1027. // region that allows control flow in the type expression e.g. fn F(x: if C
  1028. // then i32 else i64).
  1029. SemIR::ExprRegionId type_expr_region_id =
  1030. EndSubpatternAsExpr(context, type_inst_id);
  1031. if (!type_id.has_value()) {
  1032. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  1033. orig_param_type.getAsString()));
  1034. return SemIR::InstBlockId::None;
  1035. }
  1036. llvm::StringRef param_name = param->getName();
  1037. SemIR::NameId name_id =
  1038. param_name.empty()
  1039. // Translate an unnamed parameter to an underscore to
  1040. // match Carbon's naming of unnamed/unused function params.
  1041. ? SemIR::NameId::Underscore
  1042. : AddIdentifierName(context, param_name);
  1043. SemIR::LocId param_loc_id =
  1044. AddImportIRInst(context.sem_ir(), param->getLocation());
  1045. // TODO: Add template support.
  1046. SemIR::InstId pattern_id =
  1047. AddParamPattern(context, param_loc_id, name_id, type_expr_region_id,
  1048. type_id, param_info.want_ref_pattern);
  1049. param_ids.push_back(pattern_id);
  1050. param_type_ids.push_back(type_inst_id);
  1051. }
  1052. switch (signature.kind) {
  1053. case SemIR::ClangDeclKey::Signature::Normal: {
  1054. // Use the converted parameter list as-is.
  1055. break;
  1056. }
  1057. case SemIR::ClangDeclKey::Signature::TuplePattern: {
  1058. // Replace the parameters with a single tuple pattern containing the
  1059. // converted parameter list.
  1060. auto param_block_id = context.inst_blocks().Add(param_ids);
  1061. auto tuple_pattern_type_id =
  1062. GetPatternType(context, GetTupleType(context, param_type_ids));
  1063. SemIR::InstId pattern_id = AddPatternInst(
  1064. context,
  1065. SemIR::LocIdAndInst::UncheckedLoc(
  1066. loc_id, SemIR::TuplePattern{.type_id = tuple_pattern_type_id,
  1067. .elements_id = param_block_id}));
  1068. param_ids = {pattern_id};
  1069. break;
  1070. }
  1071. }
  1072. return context.inst_blocks().Add(param_ids);
  1073. }
  1074. // Returns the return `TypeExpr` of the given function declaration. In case of
  1075. // an unsupported return type, returns `SemIR::ErrorInst::InstId`. Constructors
  1076. // are treated as returning a class instance.
  1077. // TODO: Support more return types.
  1078. static auto GetReturnTypeExpr(Context& context, SemIR::LocId loc_id,
  1079. clang::FunctionDecl* clang_decl)
  1080. -> Context::FormExpr {
  1081. auto make_init_form = [&](SemIR::TypeInstId type_component_inst_id) {
  1082. SemIR::InitForm inst = {
  1083. .type_id = SemIR::FormType::TypeId,
  1084. .type_component_inst_id = type_component_inst_id,
  1085. .index = context.full_pattern_stack().NextCallParamIndex()};
  1086. return context.constant_values().GetInstId(TryEvalInst(context, inst));
  1087. };
  1088. auto make_ref_form = [&](SemIR::TypeInstId type_component_inst_id) {
  1089. SemIR::RefForm inst = {.type_id = SemIR::FormType::TypeId,
  1090. .type_component_inst_id = type_component_inst_id};
  1091. return context.constant_values().GetInstId(TryEvalInst(context, inst));
  1092. };
  1093. clang::QualType orig_ret_type = clang_decl->getReturnType();
  1094. if (!orig_ret_type->isVoidType()) {
  1095. bool is_reference = orig_ret_type->isReferenceType();
  1096. if (is_reference) {
  1097. orig_ret_type = orig_ret_type->getPointeeType();
  1098. }
  1099. // TODO: We should eventually map reference returns to non-pointer types
  1100. // here. We should return by `ref` for `T&` return types once `ref` return
  1101. // is implemented.
  1102. auto [orig_type_inst_id, type_id] = MapType(context, loc_id, orig_ret_type);
  1103. if (!orig_type_inst_id.has_value()) {
  1104. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  1105. orig_ret_type.getAsString()));
  1106. return {.form_inst_id = SemIR::ErrorInst::InstId,
  1107. .type_component_id = SemIR::ErrorInst::TypeInstId,
  1108. .type_id = SemIR::ErrorInst::TypeId};
  1109. }
  1110. Context::FormExpr result = {
  1111. .form_inst_id = is_reference ? make_ref_form(orig_type_inst_id)
  1112. : make_init_form(orig_type_inst_id),
  1113. .type_component_id = orig_type_inst_id,
  1114. .type_id = type_id};
  1115. return result;
  1116. }
  1117. auto* ctor = dyn_cast<clang::CXXConstructorDecl>(clang_decl);
  1118. if (!ctor) {
  1119. // void.
  1120. return {.form_inst_id = SemIR::InstId::None,
  1121. .type_component_id = SemIR::TypeInstId::None,
  1122. .type_id = SemIR::TypeId::None};
  1123. }
  1124. // TODO: Make this a `PartialType`.
  1125. SemIR::TypeInstId record_type_inst_id = context.types().GetAsTypeInstId(
  1126. LookupClangDeclInstId(context, SemIR::ClangDeclKey(ctor->getParent())));
  1127. return {
  1128. .form_inst_id = make_init_form(record_type_inst_id),
  1129. .type_component_id = record_type_inst_id,
  1130. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  1131. }
  1132. // Information about a function's declared return type, corresponding to the
  1133. // fields of SemIR::Function with the same names.
  1134. struct ReturnInfo {
  1135. SemIR::TypeInstId return_type_inst_id;
  1136. SemIR::InstId return_form_inst_id;
  1137. SemIR::InstBlockId return_patterns_id;
  1138. };
  1139. // Returns information about the declared return type of the given function
  1140. // declaration. In case of an unsupported return type, it produces a diagnostic,
  1141. // and the returned return_type_inst_id will be `SemIR::ErrorInst::InstId`.
  1142. // Constructors are treated as returning a class instance.
  1143. static auto GetReturnInfo(Context& context, SemIR::LocId loc_id,
  1144. clang::FunctionDecl* clang_decl) -> ReturnInfo {
  1145. auto [form_inst_id, type_inst_id, type_id] =
  1146. GetReturnTypeExpr(context, loc_id, clang_decl);
  1147. if (!form_inst_id.has_value()) {
  1148. // void.
  1149. return {.return_type_inst_id = SemIR::TypeInstId::None,
  1150. .return_form_inst_id = SemIR::InstId::None,
  1151. .return_patterns_id = SemIR::InstBlockId::None};
  1152. }
  1153. if (form_inst_id == SemIR::ErrorInst::InstId) {
  1154. return {.return_type_inst_id = SemIR::ErrorInst::TypeInstId,
  1155. .return_form_inst_id = SemIR::ErrorInst::InstId,
  1156. .return_patterns_id = SemIR::InstBlockId::None};
  1157. }
  1158. auto pattern_type_id = GetPatternType(context, type_id);
  1159. clang::SourceLocation return_type_loc =
  1160. clang_decl->getReturnTypeSourceRange().getBegin();
  1161. if (return_type_loc.isInvalid()) {
  1162. // TODO: While `getReturnTypeSourceRange()` should work, it seems broken for
  1163. // trailing return type. See
  1164. // https://github.com/llvm/llvm-project/issues/162649. Until this is fixed,
  1165. // we fallback to `getTypeSpecStartLoc()`.
  1166. return_type_loc = clang_decl->getTypeSpecStartLoc();
  1167. }
  1168. SemIR::ImportIRInstId return_type_import_ir_inst_id =
  1169. AddImportIRInst(context.sem_ir(), return_type_loc);
  1170. auto return_patterns_id = SemIR::InstBlockId::Empty;
  1171. if (auto init_form =
  1172. context.insts().TryGetAs<SemIR::InitForm>(form_inst_id)) {
  1173. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  1174. context, MakeImportedLocIdAndInst(
  1175. context, return_type_import_ir_inst_id,
  1176. SemIR::ReturnSlotPattern({.type_id = pattern_type_id,
  1177. .type_inst_id = type_inst_id})));
  1178. auto param_pattern_id = AddPatternInst(
  1179. context,
  1180. MakeImportedLocIdAndInst(
  1181. context, return_type_import_ir_inst_id,
  1182. SemIR::OutParamPattern({.type_id = pattern_type_id,
  1183. .subpattern_id = return_slot_pattern_id,
  1184. .index = init_form->index})));
  1185. return_patterns_id = context.inst_blocks().Add({param_pattern_id});
  1186. }
  1187. return {.return_type_inst_id = type_inst_id,
  1188. .return_form_inst_id = form_inst_id,
  1189. .return_patterns_id = return_patterns_id};
  1190. }
  1191. namespace {
  1192. // Represents the insts and inst blocks associated with the parameters and
  1193. // returns of a function declaration, corresponding to the fields of
  1194. // SemIR::Function with the same names.
  1195. struct FunctionSignatureInsts {
  1196. SemIR::InstBlockId implicit_param_patterns_id;
  1197. SemIR::InstBlockId param_patterns_id;
  1198. SemIR::TypeInstId return_type_inst_id;
  1199. SemIR::InstId return_form_inst_id;
  1200. SemIR::InstBlockId return_patterns_id;
  1201. SemIR::InstBlockId call_param_patterns_id;
  1202. SemIR::InstBlockId call_params_id;
  1203. };
  1204. } // namespace
  1205. // Creates the insts and inst blocks that represent the parameters and returns
  1206. // of the given C++ function's Carbon counterpart, including emitting a callee
  1207. // pattern match to create the `Call` parameters, and returns a
  1208. // FunctionSignatureInsts containing the results. Produces a diagnostic and
  1209. // returns `std::nullopt` if the function declaration has an unsupported
  1210. // parameter type. `signature` specifies how to convert the C++ function
  1211. // signature to the Carbon function signature.
  1212. static auto CreateFunctionSignatureInsts(
  1213. Context& context, SemIR::LocId loc_id, clang::FunctionDecl* clang_decl,
  1214. SemIR::ClangDeclKey::Signature signature)
  1215. -> std::optional<FunctionSignatureInsts> {
  1216. context.full_pattern_stack().PushFullPattern(
  1217. FullPatternStack::Kind::ImplicitParamList);
  1218. std::optional pop = llvm::scope_exit(
  1219. [&context] { context.full_pattern_stack().PopFullPattern(); });
  1220. auto implicit_param_patterns_id =
  1221. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  1222. if (!implicit_param_patterns_id.has_value()) {
  1223. return std::nullopt;
  1224. }
  1225. context.full_pattern_stack().EndImplicitParamList();
  1226. auto param_patterns_id =
  1227. MakeParamPatternsBlockId(context, loc_id, *clang_decl, signature);
  1228. if (!param_patterns_id.has_value()) {
  1229. return std::nullopt;
  1230. }
  1231. auto [return_type_inst_id, return_form_inst_id, return_patterns_id] =
  1232. GetReturnInfo(context, loc_id, clang_decl);
  1233. if (return_type_inst_id == SemIR::ErrorInst::TypeInstId) {
  1234. return std::nullopt;
  1235. }
  1236. pop.reset();
  1237. auto [call_param_patterns_id, call_params_id] =
  1238. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  1239. return_patterns_id);
  1240. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  1241. .param_patterns_id = param_patterns_id,
  1242. .return_type_inst_id = return_type_inst_id,
  1243. .return_form_inst_id = return_form_inst_id,
  1244. .return_patterns_id = return_patterns_id,
  1245. .call_param_patterns_id = call_param_patterns_id,
  1246. .call_params_id = call_params_id}};
  1247. }
  1248. // Returns the Carbon function name for the given function.
  1249. static auto GetFunctionName(Context& context, clang::FunctionDecl* clang_decl)
  1250. -> SemIR::NameId {
  1251. switch (clang_decl->getDeclName().getNameKind()) {
  1252. case clang::DeclarationName::CXXConstructorName: {
  1253. auto key = SemIR::ClangDeclKey(
  1254. cast<clang::CXXConstructorDecl>(clang_decl)->getParent());
  1255. return context.classes()
  1256. .Get(context.insts()
  1257. .GetAs<SemIR::ClassDecl>(LookupClangDeclInstId(context, key))
  1258. .class_id)
  1259. .name_id;
  1260. }
  1261. case clang::DeclarationName::CXXDestructorName: {
  1262. return SemIR::NameId::CppDestructor;
  1263. }
  1264. case clang::DeclarationName::CXXOperatorName:
  1265. case clang::DeclarationName::CXXConversionFunctionName: {
  1266. return SemIR::NameId::CppOperator;
  1267. }
  1268. default: {
  1269. return AddIdentifierName(context, clang_decl->getName());
  1270. }
  1271. }
  1272. }
  1273. // Creates a `FunctionDecl` and a `Function` without C++ thunk information.
  1274. // Returns std::nullopt on failure.
  1275. //
  1276. // The given Clang declaration is assumed to:
  1277. // * Have not been imported before.
  1278. // * Be of supported type (ignoring parameters).
  1279. //
  1280. // `signature` specifies how to convert the C++ function signature to the Carbon
  1281. // function signature.
  1282. static auto ImportFunction(Context& context, SemIR::LocId loc_id,
  1283. SemIR::ImportIRInstId import_ir_inst_id,
  1284. clang::FunctionDecl* clang_decl,
  1285. SemIR::ClangDeclKey::Signature signature)
  1286. -> std::optional<SemIR::FunctionId> {
  1287. StartFunctionSignature(context);
  1288. auto function_params_insts =
  1289. CreateFunctionSignatureInsts(context, loc_id, clang_decl, signature);
  1290. auto [pattern_block_id, decl_block_id] = FinishFunctionSignature(context);
  1291. if (!function_params_insts.has_value()) {
  1292. return std::nullopt;
  1293. }
  1294. auto virtual_modifier = SemIR::Function::VirtualModifier::None;
  1295. int32_t virtual_index = -1;
  1296. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  1297. if (method_decl->size_overridden_methods()) {
  1298. virtual_modifier = SemIR::Function::VirtualModifier::Override;
  1299. } else if (method_decl->isVirtual()) {
  1300. virtual_modifier = SemIR::Function::VirtualModifier::Virtual;
  1301. }
  1302. if (virtual_modifier != SemIR::Function::VirtualModifier::None) {
  1303. // TODO: Add support for Microsoft/non-Itanium vtables.
  1304. virtual_index = dyn_cast<clang::ItaniumVTableContext>(
  1305. context.ast_context().getVTableContext())
  1306. ->getMethodVTableIndex(method_decl);
  1307. }
  1308. }
  1309. auto [decl_id, function_id] = MakeFunctionDecl(
  1310. context, import_ir_inst_id, decl_block_id, /*build_generic=*/false,
  1311. /*is_definition=*/false,
  1312. SemIR::Function{
  1313. {
  1314. .name_id = GetFunctionName(context, clang_decl),
  1315. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  1316. .generic_id = SemIR::GenericId::None,
  1317. .first_param_node_id = Parse::NodeId::None,
  1318. .last_param_node_id = Parse::NodeId::None,
  1319. .pattern_block_id = pattern_block_id,
  1320. .implicit_param_patterns_id =
  1321. function_params_insts->implicit_param_patterns_id,
  1322. .param_patterns_id = function_params_insts->param_patterns_id,
  1323. .is_extern = false,
  1324. .extern_library_id = SemIR::LibraryNameId::None,
  1325. .non_owning_decl_id = SemIR::InstId::None,
  1326. // Set by `MakeFunctionDecl`.
  1327. .first_owning_decl_id = SemIR::InstId::None,
  1328. },
  1329. {
  1330. .call_param_patterns_id =
  1331. function_params_insts->call_param_patterns_id,
  1332. .call_params_id = function_params_insts->call_params_id,
  1333. .return_type_inst_id = function_params_insts->return_type_inst_id,
  1334. .return_form_inst_id = function_params_insts->return_form_inst_id,
  1335. .return_patterns_id = function_params_insts->return_patterns_id,
  1336. .virtual_modifier = virtual_modifier,
  1337. .virtual_index = virtual_index,
  1338. .self_param_id = FindSelfPattern(
  1339. context, function_params_insts->implicit_param_patterns_id),
  1340. }});
  1341. context.imports().push_back(decl_id);
  1342. context.functions().Get(function_id).clang_decl_id =
  1343. context.clang_decls().Add(
  1344. {.key = SemIR::ClangDeclKey::ForFunctionDecl(clang_decl, signature),
  1345. .inst_id = decl_id});
  1346. return function_id;
  1347. }
  1348. // Imports a C++ function, returning a corresponding Carbon function.
  1349. // `signature` specifies how to convert the C++ function signature to the Carbon
  1350. // function signature. `signature.num_params` may be less than the number of
  1351. // parameters that the C++ function has if default arguments are available for
  1352. // the trailing parameters.
  1353. static auto ImportFunctionDecl(Context& context, SemIR::LocId loc_id,
  1354. clang::FunctionDecl* clang_decl,
  1355. SemIR::ClangDeclKey::Signature signature)
  1356. -> SemIR::InstId {
  1357. auto key = SemIR::ClangDeclKey::ForFunctionDecl(clang_decl, signature);
  1358. // Check if the declaration is already mapped.
  1359. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, key);
  1360. existing_inst_id.has_value()) {
  1361. return existing_inst_id;
  1362. }
  1363. if (clang_decl->isVariadic()) {
  1364. context.TODO(loc_id, "Unsupported: Variadic function");
  1365. MarkFailedDecl(context, key);
  1366. return SemIR::ErrorInst::InstId;
  1367. }
  1368. if (clang_decl->getTemplatedKind() ==
  1369. clang::FunctionDecl::TK_FunctionTemplate) {
  1370. context.TODO(loc_id, "Unsupported: Template function");
  1371. MarkFailedDecl(context, key);
  1372. return SemIR::ErrorInst::InstId;
  1373. }
  1374. auto import_ir_inst_id =
  1375. AddImportIRInst(context.sem_ir(), clang_decl->getLocation());
  1376. CARBON_CHECK(clang_decl->getFunctionType()->isFunctionProtoType(),
  1377. "Not Prototype function (non-C++ code)");
  1378. auto function_id =
  1379. ImportFunction(context, loc_id, import_ir_inst_id, clang_decl, signature);
  1380. if (!function_id) {
  1381. MarkFailedDecl(context, key);
  1382. return SemIR::ErrorInst::InstId;
  1383. }
  1384. SemIR::Function& function_info = context.functions().Get(*function_id);
  1385. if (IsCppThunkRequired(context, function_info)) {
  1386. Diagnostics::AnnotationScope annotate_diagnostics(
  1387. &context.emitter(), [&](auto& builder) {
  1388. CARBON_DIAGNOSTIC(InCppThunk, Note,
  1389. "in thunk for C++ function used here");
  1390. builder.Note(loc_id, InCppThunk);
  1391. });
  1392. if (clang::FunctionDecl* thunk_clang_decl =
  1393. BuildCppThunk(context, function_info)) {
  1394. if (auto thunk_function_id = ImportFunction(
  1395. context, loc_id, import_ir_inst_id, thunk_clang_decl,
  1396. {.num_params =
  1397. static_cast<int32_t>(thunk_clang_decl->getNumParams())})) {
  1398. SemIR::InstId thunk_function_decl_id =
  1399. context.functions().Get(*thunk_function_id).first_owning_decl_id;
  1400. function_info.SetHasCppThunk(thunk_function_decl_id);
  1401. }
  1402. }
  1403. } else {
  1404. // Inform Clang that the function has been referenced. This will trigger
  1405. // instantiation if needed.
  1406. context.clang_sema().MarkFunctionReferenced(GetCppLocation(context, loc_id),
  1407. clang_decl);
  1408. // If the function is trivial, mark it as being a builtin if possible.
  1409. if (clang_decl->isTrivial()) {
  1410. // Trivial destructors map to a "no_op" builtin.
  1411. if (isa<clang::CXXDestructorDecl>(clang_decl)) {
  1412. function_info.SetBuiltinFunction(SemIR::BuiltinFunctionKind::NoOp);
  1413. }
  1414. // TODO: Should we model a trivial default constructor as performing
  1415. // value-initialization (zero-initializing all fields) or
  1416. // default-initialization (leaving fields uniniitalized)? Either way we
  1417. // could model that effect as a builtin.
  1418. // TODO: Add a builtin to model trivial copies.
  1419. }
  1420. }
  1421. return function_info.first_owning_decl_id;
  1422. }
  1423. namespace {
  1424. // An item to be imported in an import worklist.
  1425. // TODO: If worklists ever become particularly large, consider changing this
  1426. // to use a `PointerIntPair`.
  1427. struct ImportItem {
  1428. // A declaration that we want to import.
  1429. SemIR::ClangDeclKey decl_key;
  1430. // Whether we have added `decl`'s dependencies to the worklist.
  1431. bool added_dependencies;
  1432. };
  1433. // A worklist of declarations to import.
  1434. using ImportWorklist = llvm::SmallVector<ImportItem>;
  1435. } // namespace
  1436. // Adds the given declaration to our list of declarations to import.
  1437. static auto AddDependentDecl(Context& context, SemIR::ClangDeclKey decl,
  1438. ImportWorklist& worklist) -> void {
  1439. if (!IsClangDeclImported(context, decl)) {
  1440. worklist.push_back({.decl_key = decl, .added_dependencies = false});
  1441. }
  1442. }
  1443. // Finds all decls that need to be imported before importing the given type and
  1444. // adds them to the given set.
  1445. static auto AddDependentUnimportedTypeDecls(Context& context,
  1446. clang::QualType type,
  1447. ImportWorklist& worklist) -> void {
  1448. while (true) {
  1449. if (type->isPointerType() || type->isReferenceType()) {
  1450. type = type->getPointeeType();
  1451. } else if (const clang::ArrayType* array_type =
  1452. type->getAsArrayTypeUnsafe()) {
  1453. type = array_type->getElementType();
  1454. } else {
  1455. break;
  1456. }
  1457. }
  1458. if (const auto* tag_type = type->getAs<clang::TagType>()) {
  1459. AddDependentDecl(context, SemIR::ClangDeclKey(tag_type->getDecl()),
  1460. worklist);
  1461. }
  1462. }
  1463. // Finds all decls that need to be imported before importing the given function
  1464. // and adds them to the given set.
  1465. static auto AddDependentUnimportedFunctionDecls(
  1466. Context& context, const clang::FunctionDecl& clang_decl,
  1467. SemIR::ClangDeclKey::Signature signature, ImportWorklist& worklist)
  1468. -> void {
  1469. const auto* function_type =
  1470. clang_decl.getType()->castAs<clang::FunctionProtoType>();
  1471. for (int i : llvm::seq(clang_decl.hasCXXExplicitFunctionObjectParameter() +
  1472. signature.num_params)) {
  1473. AddDependentUnimportedTypeDecls(context, function_type->getParamType(i),
  1474. worklist);
  1475. }
  1476. AddDependentUnimportedTypeDecls(context, clang_decl.getReturnType(),
  1477. worklist);
  1478. }
  1479. // Finds all decls that need to be imported before importing the given
  1480. // declaration and adds them to the given set.
  1481. static auto AddDependentUnimportedDecls(Context& context,
  1482. SemIR::ClangDeclKey key,
  1483. ImportWorklist& worklist) -> void {
  1484. clang::Decl* clang_decl = key.decl;
  1485. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1486. AddDependentUnimportedFunctionDecls(context, *clang_function_decl,
  1487. key.signature, worklist);
  1488. } else if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1489. if (!isa<clang::TagDecl>(clang_decl)) {
  1490. AddDependentUnimportedTypeDecls(
  1491. context, type_decl->getASTContext().getTypeDeclType(type_decl),
  1492. worklist);
  1493. }
  1494. }
  1495. auto* parent = GetParentDecl(clang_decl);
  1496. if (llvm::isa_and_nonnull<clang::TagDecl, clang::NamespaceDecl,
  1497. clang::TranslationUnitDecl>(parent)) {
  1498. AddDependentDecl(context, SemIR::ClangDeclKey::ForNonFunctionDecl(parent),
  1499. worklist);
  1500. }
  1501. }
  1502. static auto ImportVarDecl(Context& context, SemIR::LocId loc_id,
  1503. clang::VarDecl* var_decl) -> SemIR::InstId {
  1504. if (SemIR::InstId existing_inst_id =
  1505. LookupClangDeclInstId(context, SemIR::ClangDeclKey(var_decl));
  1506. existing_inst_id.has_value()) {
  1507. return existing_inst_id;
  1508. }
  1509. // Extract type and name.
  1510. clang::QualType var_type = var_decl->getType();
  1511. SemIR::TypeId var_type_id = MapType(context, loc_id, var_type).type_id;
  1512. if (!var_type_id.has_value()) {
  1513. context.TODO(loc_id, llvm::formatv("Unsupported: var type: {0}",
  1514. var_type.getAsString()));
  1515. return SemIR::ErrorInst::InstId;
  1516. }
  1517. SemIR::NameId var_name_id = AddIdentifierName(context, var_decl->getName());
  1518. // Create an entity name to identify this variable.
  1519. SemIR::EntityNameId entity_name_id =
  1520. context.entity_names().AddSymbolicBindingName(
  1521. var_name_id, GetParentNameScopeId(context, var_decl),
  1522. SemIR::CompileTimeBindIndex::None, false);
  1523. // Create `RefBindingPattern` and `VarPattern`. Mirror the behavior of
  1524. // import_ref and don't create a `NameBindingDecl` here; we'd never use it for
  1525. // anything.
  1526. SemIR::TypeId pattern_type_id = GetPatternType(context, var_type_id);
  1527. SemIR::InstId binding_pattern_inst_id =
  1528. AddInstInNoBlock<SemIR::RefBindingPattern>(
  1529. context, loc_id,
  1530. {.type_id = pattern_type_id, .entity_name_id = entity_name_id});
  1531. context.imports().push_back(binding_pattern_inst_id);
  1532. auto pattern_id = AddInstInNoBlock<SemIR::VarPattern>(
  1533. context, Parse::VariablePatternId::None,
  1534. {.type_id = pattern_type_id, .subpattern_id = binding_pattern_inst_id});
  1535. context.imports().push_back(pattern_id);
  1536. // Create the imported storage for the global. We intentionally use the
  1537. // untyped form of `AddInstInNoBlock` to bypass the check on adding an
  1538. // instruction that requires a cleanup, because we don't want a cleanup here!
  1539. SemIR::InstId var_storage_inst_id = AddInstInNoBlock(
  1540. context, {loc_id, SemIR::VarStorage{.type_id = var_type_id,
  1541. .pattern_id = pattern_id}});
  1542. context.imports().push_back(var_storage_inst_id);
  1543. // Register the variable so we don't create it again, and track the
  1544. // corresponding declaration to use for mangling.
  1545. auto clang_decl_id = context.clang_decls().Add(
  1546. {.key = SemIR::ClangDeclKey(var_decl), .inst_id = var_storage_inst_id});
  1547. context.cpp_global_names().Add({.key = {.entity_name_id = entity_name_id},
  1548. .clang_decl_id = clang_decl_id});
  1549. // Inform Clang that the variable has been referenced.
  1550. context.clang_sema().MarkVariableReferenced(GetCppLocation(context, loc_id),
  1551. var_decl);
  1552. return var_storage_inst_id;
  1553. }
  1554. static auto ImportTemplateDecl(Context& context,
  1555. clang::TemplateDecl* template_decl)
  1556. -> SemIR::InstId {
  1557. auto key = SemIR::ClangDeclKey(template_decl);
  1558. // TODO: Avoid doing this lookup both here and in the insertion below.
  1559. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, key);
  1560. existing_inst_id.has_value()) {
  1561. return existing_inst_id;
  1562. }
  1563. // Add a placeholder instruction to resolve cycle between the clang
  1564. // declaration and the type.
  1565. auto import_loc_id =
  1566. AddImportIRInst(context.sem_ir(), template_decl->getLocation());
  1567. SemIR::StructValue value = {.type_id = SemIR::TypeId::None,
  1568. .elements_id = SemIR::InstBlockId::Empty};
  1569. auto inst_id = AddPlaceholderImportedInstInNoBlock(
  1570. context, MakeImportedLocIdAndInst(context, import_loc_id, value));
  1571. // Create a type for the constant value.
  1572. auto name_id = context.entity_names().Add(
  1573. {.name_id = AddIdentifierName(context, template_decl->getName()),
  1574. .parent_scope_id = GetParentNameScopeId(context, template_decl)});
  1575. auto decl_id = context.clang_decls().Add({.key = key, .inst_id = inst_id});
  1576. value.type_id = GetCppTemplateNameType(context, name_id, decl_id);
  1577. // Update the value with its type.
  1578. ReplaceInstBeforeConstantUse(context, inst_id, value);
  1579. return inst_id;
  1580. }
  1581. // Imports a declaration from Clang to Carbon. Returns the instruction for the
  1582. // new Carbon declaration, which will be an ErrorInst on failure. Assumes all
  1583. // dependencies have already been imported.
  1584. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1585. SemIR::ClangDeclKey key)
  1586. -> SemIR::InstId {
  1587. clang::Decl* clang_decl = key.decl;
  1588. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1589. return ImportFunctionDecl(context, loc_id, clang_function_decl,
  1590. key.signature);
  1591. }
  1592. if (auto* clang_namespace_decl = dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1593. return ImportNamespaceDecl(context, clang_namespace_decl);
  1594. }
  1595. if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1596. auto type = clang_decl->getASTContext().getTypeDeclType(type_decl);
  1597. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1598. if (!type_inst_id.has_value()) {
  1599. context.TODO(AddImportIRInst(context.sem_ir(), type_decl->getLocation()),
  1600. llvm::formatv("Unsupported: Type declaration: {0}",
  1601. type.getAsString()));
  1602. return SemIR::ErrorInst::InstId;
  1603. }
  1604. context.clang_decls().Add({.key = key, .inst_id = type_inst_id});
  1605. return type_inst_id;
  1606. }
  1607. if (isa<clang::FieldDecl, clang::IndirectFieldDecl>(clang_decl)) {
  1608. // Usable fields get imported as a side effect of importing the class.
  1609. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, key);
  1610. existing_inst_id.has_value()) {
  1611. return existing_inst_id;
  1612. }
  1613. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1614. "Unsupported: field declaration has unhandled type or kind");
  1615. return SemIR::ErrorInst::InstId;
  1616. }
  1617. if (auto* enum_const_decl = dyn_cast<clang::EnumConstantDecl>(clang_decl)) {
  1618. return ImportEnumConstantDecl(context, enum_const_decl);
  1619. }
  1620. if (auto* var_decl = dyn_cast<clang::VarDecl>(clang_decl)) {
  1621. return ImportVarDecl(context, loc_id, var_decl);
  1622. }
  1623. if (auto* template_decl = dyn_cast<clang::TemplateDecl>(clang_decl)) {
  1624. return ImportTemplateDecl(context, template_decl);
  1625. }
  1626. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1627. llvm::formatv("Unsupported: Declaration type {0}",
  1628. clang_decl->getDeclKindName()));
  1629. return SemIR::ErrorInst::InstId;
  1630. }
  1631. // Attempts to import a set of declarations. Returns `false` if an error was
  1632. // produced, `true` otherwise.
  1633. static auto ImportDeclSet(Context& context, SemIR::LocId loc_id,
  1634. ImportWorklist& worklist) -> bool {
  1635. // Walk the dependency graph in depth-first order, and import declarations
  1636. // once we've imported all of their dependencies.
  1637. while (!worklist.empty()) {
  1638. auto& item = worklist.back();
  1639. if (!item.added_dependencies) {
  1640. // Skip items we've already imported. We checked this when initially
  1641. // adding the item to the worklist, but it might have been added to the
  1642. // worklist twice before the first time we visited it. For example, this
  1643. // happens for `fn F(a: Cpp.T, b: Cpp.T)`.
  1644. if (IsClangDeclImported(context, item.decl_key)) {
  1645. worklist.pop_back();
  1646. continue;
  1647. }
  1648. // First time visiting this declaration (preorder): add its dependencies
  1649. // to the work list.
  1650. item.added_dependencies = true;
  1651. AddDependentUnimportedDecls(context, item.decl_key, worklist);
  1652. } else {
  1653. // Second time visiting this declaration (postorder): its dependencies are
  1654. // already imported, so we can import it now.
  1655. auto decl_key = worklist.pop_back_val().decl_key;
  1656. auto inst_id = ImportDeclAfterDependencies(context, loc_id, decl_key);
  1657. CARBON_CHECK(inst_id.has_value());
  1658. if (inst_id == SemIR::ErrorInst::InstId) {
  1659. return false;
  1660. }
  1661. CARBON_CHECK(IsClangDeclImported(context, decl_key));
  1662. }
  1663. }
  1664. return true;
  1665. }
  1666. auto ImportCppDecl(Context& context, SemIR::LocId loc_id,
  1667. SemIR::ClangDeclKey key) -> SemIR::InstId {
  1668. // Collect dependencies by walking the dependency graph in depth-first order.
  1669. ImportWorklist worklist;
  1670. AddDependentDecl(context, key, worklist);
  1671. if (!ImportDeclSet(context, loc_id, worklist)) {
  1672. return SemIR::ErrorInst::InstId;
  1673. }
  1674. return LookupClangDeclInstId(context, key);
  1675. }
  1676. auto ImportCppType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  1677. -> TypeExpr {
  1678. // Collect dependencies by walking the dependency graph in depth-first order.
  1679. ImportWorklist worklist;
  1680. AddDependentUnimportedTypeDecls(context, type, worklist);
  1681. if (!ImportDeclSet(context, loc_id, worklist)) {
  1682. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1683. .type_id = SemIR::ErrorInst::TypeId};
  1684. }
  1685. return MapType(context, loc_id, type);
  1686. }
  1687. // Imports a Clang declaration into Carbon and adds that name into the
  1688. // `NameScope`.
  1689. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1690. SemIR::NameScopeId scope_id,
  1691. SemIR::NameId name_id,
  1692. SemIR::ClangDeclKey key,
  1693. SemIR::AccessKind access_kind)
  1694. -> SemIR::ScopeLookupResult {
  1695. SemIR::InstId inst_id = ImportCppDecl(context, loc_id, key);
  1696. if (!inst_id.has_value()) {
  1697. return SemIR::ScopeLookupResult::MakeNotFound();
  1698. }
  1699. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1700. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1701. access_kind);
  1702. }
  1703. // Returns true if the scope is the top `Cpp` scope.
  1704. static auto IsTopCppScope(Context& context, SemIR::NameScopeId scope_id)
  1705. -> bool {
  1706. const SemIR::NameScope& name_scope = context.name_scopes().Get(scope_id);
  1707. CARBON_CHECK(name_scope.is_cpp_scope());
  1708. return name_scope.parent_scope_id() == SemIR::NameScopeId::Package;
  1709. }
  1710. // For a builtin name like `Cpp.long`, returns the associated type.
  1711. static auto LookupBuiltinName(Context& context, SemIR::LocId loc_id,
  1712. SemIR::NameScopeId scope_id,
  1713. SemIR::NameId name_id) -> SemIR::InstId {
  1714. if (!IsTopCppScope(context, scope_id)) {
  1715. return SemIR::InstId::None;
  1716. }
  1717. auto name = context.names().GetAsStringIfIdentifier(name_id);
  1718. if (!name) {
  1719. return SemIR::InstId::None;
  1720. }
  1721. const clang::ASTContext& ast_context = context.ast_context();
  1722. // List of types based on
  1723. // https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p5448.md#details
  1724. auto builtin_type =
  1725. llvm::StringSwitch<clang::QualType>(*name)
  1726. .Case("signed_char", ast_context.SignedCharTy)
  1727. .Case("short", ast_context.ShortTy)
  1728. .Case("int", ast_context.IntTy)
  1729. .Case("long", ast_context.LongTy)
  1730. .Case("long_long", ast_context.LongLongTy)
  1731. .Case("unsigned_char", ast_context.UnsignedCharTy)
  1732. .Case("unsigned_short", ast_context.UnsignedShortTy)
  1733. .Case("unsigned_int", ast_context.UnsignedIntTy)
  1734. .Case("unsigned_long", ast_context.UnsignedLongTy)
  1735. .Case("unsigned_long_long", ast_context.UnsignedLongLongTy)
  1736. .Case("float", ast_context.FloatTy)
  1737. .Case("double", ast_context.DoubleTy)
  1738. .Case("long_double", ast_context.LongDoubleTy)
  1739. .Case("void", ast_context.VoidTy)
  1740. .Default(clang::QualType());
  1741. if (builtin_type.isNull()) {
  1742. if (*name == "nullptr") {
  1743. // Map `Cpp.nullptr` to an uninitialized value of type `Core.CppNullptrT`.
  1744. auto type_id = MapNullptrType(context, loc_id).type_id;
  1745. return GetOrAddInst<SemIR::UninitializedValue>(
  1746. context, SemIR::LocId::None, {.type_id = type_id});
  1747. }
  1748. return SemIR::InstId::None;
  1749. }
  1750. SemIR::InstId inst_id =
  1751. MapNonWrapperType(context, loc_id, builtin_type).inst_id;
  1752. if (!inst_id.has_value()) {
  1753. context.TODO(loc_id, llvm::formatv("Unsupported: builtin type: {0}",
  1754. builtin_type.getAsString()));
  1755. return SemIR::ErrorInst::InstId;
  1756. }
  1757. return inst_id;
  1758. }
  1759. auto ImportCppOverloadSet(
  1760. Context& context, SemIR::LocId loc_id, SemIR::NameScopeId scope_id,
  1761. SemIR::NameId name_id, clang::CXXRecordDecl* naming_class,
  1762. clang::UnresolvedSet<4>&& overload_set,
  1763. clang::OverloadCandidateSet::OperatorRewriteInfo operator_rewrite_info)
  1764. -> SemIR::InstId {
  1765. SemIR::CppOverloadSetId overload_set_id = context.cpp_overload_sets().Add(
  1766. SemIR::CppOverloadSet{.name_id = name_id,
  1767. .parent_scope_id = scope_id,
  1768. .naming_class = naming_class,
  1769. .candidate_functions = std::move(overload_set),
  1770. .operator_rewrite_info = operator_rewrite_info});
  1771. auto overload_set_inst_id = AddInstInNoBlock<SemIR::CppOverloadSetValue>(
  1772. context, loc_id,
  1773. {.type_id = GetCppOverloadSetType(context, overload_set_id,
  1774. SemIR::SpecificId::None),
  1775. .overload_set_id = overload_set_id});
  1776. context.imports().push_back(overload_set_inst_id);
  1777. return overload_set_inst_id;
  1778. }
  1779. // Gets the best access for an overloaded function set. This is the access that
  1780. // we use for the overload set as a whole. More fine-grained checking is done
  1781. // after overload resolution.
  1782. static auto GetOverloadSetAccess(const clang::UnresolvedSet<4>& overload_set)
  1783. -> SemIR::AccessKind {
  1784. SemIR::AccessKind access_kind = SemIR::AccessKind::Private;
  1785. for (clang::DeclAccessPair overload : overload_set.pairs()) {
  1786. access_kind = std::min(access_kind, MapCppAccess(overload));
  1787. if (access_kind == SemIR::AccessKind::Public) {
  1788. break;
  1789. }
  1790. }
  1791. return access_kind;
  1792. }
  1793. // Imports an overload set from Clang to Carbon and adds the name into the
  1794. // `NameScope`.
  1795. static auto ImportOverloadSetIntoScope(Context& context, SemIR::LocId loc_id,
  1796. SemIR::NameScopeId scope_id,
  1797. SemIR::NameId name_id,
  1798. clang::CXXRecordDecl* naming_class,
  1799. clang::UnresolvedSet<4>&& overload_set)
  1800. -> SemIR::ScopeLookupResult {
  1801. SemIR::AccessKind access_kind = GetOverloadSetAccess(overload_set);
  1802. SemIR::InstId inst_id = ImportCppOverloadSet(
  1803. context, loc_id, scope_id, name_id, naming_class, std::move(overload_set),
  1804. /*operator_rewrite_info=*/{});
  1805. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1806. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1807. access_kind);
  1808. }
  1809. // Imports the constructors for a given class name. The found constructors are
  1810. // imported as part of an overload set into the scope. Currently copy/move
  1811. // constructors are not imported.
  1812. static auto ImportConstructorsIntoScope(Context& context, SemIR::LocId loc_id,
  1813. SemIR::NameScopeId scope_id,
  1814. SemIR::NameId name_id)
  1815. -> SemIR::ScopeLookupResult {
  1816. auto* naming_class =
  1817. cast<clang::CXXRecordDecl>(GetDeclContext(context, scope_id));
  1818. clang::DeclContextLookupResult constructors_lookup =
  1819. context.clang_sema().LookupConstructors(naming_class);
  1820. clang::UnresolvedSet<4> overload_set;
  1821. for (auto* decl : constructors_lookup) {
  1822. auto info = clang::getConstructorInfo(decl);
  1823. if (!info.Constructor || info.Constructor->isCopyOrMoveConstructor()) {
  1824. continue;
  1825. }
  1826. overload_set.addDecl(info.FoundDecl, info.FoundDecl.getAccess());
  1827. }
  1828. if (overload_set.empty()) {
  1829. return SemIR::ScopeLookupResult::MakeNotFound();
  1830. }
  1831. return ImportOverloadSetIntoScope(context, loc_id, scope_id, name_id,
  1832. naming_class, std::move(overload_set));
  1833. }
  1834. // Attempts to import a builtin name from Clang to Carbon and adds the name into
  1835. // the scope.
  1836. static auto ImportBuiltinNameIntoScope(Context& context, SemIR::LocId loc_id,
  1837. SemIR::NameScopeId scope_id,
  1838. SemIR::NameId name_id)
  1839. -> SemIR::ScopeLookupResult {
  1840. SemIR::InstId builtin_inst_id =
  1841. LookupBuiltinName(context, loc_id, scope_id, name_id);
  1842. if (builtin_inst_id.has_value()) {
  1843. AddNameToScope(context, scope_id, name_id, SemIR::AccessKind::Public,
  1844. builtin_inst_id);
  1845. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  1846. builtin_inst_id, SemIR::AccessKind::Public);
  1847. }
  1848. return SemIR::ScopeLookupResult::MakeNotFound();
  1849. }
  1850. // Checks if the name scope is a class that is not complete.
  1851. static auto IsIncompleteClass(Context& context, SemIR::NameScopeId scope_id)
  1852. -> bool {
  1853. auto class_decl = context.insts().TryGetAs<SemIR::ClassDecl>(
  1854. context.name_scopes().Get(scope_id).inst_id());
  1855. return class_decl.has_value() &&
  1856. !context.types().IsComplete(
  1857. context.classes().Get(class_decl->class_id).self_type_id);
  1858. }
  1859. // Maps a Clang literal expression to a Carbon constant.
  1860. // TODO: Add support for all constant types for which a C++ to Carbon type
  1861. // mapping exists.
  1862. static auto MapConstant(Context& context, SemIR::LocId loc_id,
  1863. clang::Expr* expr) -> SemIR::InstId {
  1864. CARBON_CHECK(expr, "empty expression");
  1865. if (auto* string_literal = dyn_cast<clang::StringLiteral>(expr)) {
  1866. if (!string_literal->isOrdinary() && !string_literal->isUTF8()) {
  1867. context.TODO(loc_id,
  1868. llvm::formatv("Unsupported: string literal type: {0}",
  1869. expr->getType()));
  1870. return SemIR::ErrorInst::InstId;
  1871. }
  1872. StringLiteralValueId string_id =
  1873. context.string_literal_values().Add(string_literal->getString());
  1874. auto inst_id =
  1875. MakeStringLiteral(context, Parse::StringLiteralId::None, string_id);
  1876. return inst_id;
  1877. } else if (isa<clang::CXXNullPtrLiteralExpr>(expr)) {
  1878. auto type_id = MapNullptrType(context, loc_id).type_id;
  1879. return GetOrAddInst<SemIR::UninitializedValue>(context, SemIR::LocId::None,
  1880. {.type_id = type_id});
  1881. }
  1882. SemIR::TypeId type_id = MapType(context, loc_id, expr->getType()).type_id;
  1883. if (!type_id.has_value()) {
  1884. context.TODO(loc_id, llvm::formatv("Unsupported: C++ literal's type `{0}` "
  1885. "could not be mapped to a Carbon type",
  1886. expr->getType().getAsString()));
  1887. return SemIR::ErrorInst::InstId;
  1888. }
  1889. SemIR::InstId inst_id = SemIR::InstId::None;
  1890. SemIR::ImportIRInstId imported_loc_id =
  1891. AddImportIRInst(context.sem_ir(), expr->getExprLoc());
  1892. if (auto* integer_literal = dyn_cast<clang::IntegerLiteral>(expr)) {
  1893. IntId int_id =
  1894. context.ints().Add(integer_literal->getValue().getSExtValue());
  1895. inst_id = AddInstInNoBlock(
  1896. context,
  1897. MakeImportedLocIdAndInst<SemIR::IntValue>(
  1898. context, imported_loc_id, {.type_id = type_id, .int_id = int_id}));
  1899. } else if (auto* bool_literal = dyn_cast<clang::CXXBoolLiteralExpr>(expr)) {
  1900. inst_id = AddInstInNoBlock(
  1901. context,
  1902. MakeImportedLocIdAndInst<SemIR::BoolLiteral>(
  1903. context, imported_loc_id,
  1904. {.type_id = type_id,
  1905. .value = SemIR::BoolValue::From(bool_literal->getValue())}));
  1906. } else if (auto* float_literal = dyn_cast<clang::FloatingLiteral>(expr)) {
  1907. FloatId float_id = context.floats().Add(float_literal->getValue());
  1908. inst_id = AddInstInNoBlock(context,
  1909. MakeImportedLocIdAndInst<SemIR::FloatValue>(
  1910. context, imported_loc_id,
  1911. {.type_id = type_id, .float_id = float_id}));
  1912. } else if (auto* character_literal =
  1913. dyn_cast<clang::CharacterLiteral>(expr)) {
  1914. inst_id = AddInstInNoBlock(
  1915. context, MakeImportedLocIdAndInst<SemIR::CharLiteralValue>(
  1916. context, imported_loc_id,
  1917. {.type_id = type_id,
  1918. .value = SemIR::CharId(character_literal->getValue())}));
  1919. } else {
  1920. context.TODO(loc_id, llvm::formatv(
  1921. "Unsupported: C++ constant expression type: '{0}'",
  1922. expr->getType().getAsString()));
  1923. return SemIR::ErrorInst::InstId;
  1924. }
  1925. context.imports().push_back(inst_id);
  1926. return inst_id;
  1927. }
  1928. // Imports a macro definition into the scope. Currently supports only simple
  1929. // object-like macros that expand to a constant integer value.
  1930. // TODO: Add support for other macro types and non-integer literal values.
  1931. static auto ImportMacro(Context& context, SemIR::LocId loc_id,
  1932. SemIR::NameScopeId scope_id, SemIR::NameId name_id,
  1933. clang::MacroInfo* macro_info)
  1934. -> SemIR::ScopeLookupResult {
  1935. clang::Expr* macro_expr =
  1936. TryEvaluateMacroToConstant(context, loc_id, name_id, macro_info);
  1937. if (!macro_expr) {
  1938. return SemIR::ScopeLookupResult::MakeNotFound();
  1939. }
  1940. auto inst_id = MapConstant(context, loc_id, macro_expr);
  1941. if (inst_id == SemIR::ErrorInst::InstId) {
  1942. return SemIR::ScopeLookupResult::MakeNotFound();
  1943. }
  1944. AddNameToScope(context, scope_id, name_id, SemIR::AccessKind::Public,
  1945. inst_id);
  1946. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  1947. inst_id, SemIR::AccessKind::Public);
  1948. }
  1949. // Looks up a macro definition in the top-level `Cpp` scope. Returns nullptr if
  1950. // the macro is not found or if it is a builtin macro, function-like macro or a
  1951. // macro used for header guards.
  1952. // TODO: Function-like and builtin macros are currently not supported and their
  1953. // support still needs to be clarified.
  1954. static auto LookupMacro(Context& context, SemIR::NameScopeId scope_id,
  1955. clang::IdentifierInfo* identifier_info)
  1956. -> clang::MacroInfo* {
  1957. if (!IsTopCppScope(context, scope_id)) {
  1958. return nullptr;
  1959. }
  1960. CARBON_CHECK(identifier_info, "Identifier info is empty");
  1961. clang::MacroInfo* macro_info =
  1962. context.clang_sema().getPreprocessor().getMacroInfo(identifier_info);
  1963. if (macro_info && !macro_info->isUsedForHeaderGuard() &&
  1964. !macro_info->isFunctionLike() && !macro_info->isBuiltinMacro()) {
  1965. return macro_info;
  1966. }
  1967. return nullptr;
  1968. }
  1969. auto GetClangIdentifierInfo(Context& context, SemIR::NameId name_id)
  1970. -> clang::IdentifierInfo* {
  1971. std::optional<llvm::StringRef> string_name =
  1972. context.names().GetAsStringIfIdentifier(name_id);
  1973. if (!string_name) {
  1974. return nullptr;
  1975. }
  1976. clang::IdentifierInfo* identifier_info =
  1977. context.clang_sema().getPreprocessor().getIdentifierInfo(*string_name);
  1978. return identifier_info;
  1979. }
  1980. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1981. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1982. -> SemIR::ScopeLookupResult {
  1983. Diagnostics::AnnotationScope annotate_diagnostics(
  1984. &context.emitter(), [&](auto& builder) {
  1985. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1986. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1987. builder.Note(loc_id, InCppNameLookup, name_id);
  1988. });
  1989. if (IsIncompleteClass(context, scope_id)) {
  1990. return SemIR::ScopeLookupResult::MakeError();
  1991. }
  1992. clang::IdentifierInfo* identifier_info =
  1993. GetClangIdentifierInfo(context, name_id);
  1994. if (!identifier_info) {
  1995. return SemIR::ScopeLookupResult::MakeNotFound();
  1996. }
  1997. if (clang::MacroInfo* macro_info =
  1998. LookupMacro(context, scope_id, identifier_info)) {
  1999. return ImportMacro(context, loc_id, scope_id, name_id, macro_info);
  2000. }
  2001. auto lookup = ClangLookupName(context, scope_id, identifier_info);
  2002. if (!lookup) {
  2003. return ImportBuiltinNameIntoScope(context, loc_id, scope_id, name_id);
  2004. }
  2005. // Access checks are performed separately by the Carbon name lookup logic.
  2006. lookup->suppressAccessDiagnostics();
  2007. if (lookup->isOverloadedResult() ||
  2008. (lookup->isSingleResult() &&
  2009. lookup->getFoundDecl()->isFunctionOrFunctionTemplate())) {
  2010. clang::UnresolvedSet<4> overload_set;
  2011. overload_set.append(lookup->begin(), lookup->end());
  2012. return ImportOverloadSetIntoScope(context, loc_id, scope_id, name_id,
  2013. lookup->getNamingClass(),
  2014. std::move(overload_set));
  2015. }
  2016. if (!lookup->isSingleResult()) {
  2017. // Clang will diagnose ambiguous lookup results for us.
  2018. if (!lookup->isAmbiguous()) {
  2019. context.TODO(loc_id,
  2020. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  2021. "find a single result; LookupResultKind: {0}",
  2022. static_cast<int>(lookup->getResultKind())));
  2023. }
  2024. context.name_scopes().AddRequiredName(scope_id, name_id,
  2025. SemIR::ErrorInst::InstId);
  2026. return SemIR::ScopeLookupResult::MakeError();
  2027. }
  2028. if (IsDeclInjectedClassName(context, scope_id, name_id,
  2029. lookup->getFoundDecl())) {
  2030. return ImportConstructorsIntoScope(context, loc_id, scope_id, name_id);
  2031. }
  2032. auto key = SemIR::ClangDeclKey::ForNonFunctionDecl(lookup->getFoundDecl());
  2033. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id, key,
  2034. MapCppAccess(lookup->begin().getPair()));
  2035. }
  2036. auto ImportClassDefinitionForClangDecl(Context& context, SemIR::LocId loc_id,
  2037. SemIR::ClassId class_id,
  2038. SemIR::ClangDeclId clang_decl_id)
  2039. -> bool {
  2040. SemIR::CppFile* cpp_file = context.sem_ir().cpp_file();
  2041. CARBON_CHECK(cpp_file);
  2042. auto* clang_decl =
  2043. cast<clang::TagDecl>(context.clang_decls().Get(clang_decl_id).key.decl);
  2044. auto class_inst_id = context.types().GetAsTypeInstId(
  2045. context.classes().Get(class_id).first_owning_decl_id);
  2046. // TODO: Map loc_id into a clang location and use it for diagnostics if
  2047. // instantiation fails, instead of annotating the diagnostic with another
  2048. // location.
  2049. clang::SourceLocation loc = clang_decl->getLocation();
  2050. Diagnostics::AnnotationScope annotate_diagnostics(
  2051. &context.emitter(), [&](auto& builder) {
  2052. CARBON_DIAGNOSTIC(InCppTypeCompletion, Note,
  2053. "while completing C++ type {0}", SemIR::TypeId);
  2054. builder.Note(loc_id, InCppTypeCompletion,
  2055. context.classes().Get(class_id).self_type_id);
  2056. });
  2057. // Ask Clang whether the type is complete. This triggers template
  2058. // instantiation if necessary.
  2059. clang::DiagnosticErrorTrap trap(cpp_file->diagnostics());
  2060. if (!context.cpp_context()->sema().isCompleteType(
  2061. loc, context.ast_context().getCanonicalTagType(clang_decl))) {
  2062. // Type is incomplete. Nothing more to do, but tell the caller if we
  2063. // produced an error.
  2064. return !trap.hasErrorOccurred();
  2065. }
  2066. auto import_ir_inst_id =
  2067. context.insts().GetCanonicalLocId(class_inst_id).import_ir_inst_id();
  2068. if (auto* class_decl = dyn_cast<clang::CXXRecordDecl>(clang_decl)) {
  2069. auto* class_def = class_decl->getDefinition();
  2070. CARBON_CHECK(class_def, "Complete type has no definition");
  2071. BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  2072. class_def);
  2073. } else if (auto* enum_decl = dyn_cast<clang::EnumDecl>(clang_decl)) {
  2074. BuildEnumDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  2075. enum_decl);
  2076. }
  2077. return true;
  2078. }
  2079. } // namespace Carbon::Check