import.cpp 93 KB

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