import.cpp 92 KB

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