import.cpp 89 KB

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