import.cpp 90 KB

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