import.cpp 94 KB

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