import.cpp 102 KB

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