import.cpp 97 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458
  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 <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <tuple>
  9. #include <utility>
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/AST/RecordLayout.h"
  12. #include "clang/AST/UnresolvedSet.h"
  13. #include "clang/AST/VTableBuilder.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Frontend/ASTUnit.h"
  16. #include "clang/Frontend/CompilerInstance.h"
  17. #include "clang/Frontend/CompilerInvocation.h"
  18. #include "clang/Frontend/TextDiagnostic.h"
  19. #include "clang/Lex/PreprocessorOptions.h"
  20. #include "clang/Sema/Lookup.h"
  21. #include "common/check.h"
  22. #include "common/ostream.h"
  23. #include "common/raw_string_ostream.h"
  24. #include "llvm/ADT/IntrusiveRefCntPtr.h"
  25. #include "llvm/ADT/StringRef.h"
  26. #include "llvm/Support/raw_ostream.h"
  27. #include "toolchain/base/kind_switch.h"
  28. #include "toolchain/check/class.h"
  29. #include "toolchain/check/context.h"
  30. #include "toolchain/check/control_flow.h"
  31. #include "toolchain/check/convert.h"
  32. #include "toolchain/check/cpp/custom_type_mapping.h"
  33. #include "toolchain/check/cpp/thunk.h"
  34. #include "toolchain/check/diagnostic_helpers.h"
  35. #include "toolchain/check/eval.h"
  36. #include "toolchain/check/function.h"
  37. #include "toolchain/check/import.h"
  38. #include "toolchain/check/inst.h"
  39. #include "toolchain/check/literal.h"
  40. #include "toolchain/check/operator.h"
  41. #include "toolchain/check/pattern.h"
  42. #include "toolchain/check/pattern_match.h"
  43. #include "toolchain/check/type.h"
  44. #include "toolchain/check/type_completion.h"
  45. #include "toolchain/diagnostics/diagnostic.h"
  46. #include "toolchain/diagnostics/diagnostic_emitter.h"
  47. #include "toolchain/diagnostics/format_providers.h"
  48. #include "toolchain/parse/node_ids.h"
  49. #include "toolchain/sem_ir/clang_decl.h"
  50. #include "toolchain/sem_ir/class.h"
  51. #include "toolchain/sem_ir/cpp_overload_set.h"
  52. #include "toolchain/sem_ir/function.h"
  53. #include "toolchain/sem_ir/ids.h"
  54. #include "toolchain/sem_ir/inst.h"
  55. #include "toolchain/sem_ir/name_scope.h"
  56. #include "toolchain/sem_ir/typed_insts.h"
  57. namespace Carbon::Check {
  58. // Add a line marker directive pointing at the location of the `import Cpp`
  59. // declaration in the Carbon source file. This will cause Clang's diagnostics
  60. // machinery to track and report the location in Carbon code where the import
  61. // was written.
  62. static auto GenerateLineMarker(Context& context, llvm::raw_ostream& out,
  63. int line) {
  64. out << "# " << line << " \""
  65. << FormatEscaped(context.tokens().source().filename()) << "\"\n";
  66. }
  67. // Generates C++ file contents to #include all requested imports.
  68. static auto GenerateCppIncludesHeaderCode(
  69. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  70. -> std::string {
  71. std::string code;
  72. llvm::raw_string_ostream code_stream(code);
  73. for (const Parse::Tree::PackagingNames& import : imports) {
  74. if (import.inline_body_id.has_value()) {
  75. // Expand `import Cpp inline "code";` directly into the specified code.
  76. auto code_token = context.parse_tree().node_token(import.inline_body_id);
  77. // Compute the line number on which the C++ code starts. Usually the code
  78. // is specified as a block string literal and starts on the line after the
  79. // start of the string token.
  80. // TODO: Determine if this is a block string literal without calling
  81. // `GetTokenText`, which re-lexes the string.
  82. int line = context.tokens().GetLineNumber(code_token);
  83. if (context.tokens().GetTokenText(code_token).contains('\n')) {
  84. ++line;
  85. }
  86. GenerateLineMarker(context, code_stream, line);
  87. code_stream << context.string_literal_values().Get(
  88. context.tokens().GetStringLiteralValue(code_token))
  89. << "\n";
  90. // TODO: Inject a clang pragma here to produce an error if there are
  91. // unclosed scopes at the end of this inline C++ fragment.
  92. } else {
  93. // Translate `import Cpp library "foo.h";` into `#include "foo.h"`.
  94. GenerateLineMarker(context, code_stream,
  95. context.tokens().GetLineNumber(
  96. context.parse_tree().node_token(import.node_id)));
  97. code_stream << "#include \""
  98. << FormatEscaped(
  99. context.string_literal_values().Get(import.library_id))
  100. << "\"\n";
  101. }
  102. }
  103. // Inject a declaration of placement operator new, because the code we
  104. // generate in thunks depends on it for placement new expressions. Clang has
  105. // special-case logic for lowering a new-expression using this, so a
  106. // definition is not required.
  107. // TODO: This is a hack. We should be able to directly generate Clang AST to
  108. // construct objects in-place without this.
  109. // TODO: Once we can rely on libc++ being available, consider including
  110. // `<__new/placement_new_delete.h>` instead.
  111. code_stream << R"(# 1 "<carbon-internal>"
  112. #undef constexpr
  113. #if __cplusplus > 202302L
  114. constexpr
  115. #endif
  116. #undef void
  117. #undef operator
  118. #undef new
  119. void* operator new(__SIZE_TYPE__, void*)
  120. #if __cplusplus < 201103L
  121. #undef throw
  122. throw()
  123. #else
  124. #undef noexcept
  125. noexcept
  126. #endif
  127. ;
  128. )";
  129. return code;
  130. }
  131. // Adds the name to the scope with the given `access_kind` and `inst_id`.
  132. // `inst_id` must have a value.
  133. static auto AddNameToScope(Context& context, SemIR::NameScopeId scope_id,
  134. SemIR::NameId name_id, SemIR::AccessKind access_kind,
  135. SemIR::InstId inst_id) -> void {
  136. CARBON_CHECK(inst_id.has_value());
  137. context.name_scopes().Get(scope_id).AddRequired(
  138. {.name_id = name_id,
  139. .result = SemIR::ScopeLookupResult::MakeFound(inst_id, access_kind)});
  140. }
  141. // Maps a Clang name to a Carbon `NameId`.
  142. static auto AddIdentifierName(Context& context, llvm::StringRef name)
  143. -> SemIR::NameId {
  144. return SemIR::NameId::ForIdentifier(context.identifiers().Add(name));
  145. }
  146. // Adds the given source location and an `ImportIRInst` referring to it in
  147. // `ImportIRId::Cpp`.
  148. static auto AddImportIRInst(SemIR::File& file,
  149. clang::SourceLocation clang_source_loc)
  150. -> SemIR::ImportIRInstId {
  151. SemIR::ClangSourceLocId clang_source_loc_id =
  152. file.clang_source_locs().Add(clang_source_loc);
  153. return file.import_ir_insts().Add(SemIR::ImportIRInst(clang_source_loc_id));
  154. }
  155. namespace {
  156. // Used to convert Clang diagnostics to Carbon diagnostics.
  157. //
  158. // Handling of Clang notes is a little subtle: as far as Clang is concerned,
  159. // notes are separate diagnostics, not connected to the error or warning that
  160. // precedes them. But in Carbon's diagnostics system, notes are part of the
  161. // enclosing diagnostic. To handle this, we buffer Clang diagnostics until we
  162. // reach a point where we know we're not in the middle of a diagnostic, and then
  163. // emit a diagnostic along with all of its notes. This is triggered when adding
  164. // or removing a Carbon context note, which could otherwise get attached to the
  165. // wrong C++ diagnostics, and at the end of the Carbon program.
  166. class CarbonClangDiagnosticConsumer : public clang::DiagnosticConsumer {
  167. public:
  168. // Creates an instance with the location that triggers calling Clang. The
  169. // `context` is not stored here, and the diagnostics consumer is expected to
  170. // outlive it.
  171. explicit CarbonClangDiagnosticConsumer(
  172. Context& context, std::shared_ptr<clang::CompilerInvocation> invocation)
  173. : sem_ir_(&context.sem_ir()),
  174. emitter_(&context.emitter()),
  175. invocation_(std::move(invocation)) {
  176. emitter_->AddFlushFn([this] { EmitDiagnostics(); });
  177. }
  178. ~CarbonClangDiagnosticConsumer() override {
  179. // Do not inspect `emitter_` here; it's typically destroyed before the
  180. // consumer is.
  181. // TODO: If Clang produces diagnostics after check finishes, they'll get
  182. // added to the list of pending diagnostics and never emitted.
  183. CARBON_CHECK(diagnostic_infos_.empty(),
  184. "Missing flush before destroying diagnostic consumer");
  185. }
  186. // Generates a Carbon warning for each Clang warning and a Carbon error for
  187. // each Clang error or fatal.
  188. auto HandleDiagnostic(clang::DiagnosticsEngine::Level diag_level,
  189. const clang::Diagnostic& info) -> void override {
  190. DiagnosticConsumer::HandleDiagnostic(diag_level, info);
  191. SemIR::ImportIRInstId clang_import_ir_inst_id =
  192. AddImportIRInst(*sem_ir_, info.getLocation());
  193. llvm::SmallString<256> message;
  194. info.FormatDiagnostic(message);
  195. // Render a code snippet including any highlighted ranges and fixit hints.
  196. // TODO: Also include the #include stack and macro expansion stack in the
  197. // diagnostic output in some way.
  198. RawStringOstream snippet_stream;
  199. if (!info.hasSourceManager()) {
  200. // If we don't have a source manager, this is an error from early in the
  201. // frontend. Don't produce a snippet.
  202. CARBON_CHECK(info.getLocation().isInvalid());
  203. } else {
  204. CodeContextRenderer(snippet_stream, invocation_->getLangOpts(),
  205. invocation_->getDiagnosticOpts())
  206. .emitDiagnostic(
  207. clang::FullSourceLoc(info.getLocation(), info.getSourceManager()),
  208. diag_level, message, info.getRanges(), info.getFixItHints());
  209. }
  210. diagnostic_infos_.push_back({.level = diag_level,
  211. .import_ir_inst_id = clang_import_ir_inst_id,
  212. .message = message.str().str(),
  213. .snippet = snippet_stream.TakeStr()});
  214. }
  215. // Returns the diagnostic to use for a given Clang diagnostic level.
  216. static auto GetDiagnostic(clang::DiagnosticsEngine::Level level)
  217. -> const Diagnostics::DiagnosticBase<std::string>& {
  218. switch (level) {
  219. case clang::DiagnosticsEngine::Ignored: {
  220. CARBON_FATAL("Emitting an ignored diagnostic");
  221. break;
  222. }
  223. case clang::DiagnosticsEngine::Note: {
  224. CARBON_DIAGNOSTIC(CppInteropParseNote, Note, "{0}", std::string);
  225. return CppInteropParseNote;
  226. }
  227. case clang::DiagnosticsEngine::Remark:
  228. case clang::DiagnosticsEngine::Warning: {
  229. // TODO: Add a distinct Remark level to Carbon diagnostics, and stop
  230. // mapping remarks to warnings.
  231. CARBON_DIAGNOSTIC(CppInteropParseWarning, Warning, "{0}", std::string);
  232. return CppInteropParseWarning;
  233. }
  234. case clang::DiagnosticsEngine::Error:
  235. case clang::DiagnosticsEngine::Fatal: {
  236. CARBON_DIAGNOSTIC(CppInteropParseError, Error, "{0}", std::string);
  237. return CppInteropParseError;
  238. }
  239. }
  240. }
  241. // Outputs Carbon diagnostics based on the collected Clang diagnostics. Must
  242. // be called after the AST is set in the context.
  243. auto EmitDiagnostics() -> void {
  244. CARBON_CHECK(sem_ir_->clang_ast_unit(),
  245. "Attempted to emit diagnostics before the AST Unit is loaded");
  246. for (size_t i = 0; i != diagnostic_infos_.size(); ++i) {
  247. const ClangDiagnosticInfo& info = diagnostic_infos_[i];
  248. auto builder = emitter_->Build(SemIR::LocId(info.import_ir_inst_id),
  249. GetDiagnostic(info.level), info.message);
  250. builder.OverrideSnippet(info.snippet);
  251. for (; i + 1 < diagnostic_infos_.size() &&
  252. diagnostic_infos_[i + 1].level == clang::DiagnosticsEngine::Note;
  253. ++i) {
  254. const ClangDiagnosticInfo& note_info = diagnostic_infos_[i + 1];
  255. builder
  256. .Note(SemIR::LocId(note_info.import_ir_inst_id),
  257. GetDiagnostic(note_info.level), note_info.message)
  258. .OverrideSnippet(note_info.snippet);
  259. }
  260. // TODO: This will apply all current Carbon annotation functions. We
  261. // should instead track how Clang's context notes and Carbon's annotation
  262. // functions are interleaved, and interleave the notes in the same order.
  263. builder.Emit();
  264. }
  265. diagnostic_infos_.clear();
  266. }
  267. private:
  268. // A diagnostics renderer based on clang's TextDiagnostic that captures just
  269. // the code context (the snippet).
  270. class CodeContextRenderer : public clang::TextDiagnostic {
  271. public:
  272. using TextDiagnostic::TextDiagnostic;
  273. void emitDiagnosticMessage(
  274. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  275. clang::DiagnosticsEngine::Level /*level*/, llvm::StringRef /*message*/,
  276. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/,
  277. clang::DiagOrStoredDiag /*info*/) override {}
  278. void emitDiagnosticLoc(
  279. clang::FullSourceLoc /*loc*/, clang::PresumedLoc /*ploc*/,
  280. clang::DiagnosticsEngine::Level /*level*/,
  281. llvm::ArrayRef<clang::CharSourceRange> /*ranges*/) override {}
  282. // emitCodeContext is inherited from clang::TextDiagnostic.
  283. void emitIncludeLocation(clang::FullSourceLoc /*loc*/,
  284. clang::PresumedLoc /*ploc*/) override {}
  285. void emitImportLocation(clang::FullSourceLoc /*loc*/,
  286. clang::PresumedLoc /*ploc*/,
  287. llvm::StringRef /*module_name*/) override {}
  288. void emitBuildingModuleLocation(clang::FullSourceLoc /*loc*/,
  289. clang::PresumedLoc /*ploc*/,
  290. llvm::StringRef /*module_name*/) override {}
  291. // beginDiagnostic and endDiagnostic are inherited from
  292. // clang::TextDiagnostic in case it wants to do any setup / teardown work.
  293. };
  294. // Information on a Clang diagnostic that can be converted to a Carbon
  295. // diagnostic.
  296. struct ClangDiagnosticInfo {
  297. // The Clang diagnostic level.
  298. clang::DiagnosticsEngine::Level level;
  299. // The ID of the ImportIR instruction referring to the Clang source
  300. // location.
  301. SemIR::ImportIRInstId import_ir_inst_id;
  302. // The Clang diagnostic textual message.
  303. std::string message;
  304. // The code snippet produced by clang.
  305. std::string snippet;
  306. };
  307. // The Carbon file that this C++ compilation is attached to.
  308. SemIR::File* sem_ir_;
  309. // The diagnostic emitter that we're emitting diagnostics into.
  310. DiagnosticEmitterBase* emitter_;
  311. // The compiler invocation that is producing the diagnostics.
  312. std::shared_ptr<clang::CompilerInvocation> invocation_;
  313. // Collects the information for all Clang diagnostics to be converted to
  314. // Carbon diagnostics after the context has been initialized with the Clang
  315. // AST.
  316. llvm::SmallVector<ClangDiagnosticInfo> diagnostic_infos_;
  317. };
  318. // A wrapper around a clang::CompilerInvocation that allows us to make a shallow
  319. // copy of most of the invocation and only make a deep copy of the parts that we
  320. // want to change.
  321. //
  322. // clang::CowCompilerInvocation almost allows this, but doesn't derive from
  323. // CompilerInvocation or support shallow copies from a CompilerInvocation, so is
  324. // not useful to us as we can't build an ASTUnit from it.
  325. class ShallowCopyCompilerInvocation : public clang::CompilerInvocation {
  326. public:
  327. explicit ShallowCopyCompilerInvocation(
  328. const clang::CompilerInvocation& invocation) {
  329. shallow_copy_assign(invocation);
  330. // The preprocessor options are modified to hold a replacement includes
  331. // buffer, so make our own version of those options.
  332. PPOpts = std::make_shared<clang::PreprocessorOptions>(*PPOpts);
  333. }
  334. };
  335. } // namespace
  336. // Returns an AST for the C++ imports and a bool that represents whether
  337. // compilation errors where encountered or the generated AST is null due to an
  338. // error. Sets the AST in the context's `sem_ir`.
  339. // TODO: Consider to always have a (non-null) AST.
  340. static auto GenerateAst(
  341. Context& context, llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  342. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  343. std::shared_ptr<clang::CompilerInvocation> base_invocation)
  344. -> std::pair<std::unique_ptr<clang::ASTUnit>, bool> {
  345. auto invocation =
  346. std::make_shared<ShallowCopyCompilerInvocation>(*base_invocation);
  347. // Build a diagnostics engine.
  348. llvm::IntrusiveRefCntPtr<clang::DiagnosticsEngine> diags(
  349. clang::CompilerInstance::createDiagnostics(
  350. *fs, invocation->getDiagnosticOpts(),
  351. new CarbonClangDiagnosticConsumer(context, invocation),
  352. /*ShouldOwnClient=*/true));
  353. // Extract the input from the frontend invocation and make sure it makes
  354. // sense.
  355. const auto& inputs = invocation->getFrontendOpts().Inputs;
  356. CARBON_CHECK(inputs.size() == 1 &&
  357. inputs[0].getKind().getLanguage() == clang::Language::CXX &&
  358. inputs[0].getKind().getFormat() == clang::InputKind::Source);
  359. llvm::StringRef file_name = inputs[0].getFile();
  360. // Remap the imports file name to the corresponding `#include`s.
  361. // TODO: Modify the frontend options to specify this memory buffer as input
  362. // instead of remapping the file.
  363. std::string includes = GenerateCppIncludesHeaderCode(context, imports);
  364. auto includes_buffer =
  365. llvm::MemoryBuffer::getMemBufferCopy(includes, file_name);
  366. invocation->getPreprocessorOpts().addRemappedFile(file_name,
  367. includes_buffer.release());
  368. clang::DiagnosticErrorTrap trap(*diags);
  369. // Create the AST unit.
  370. auto ast = clang::ASTUnit::LoadFromCompilerInvocation(
  371. invocation, std::make_shared<clang::PCHContainerOperations>(), nullptr,
  372. diags, new clang::FileManager(invocation->getFileSystemOpts(), fs));
  373. // Attach the AST to SemIR. This needs to be done before we can emit any
  374. // diagnostics, so their locations can be properly interpreted by our
  375. // diagnostics machinery.
  376. context.sem_ir().set_clang_ast_unit(ast.get());
  377. // Emit any diagnostics we queued up while building the AST.
  378. context.emitter().Flush();
  379. return {std::move(ast), !ast || trap.hasErrorOccurred()};
  380. }
  381. // Adds a namespace for the `Cpp` import and returns its `NameScopeId`.
  382. static auto AddNamespace(Context& context, PackageNameId cpp_package_id,
  383. llvm::ArrayRef<Parse::Tree::PackagingNames> imports)
  384. -> SemIR::NameScopeId {
  385. auto& import_cpps = context.sem_ir().import_cpps();
  386. import_cpps.Reserve(imports.size());
  387. for (const Parse::Tree::PackagingNames& import : imports) {
  388. import_cpps.Add({.node_id = context.parse_tree().As<Parse::ImportDeclId>(
  389. import.node_id),
  390. .library_id = import.library_id});
  391. }
  392. return AddImportNamespaceToScope(
  393. context,
  394. GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  395. SemIR::NameId::ForPackageName(cpp_package_id),
  396. SemIR::NameScopeId::Package,
  397. /*diagnose_duplicate_namespace=*/false,
  398. [&]() {
  399. return AddInst<SemIR::ImportCppDecl>(
  400. context,
  401. context.parse_tree().As<Parse::ImportDeclId>(
  402. imports.front().node_id),
  403. {});
  404. })
  405. .add_result.name_scope_id;
  406. }
  407. auto ImportCppFiles(Context& context,
  408. llvm::ArrayRef<Parse::Tree::PackagingNames> imports,
  409. llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> fs,
  410. std::shared_ptr<clang::CompilerInvocation> invocation)
  411. -> std::unique_ptr<clang::ASTUnit> {
  412. if (imports.empty()) {
  413. return nullptr;
  414. }
  415. CARBON_CHECK(!context.sem_ir().clang_ast_unit());
  416. PackageNameId package_id = imports.front().package_id;
  417. CARBON_CHECK(
  418. llvm::all_of(imports, [&](const Parse::Tree::PackagingNames& import) {
  419. return import.package_id == package_id;
  420. }));
  421. auto name_scope_id = AddNamespace(context, package_id, imports);
  422. auto [generated_ast, ast_has_error] =
  423. GenerateAst(context, imports, fs, std::move(invocation));
  424. SemIR::NameScope& name_scope = context.name_scopes().Get(name_scope_id);
  425. name_scope.set_is_closed_import(true);
  426. name_scope.set_clang_decl_context_id(context.clang_decls().Add(
  427. {.decl = generated_ast->getASTContext().getTranslationUnitDecl(),
  428. .inst_id = name_scope.inst_id()}));
  429. if (ast_has_error) {
  430. name_scope.set_has_error();
  431. }
  432. return std::move(generated_ast);
  433. }
  434. // Returns the Clang `DeclContext` for the given name scope. Return the
  435. // translation unit decl if no scope is provided.
  436. static auto GetDeclContext(Context& context, SemIR::NameScopeId scope_id)
  437. -> clang::DeclContext* {
  438. if (!scope_id.has_value()) {
  439. return context.ast_context().getTranslationUnitDecl();
  440. }
  441. auto scope_clang_decl_context_id =
  442. context.name_scopes().Get(scope_id).clang_decl_context_id();
  443. return dyn_cast<clang::DeclContext>(
  444. context.clang_decls().Get(scope_clang_decl_context_id).decl);
  445. }
  446. static auto ClangLookup(Context& context, SemIR::NameScopeId scope_id,
  447. clang::DeclarationName name)
  448. -> std::optional<clang::LookupResult> {
  449. clang::ASTUnit* ast = context.sem_ir().clang_ast_unit();
  450. CARBON_CHECK(ast);
  451. clang::Sema& sema = ast->getSema();
  452. // TODO: Map the LocId of the lookup to a clang SourceLocation and provide it
  453. // here so that clang's diagnostics can point into the carbon code that uses
  454. // the name.
  455. clang::LookupResult lookup(
  456. sema, clang::DeclarationNameInfo(name, clang::SourceLocation()),
  457. clang::Sema::LookupNameKind::LookupOrdinaryName);
  458. bool found =
  459. sema.LookupQualifiedName(lookup, GetDeclContext(context, scope_id));
  460. if (!found) {
  461. return std::nullopt;
  462. }
  463. return lookup;
  464. }
  465. // Looks up the given declaration name in the Clang AST in a specific scope.
  466. // Returns the found declaration and its access. If not found, returns
  467. // `nullopt`. If there's not a single result, returns `nullptr` and default
  468. // access.
  469. static auto ClangLookupDeclarationName(Context& context, SemIR::LocId loc_id,
  470. SemIR::NameScopeId scope_id,
  471. clang::DeclarationName name)
  472. -> std::optional<std::tuple<clang::NamedDecl*, clang::AccessSpecifier>> {
  473. auto lookup = ClangLookup(context, scope_id, name);
  474. if (!lookup) {
  475. return std::nullopt;
  476. }
  477. std::tuple<clang::NamedDecl*, clang::AccessSpecifier> result{
  478. nullptr, clang::AccessSpecifier::AS_none};
  479. // Access checks are performed separately by the Carbon name lookup logic.
  480. lookup->suppressAccessDiagnostics();
  481. if (!lookup->isSingleResult()) {
  482. // Clang will diagnose ambiguous lookup results for us.
  483. if (!lookup->isAmbiguous()) {
  484. context.TODO(loc_id,
  485. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  486. "find a single result; LookupResultKind: {0}",
  487. static_cast<int>(lookup->getResultKind())));
  488. }
  489. return result;
  490. }
  491. result = {lookup->getFoundDecl(), lookup->begin().getAccess()};
  492. return result;
  493. }
  494. // Looks up for constructors in the class scope and returns the lookup result.
  495. static auto ClangConstructorLookup(Context& context,
  496. SemIR::NameScopeId scope_id)
  497. -> clang::DeclContextLookupResult {
  498. const SemIR::NameScope& scope = context.sem_ir().name_scopes().Get(scope_id);
  499. clang::Sema& sema = context.sem_ir().clang_ast_unit()->getSema();
  500. clang::Decl* decl =
  501. context.clang_decls().Get(scope.clang_decl_context_id()).decl;
  502. return sema.LookupConstructors(cast<clang::CXXRecordDecl>(decl));
  503. }
  504. // Returns true if the given Clang declaration is the implicit injected class
  505. // name within the class.
  506. static auto IsDeclInjectedClassName(Context& context,
  507. SemIR::NameScopeId scope_id,
  508. SemIR::NameId name_id,
  509. const clang::NamedDecl* named_decl)
  510. -> bool {
  511. if (!named_decl->isImplicit()) {
  512. return false;
  513. }
  514. const auto* record_decl = dyn_cast<clang::CXXRecordDecl>(named_decl);
  515. if (!record_decl) {
  516. return false;
  517. }
  518. const SemIR::ClangDecl& clang_decl = context.clang_decls().Get(
  519. context.sem_ir().name_scopes().Get(scope_id).clang_decl_context_id());
  520. const auto* scope_record_decl = cast<clang::CXXRecordDecl>(clang_decl.decl);
  521. const clang::ASTContext& ast_context =
  522. context.sem_ir().clang_ast_unit()->getASTContext();
  523. CARBON_CHECK(ast_context.getCanonicalTagType(scope_record_decl) ==
  524. ast_context.getCanonicalTagType(record_decl));
  525. auto class_decl = context.insts().GetAs<SemIR::ClassDecl>(clang_decl.inst_id);
  526. CARBON_CHECK(name_id ==
  527. context.sem_ir().classes().Get(class_decl.class_id).name_id);
  528. return true;
  529. }
  530. // Returns a Clang DeclarationName for the given `NameId`.
  531. static auto GetDeclarationName(Context& context, SemIR::NameId name_id)
  532. -> std::optional<clang::DeclarationName> {
  533. std::optional<llvm::StringRef> name =
  534. context.names().GetAsStringIfIdentifier(name_id);
  535. if (!name) {
  536. // Special names never exist in C++ code.
  537. return std::nullopt;
  538. }
  539. return clang::DeclarationName(context.sem_ir()
  540. .clang_ast_unit()
  541. ->getSema()
  542. .getPreprocessor()
  543. .getIdentifierInfo(*name));
  544. }
  545. // Looks up the given name in the Clang AST in a specific scope. Returns the
  546. // lookup result if lookup was successful.
  547. // TODO: Merge this with `ClangLookupDeclarationName`.
  548. static auto ClangLookupName(Context& context, SemIR::NameScopeId scope_id,
  549. SemIR::NameId name_id)
  550. -> std::optional<clang::LookupResult> {
  551. auto declaration_name = GetDeclarationName(context, name_id);
  552. if (!declaration_name) {
  553. return std::nullopt;
  554. }
  555. return ClangLookup(context, scope_id, *declaration_name);
  556. }
  557. // Returns whether `decl` already mapped to an instruction.
  558. static auto IsClangDeclImported(const Context& context, clang::Decl* decl)
  559. -> bool {
  560. return context.sem_ir()
  561. .clang_decls()
  562. .Lookup(decl->getCanonicalDecl())
  563. .has_value();
  564. }
  565. // If `decl` already mapped to an instruction, returns that instruction.
  566. // Otherwise returns `None`.
  567. static auto LookupClangDeclInstId(Context& context, clang::Decl* decl)
  568. -> SemIR::InstId {
  569. const auto& clang_decls = context.clang_decls();
  570. if (auto context_clang_decl_id = clang_decls.Lookup(decl->getCanonicalDecl());
  571. context_clang_decl_id.has_value()) {
  572. return clang_decls.Get(context_clang_decl_id).inst_id;
  573. }
  574. return SemIR::InstId::None;
  575. }
  576. // Returns the parent of the given declaration. Skips declaration types we
  577. // ignore.
  578. static auto GetParentDecl(clang::Decl* clang_decl) -> clang::Decl* {
  579. auto* parent_dc = clang_decl->getDeclContext();
  580. while (!parent_dc->isLookupContext()) {
  581. parent_dc = parent_dc->getParent();
  582. }
  583. return cast<clang::Decl>(parent_dc);
  584. }
  585. // Returns the given declaration's parent scope. Assumes the parent declaration
  586. // was already imported.
  587. static auto GetParentNameScopeId(Context& context, clang::Decl* clang_decl)
  588. -> SemIR::NameScopeId {
  589. SemIR::InstId parent_inst_id =
  590. LookupClangDeclInstId(context, GetParentDecl(clang_decl));
  591. CARBON_CHECK(parent_inst_id.has_value());
  592. CARBON_KIND_SWITCH(context.insts().Get(parent_inst_id)) {
  593. case CARBON_KIND(SemIR::ClassDecl class_decl): {
  594. return context.classes().Get(class_decl.class_id).scope_id;
  595. }
  596. case CARBON_KIND(SemIR::InterfaceDecl interface_decl): {
  597. return context.interfaces().Get(interface_decl.interface_id).scope_id;
  598. }
  599. case CARBON_KIND(SemIR::Namespace namespace_inst): {
  600. return namespace_inst.name_scope_id;
  601. }
  602. default: {
  603. CARBON_FATAL("Unexpected parent instruction kind");
  604. }
  605. }
  606. }
  607. // Imports a namespace declaration from Clang to Carbon. If successful, returns
  608. // the new Carbon namespace declaration `InstId`. If the declaration was already
  609. // imported, returns the mapped instruction.
  610. static auto ImportNamespaceDecl(Context& context,
  611. clang::NamespaceDecl* clang_decl)
  612. -> SemIR::InstId {
  613. // Check if the declaration is already mapped.
  614. if (SemIR::InstId existing_inst_id =
  615. LookupClangDeclInstId(context, clang_decl);
  616. existing_inst_id.has_value()) {
  617. return existing_inst_id;
  618. }
  619. auto result = AddImportNamespace(
  620. context, GetSingletonType(context, SemIR::NamespaceType::TypeInstId),
  621. AddIdentifierName(context, clang_decl->getName()),
  622. GetParentNameScopeId(context, clang_decl),
  623. /*import_id=*/SemIR::InstId::None);
  624. context.name_scopes()
  625. .Get(result.name_scope_id)
  626. .set_clang_decl_context_id(context.clang_decls().Add(
  627. {.decl = clang_decl->getCanonicalDecl(), .inst_id = result.inst_id}));
  628. return result.inst_id;
  629. }
  630. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  631. clang::QualType type) -> TypeExpr;
  632. // Creates a class declaration for the given class name in the given scope.
  633. // Returns the `InstId` for the declaration.
  634. static auto BuildClassDecl(Context& context,
  635. SemIR::ImportIRInstId import_ir_inst_id,
  636. SemIR::NameScopeId parent_scope_id,
  637. SemIR::NameId name_id)
  638. -> std::tuple<SemIR::ClassId, SemIR::TypeInstId> {
  639. // Add the class declaration.
  640. auto class_decl = SemIR::ClassDecl{.type_id = SemIR::TypeType::TypeId,
  641. .class_id = SemIR::ClassId::None,
  642. .decl_block_id = SemIR::InstBlockId::None};
  643. auto class_decl_id = AddPlaceholderInstInNoBlock(
  644. context,
  645. SemIR::LocIdAndInst::UncheckedLoc(import_ir_inst_id, class_decl));
  646. context.imports().push_back(class_decl_id);
  647. SemIR::Class class_info = {
  648. {.name_id = name_id,
  649. .parent_scope_id = parent_scope_id,
  650. .generic_id = SemIR::GenericId::None,
  651. .first_param_node_id = Parse::NodeId::None,
  652. .last_param_node_id = Parse::NodeId::None,
  653. .pattern_block_id = SemIR::InstBlockId::None,
  654. .implicit_param_patterns_id = SemIR::InstBlockId::None,
  655. .param_patterns_id = SemIR::InstBlockId::None,
  656. .is_extern = false,
  657. .extern_library_id = SemIR::LibraryNameId::None,
  658. .non_owning_decl_id = SemIR::InstId::None,
  659. .first_owning_decl_id = class_decl_id},
  660. {// `.self_type_id` depends on the ClassType, so is set below.
  661. .self_type_id = SemIR::TypeId::None,
  662. // TODO: Support Dynamic classes.
  663. // TODO: Support Final classes.
  664. .inheritance_kind = SemIR::Class::Base}};
  665. class_decl.class_id = context.classes().Add(class_info);
  666. // Write the class ID into the ClassDecl.
  667. ReplaceInstBeforeConstantUse(context, class_decl_id, class_decl);
  668. SetClassSelfType(context, class_decl.class_id);
  669. return {class_decl.class_id, context.types().GetAsTypeInstId(class_decl_id)};
  670. }
  671. // Imports a tag declaration from Clang to Carbon. This covers classes (which
  672. // includes structs and unions) as well as enums. If successful, returns the new
  673. // Carbon class declaration `InstId`.
  674. static auto ImportTagDecl(Context& context, clang::TagDecl* clang_decl)
  675. -> SemIR::InstId {
  676. auto import_ir_inst_id =
  677. AddImportIRInst(context.sem_ir(), clang_decl->getLocation());
  678. auto [class_id, class_inst_id] = BuildClassDecl(
  679. context, import_ir_inst_id, GetParentNameScopeId(context, clang_decl),
  680. AddIdentifierName(context, clang_decl->getName()));
  681. // TODO: The caller does the same lookup. Avoid doing it twice.
  682. auto clang_decl_id = context.clang_decls().Add(
  683. {.decl = clang_decl->getCanonicalDecl(), .inst_id = class_inst_id});
  684. // Name lookup into the Carbon class looks in the C++ class definition.
  685. auto& class_info = context.classes().Get(class_id);
  686. class_info.scope_id = context.name_scopes().Add(
  687. class_inst_id, SemIR::NameId::None, class_info.parent_scope_id);
  688. context.name_scopes()
  689. .Get(class_info.scope_id)
  690. .set_clang_decl_context_id(clang_decl_id);
  691. return class_inst_id;
  692. }
  693. // Determines the Carbon inheritance kind to use for a C++ class definition.
  694. static auto GetInheritanceKind(clang::CXXRecordDecl* class_def)
  695. -> SemIR::Class::InheritanceKind {
  696. if (class_def->isUnion()) {
  697. // Treat all unions as final classes to match their C++ semantics. While we
  698. // could support this, the author of a C++ union has no way to mark their
  699. // type as `final` to prevent it, and so we assume the intent was to
  700. // disallow inheritance.
  701. return SemIR::Class::Final;
  702. }
  703. if (class_def->hasAttr<clang::FinalAttr>()) {
  704. // The class is final in C++; don't allow Carbon types to derive from it.
  705. // Note that such a type might also be abstract in C++; we treat final as
  706. // taking precedence.
  707. //
  708. // We could also treat classes with a final destructor as being final, as
  709. // Clang does when determining whether a class is "effectively final", but
  710. // to keep our rules simpler we do not.
  711. return SemIR::Class::Final;
  712. }
  713. if (class_def->isAbstract()) {
  714. // If the class has any abstract members, it's abstract.
  715. return SemIR::Class::Abstract;
  716. }
  717. // Allow inheritance from any other C++ class type.
  718. return SemIR::Class::Base;
  719. }
  720. // Checks that the specified finished class definition is valid and builds and
  721. // returns a corresponding complete type witness instruction.
  722. static auto ImportClassObjectRepr(Context& context, SemIR::ClassId class_id,
  723. SemIR::ImportIRInstId import_ir_inst_id,
  724. SemIR::TypeInstId class_type_inst_id,
  725. const clang::CXXRecordDecl* clang_def)
  726. -> SemIR::TypeInstId {
  727. if (clang_def->isInvalidDecl()) {
  728. // Clang already diagnosed this error.
  729. return SemIR::ErrorInst::TypeInstId;
  730. }
  731. // For now, if the class is empty, produce an empty struct as the object
  732. // representation. This allows our tests to continue to pass while we don't
  733. // properly support initializing imported C++ classes.
  734. // TODO: Remove this.
  735. if (clang_def->isEmpty() && !clang_def->getNumBases()) {
  736. return context.types().GetAsTypeInstId(AddInst(
  737. context,
  738. MakeImportedLocIdAndInst(
  739. context, import_ir_inst_id,
  740. SemIR::StructType{.type_id = SemIR::TypeType::TypeId,
  741. .fields_id = SemIR::StructTypeFieldsId::Empty})));
  742. }
  743. const auto& clang_layout =
  744. context.ast_context().getASTRecordLayout(clang_def);
  745. llvm::SmallVector<uint64_t> layout;
  746. llvm::SmallVector<SemIR::StructTypeField> fields;
  747. static_assert(SemIR::CustomLayoutId::SizeIndex == 0);
  748. layout.push_back(clang_layout.getSize().getQuantity());
  749. static_assert(SemIR::CustomLayoutId::AlignIndex == 1);
  750. layout.push_back(clang_layout.getAlignment().getQuantity());
  751. static_assert(SemIR::CustomLayoutId::FirstFieldIndex == 2);
  752. // TODO: Import vptr(s).
  753. // Import bases.
  754. for (const auto& base : clang_def->bases()) {
  755. CARBON_CHECK(!base.isVirtual(),
  756. "Should not import definition for class with a virtual base");
  757. auto [base_type_inst_id, base_type_id] =
  758. ImportTypeAndDependencies(context, import_ir_inst_id, base.getType());
  759. if (!base_type_id.has_value()) {
  760. // TODO: If the base class's type can't be mapped, skip it.
  761. continue;
  762. }
  763. auto base_decl_id = AddInst(
  764. context,
  765. MakeImportedLocIdAndInst(
  766. context, import_ir_inst_id,
  767. SemIR::BaseDecl{.type_id = GetUnboundElementType(
  768. context, class_type_inst_id, base_type_inst_id),
  769. .base_type_inst_id = base_type_inst_id,
  770. .index = SemIR::ElementIndex(fields.size())}));
  771. // If there's exactly one base class, treat it as a Carbon base class too.
  772. // TODO: Improve handling for the case where the class has multiple base
  773. // classes.
  774. if (clang_def->getNumBases() == 1) {
  775. auto& class_info = context.classes().Get(class_id);
  776. CARBON_CHECK(!class_info.base_id.has_value());
  777. class_info.base_id = base_decl_id;
  778. }
  779. auto* base_class = base.getType()->getAsCXXRecordDecl();
  780. CARBON_CHECK(base_class, "Base class {0} is not a class",
  781. base.getType().getAsString());
  782. auto base_offset = base.isVirtual()
  783. ? clang_layout.getVBaseClassOffset(base_class)
  784. : clang_layout.getBaseClassOffset(base_class);
  785. layout.push_back(base_offset.getQuantity());
  786. fields.push_back(
  787. {.name_id = SemIR::NameId::Base, .type_inst_id = base_type_inst_id});
  788. }
  789. // Import fields.
  790. for (auto* decl : clang_def->decls()) {
  791. auto* field = dyn_cast<clang::FieldDecl>(decl);
  792. // Track the chain of fields from the class to this field. This chain is
  793. // only one element long unless the field is a member of an anonymous struct
  794. // or union.
  795. clang::NamedDecl* single_field_chain[1] = {field};
  796. llvm::ArrayRef<clang::NamedDecl*> chain = single_field_chain;
  797. // If this isn't a field, it might be an indirect field in an anonymous
  798. // struct or union.
  799. if (!field) {
  800. auto* indirect_field = dyn_cast<clang::IndirectFieldDecl>(decl);
  801. if (!indirect_field) {
  802. continue;
  803. }
  804. chain = indirect_field->chain();
  805. field = indirect_field->getAnonField();
  806. }
  807. if (field->isBitField()) {
  808. // TODO: Add a representation for named bitfield members.
  809. continue;
  810. }
  811. if (field->isAnonymousStructOrUnion()) {
  812. // Fields within an anonymous structure or union will be added via their
  813. // IndirectFieldDecls.
  814. continue;
  815. }
  816. auto field_name_id = AddIdentifierName(context, field->getName());
  817. auto [field_type_inst_id, field_type_id] =
  818. ImportTypeAndDependencies(context, import_ir_inst_id, field->getType());
  819. if (!field_type_inst_id.has_value()) {
  820. // TODO: For now, just skip over fields whose types we can't map.
  821. continue;
  822. }
  823. // Create a field now, as we know the index to use.
  824. // TODO: Consider doing this lazily instead.
  825. auto field_decl_id = AddInst(
  826. context, MakeImportedLocIdAndInst(
  827. context, import_ir_inst_id,
  828. SemIR::FieldDecl{
  829. .type_id = GetUnboundElementType(
  830. context, class_type_inst_id, field_type_inst_id),
  831. .name_id = field_name_id,
  832. .index = SemIR::ElementIndex(fields.size())}));
  833. context.clang_decls().Add(
  834. {.decl = decl->getCanonicalDecl(), .inst_id = field_decl_id});
  835. // Compute the offset to the field that appears directly in the class.
  836. uint64_t offset = clang_layout.getFieldOffset(
  837. cast<clang::FieldDecl>(chain.front())->getFieldIndex());
  838. // If this is an indirect field, walk the path and accumulate the offset to
  839. // the named field.
  840. for (auto* inner_decl : chain.drop_front()) {
  841. auto* inner_field = cast<clang::FieldDecl>(inner_decl);
  842. const auto& inner_layout =
  843. context.ast_context().getASTRecordLayout(inner_field->getParent());
  844. offset += inner_layout.getFieldOffset(inner_field->getFieldIndex());
  845. }
  846. layout.push_back(
  847. context.ast_context().toCharUnitsFromBits(offset).getQuantity());
  848. fields.push_back(
  849. {.name_id = field_name_id, .type_inst_id = field_type_inst_id});
  850. }
  851. // TODO: Add a field to prevent tail padding reuse if necessary.
  852. return AddTypeInst<SemIR::CustomLayoutType>(
  853. context, import_ir_inst_id,
  854. {.type_id = SemIR::TypeType::TypeId,
  855. .fields_id = context.struct_type_fields().Add(fields),
  856. .layout_id = context.custom_layouts().Add(layout)});
  857. }
  858. // Creates a Carbon class definition based on the information in the given Clang
  859. // class declaration, which is assumed to be for a class definition.
  860. static auto BuildClassDefinition(Context& context,
  861. SemIR::ImportIRInstId import_ir_inst_id,
  862. SemIR::ClassId class_id,
  863. SemIR::TypeInstId class_inst_id,
  864. clang::CXXRecordDecl* clang_def) -> void {
  865. auto& class_info = context.classes().Get(class_id);
  866. CARBON_CHECK(!class_info.has_definition_started());
  867. class_info.definition_id = class_inst_id;
  868. context.inst_block_stack().Push();
  869. class_info.inheritance_kind = GetInheritanceKind(clang_def);
  870. // Compute the class's object representation.
  871. auto object_repr_id = ImportClassObjectRepr(
  872. context, class_id, import_ir_inst_id, class_inst_id, clang_def);
  873. class_info.complete_type_witness_id = AddInst<SemIR::CompleteTypeWitness>(
  874. context, import_ir_inst_id,
  875. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  876. .object_repr_type_inst_id = object_repr_id});
  877. class_info.body_block_id = context.inst_block_stack().Pop();
  878. }
  879. // Computes and returns the Carbon type to use as the object representation of
  880. // the given C++ enum type. This is a builtin int type matching the enum's
  881. // representation.
  882. static auto ImportEnumObjectRepresentation(
  883. Context& context, SemIR::ImportIRInstId import_ir_inst_id,
  884. clang::EnumDecl* enum_decl) -> SemIR::TypeInstId {
  885. auto int_type = enum_decl->getIntegerType();
  886. CARBON_CHECK(!int_type.isNull(), "incomplete enum type {0}",
  887. enum_decl->getNameAsString());
  888. auto int_kind = int_type->isSignedIntegerType() ? SemIR::IntKind::Signed
  889. : SemIR::IntKind::Unsigned;
  890. auto bit_width_id = GetOrAddInst<SemIR::IntValue>(
  891. context, import_ir_inst_id,
  892. {.type_id = GetSingletonType(context, SemIR::IntLiteralType::TypeInstId),
  893. .int_id = context.ints().AddUnsigned(
  894. llvm::APInt(64, context.ast_context().getIntWidth(int_type)))});
  895. return context.types().GetAsTypeInstId(
  896. GetOrAddInst(context, SemIR::LocIdAndInst::NoLoc(SemIR::IntType{
  897. .type_id = SemIR::TypeType::TypeId,
  898. .int_kind = int_kind,
  899. .bit_width_id = bit_width_id})));
  900. }
  901. // Creates a Carbon class definition based on the information in the given Clang
  902. // enum declaration.
  903. static auto BuildEnumDefinition(Context& context,
  904. SemIR::ImportIRInstId import_ir_inst_id,
  905. SemIR::ClassId class_id,
  906. SemIR::TypeInstId class_inst_id,
  907. clang::EnumDecl* enum_decl) -> void {
  908. auto& class_info = context.classes().Get(class_id);
  909. CARBON_CHECK(!class_info.has_definition_started());
  910. class_info.definition_id = class_inst_id;
  911. context.inst_block_stack().Push();
  912. // Don't allow inheritance from C++ enums, to match the behavior in C++.
  913. class_info.inheritance_kind = SemIR::Class::Final;
  914. // Compute the enum type's object representation. An enum is an adapter for
  915. // the corresponding builtin integer type.
  916. auto object_repr_id =
  917. ImportEnumObjectRepresentation(context, import_ir_inst_id, enum_decl);
  918. class_info.adapt_id = AddInst(
  919. context, SemIR::LocIdAndInst::UncheckedLoc(
  920. import_ir_inst_id,
  921. SemIR::AdaptDecl{.adapted_type_inst_id = object_repr_id}));
  922. class_info.complete_type_witness_id = AddInst<SemIR::CompleteTypeWitness>(
  923. context, import_ir_inst_id,
  924. {.type_id = GetSingletonType(context, SemIR::WitnessType::TypeInstId),
  925. .object_repr_type_inst_id = object_repr_id});
  926. class_info.body_block_id = context.inst_block_stack().Pop();
  927. }
  928. // Imports an enumerator declaration from Clang to Carbon.
  929. static auto ImportEnumConstantDecl(Context& context,
  930. clang::EnumConstantDecl* enumerator_decl)
  931. -> SemIR::InstId {
  932. CARBON_CHECK(!IsClangDeclImported(context, enumerator_decl));
  933. // Find the enclosing enum type.
  934. auto type_inst_id = LookupClangDeclInstId(
  935. context, cast<clang::EnumDecl>(enumerator_decl->getDeclContext()));
  936. auto type_id = context.types().GetTypeIdForTypeInstId(type_inst_id);
  937. // Build a corresponding IntValue.
  938. auto int_id = context.ints().Add(enumerator_decl->getInitVal());
  939. auto loc_id =
  940. AddImportIRInst(context.sem_ir(), enumerator_decl->getLocation());
  941. auto inst_id = AddInstInNoBlock<SemIR::IntValue>(
  942. context, loc_id, {.type_id = type_id, .int_id = int_id});
  943. context.imports().push_back(inst_id);
  944. context.clang_decls().Add(
  945. {.decl = enumerator_decl->getCanonicalDecl(), .inst_id = inst_id});
  946. return inst_id;
  947. }
  948. // Mark the given `Decl` as failed in `clang_decls`.
  949. static auto MarkFailedDecl(Context& context, clang::Decl* clang_decl) {
  950. context.clang_decls().Add({.decl = clang_decl->getCanonicalDecl(),
  951. .inst_id = SemIR::ErrorInst::InstId});
  952. }
  953. // Creates an integer type of the given size.
  954. static auto MakeIntType(Context& context, IntId size_id, bool is_signed)
  955. -> TypeExpr {
  956. auto type_inst_id = MakeIntTypeLiteral(
  957. context, Parse::NodeId::None,
  958. is_signed ? SemIR::IntKind::Signed : SemIR::IntKind::Unsigned, size_id);
  959. return ExprAsType(context, Parse::NodeId::None, type_inst_id);
  960. }
  961. // Maps a C++ builtin integer type to a Carbon type.
  962. // TODO: Handle integer types that map to named aliases.
  963. static auto MapBuiltinIntegerType(Context& context, SemIR::LocId loc_id,
  964. clang::QualType qual_type,
  965. const clang::BuiltinType& type) -> TypeExpr {
  966. clang::ASTContext& ast_context = context.ast_context();
  967. unsigned width = ast_context.getIntWidth(qual_type);
  968. bool is_signed = type.isSignedInteger();
  969. auto int_n_type = ast_context.getIntTypeForBitwidth(width, is_signed);
  970. if (ast_context.hasSameType(qual_type, int_n_type)) {
  971. TypeExpr type_expr =
  972. MakeIntType(context, context.ints().Add(width), is_signed);
  973. // Try to make sure integer types of 32 or 64 bits are complete so we can
  974. // check against them when deciding whether we need to generate a thunk.
  975. if (width == 32 || width == 64) {
  976. SemIR::TypeId type_id = type_expr.type_id;
  977. if (!context.types().IsComplete(type_id)) {
  978. TryToCompleteType(context, type_id, loc_id);
  979. }
  980. }
  981. return type_expr;
  982. }
  983. if (ast_context.hasSameType(qual_type, ast_context.CharTy)) {
  984. return ExprAsType(context, Parse::NodeId::None,
  985. MakeCharTypeLiteral(context, Parse::NodeId::None));
  986. }
  987. return TypeExpr::None;
  988. }
  989. // Maps a C++ builtin type to a Carbon type.
  990. // TODO: Support more builtin types.
  991. static auto MapBuiltinType(Context& context, SemIR::LocId loc_id,
  992. clang::QualType qual_type,
  993. const clang::BuiltinType& type) -> TypeExpr {
  994. clang::ASTContext& ast_context = context.ast_context();
  995. if (type.isBooleanType()) {
  996. CARBON_CHECK(ast_context.hasSameType(qual_type, ast_context.BoolTy));
  997. return ExprAsType(context, Parse::NodeId::None,
  998. context.types().GetInstId(GetSingletonType(
  999. context, SemIR::BoolType::TypeInstId)));
  1000. }
  1001. if (type.isInteger()) {
  1002. return MapBuiltinIntegerType(context, loc_id, qual_type, type);
  1003. }
  1004. if (type.isFloatingPoint()) {
  1005. if (type.isFloat16Type() || type.isFloat32Type() || type.isDoubleType() ||
  1006. type.isFloat128Type()) {
  1007. return ExprAsType(
  1008. context, Parse::NodeId::None,
  1009. MakeFloatTypeLiteral(
  1010. context, Parse::NodeId::None,
  1011. context.ints().Add(ast_context.getTypeSize(qual_type))));
  1012. }
  1013. // TODO: Handle floating-point types that map to named aliases.
  1014. }
  1015. return TypeExpr::None;
  1016. }
  1017. // Determines whether record_decl is a C++ class that has a custom mapping into
  1018. // Carbon, and if so, returns the corresponding Carbon type. Otherwise returns
  1019. // None.
  1020. static auto LookupCustomRecordType(Context& context,
  1021. const clang::CXXRecordDecl* record_decl)
  1022. -> TypeExpr {
  1023. switch (GetCustomCppTypeMapping(record_decl)) {
  1024. case CustomCppTypeMapping::None:
  1025. return TypeExpr::None;
  1026. case CustomCppTypeMapping::Str:
  1027. return MakeStringType(
  1028. context,
  1029. AddImportIRInst(context.sem_ir(), record_decl->getLocation()));
  1030. }
  1031. }
  1032. // Maps a C++ tag type (class, struct, union, enum) to a Carbon type.
  1033. static auto MapTagType(Context& context, const clang::TagType& type)
  1034. -> TypeExpr {
  1035. auto* tag_decl = type.getOriginalDecl();
  1036. CARBON_CHECK(tag_decl);
  1037. // Check if the declaration is already mapped.
  1038. SemIR::InstId tag_inst_id = LookupClangDeclInstId(context, tag_decl);
  1039. if (!tag_inst_id.has_value()) {
  1040. if (auto* record_decl = dyn_cast<clang::CXXRecordDecl>(tag_decl)) {
  1041. auto custom_type = LookupCustomRecordType(context, record_decl);
  1042. if (custom_type.inst_id.has_value()) {
  1043. context.clang_decls().Add(
  1044. {.decl = record_decl, .inst_id = custom_type.inst_id});
  1045. return custom_type;
  1046. }
  1047. }
  1048. tag_inst_id = ImportTagDecl(context, tag_decl);
  1049. }
  1050. SemIR::TypeInstId record_type_inst_id =
  1051. context.types().GetAsTypeInstId(tag_inst_id);
  1052. return {
  1053. .inst_id = record_type_inst_id,
  1054. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  1055. }
  1056. // Maps a C++ type that is not a wrapper type such as a pointer to a Carbon
  1057. // type.
  1058. // TODO: Support more types.
  1059. static auto MapNonWrapperType(Context& context, SemIR::LocId loc_id,
  1060. clang::QualType type) -> TypeExpr {
  1061. if (const auto* builtin_type = type->getAs<clang::BuiltinType>()) {
  1062. return MapBuiltinType(context, loc_id, type, *builtin_type);
  1063. }
  1064. if (const auto* tag_type = type->getAs<clang::TagType>()) {
  1065. return MapTagType(context, *tag_type);
  1066. }
  1067. CARBON_CHECK(!type.hasQualifiers() && !type->isPointerType(),
  1068. "Should not see wrapper types here");
  1069. return TypeExpr::None;
  1070. }
  1071. // Maps a qualified C++ type to a Carbon type.
  1072. static auto MapQualifiedType(Context& context, clang::QualType type,
  1073. TypeExpr type_expr) -> TypeExpr {
  1074. auto quals = type.getQualifiers();
  1075. if (quals.hasConst()) {
  1076. auto type_id = GetConstType(context, type_expr.inst_id);
  1077. type_expr = {.inst_id = context.types().GetInstId(type_id),
  1078. .type_id = type_id};
  1079. quals.removeConst();
  1080. }
  1081. // TODO: Support other qualifiers.
  1082. if (!quals.empty()) {
  1083. return TypeExpr::None;
  1084. }
  1085. return type_expr;
  1086. }
  1087. // Maps a C++ pointer type to a Carbon pointer type.
  1088. static auto MapPointerType(Context& context, clang::QualType type,
  1089. TypeExpr pointee_type_expr) -> TypeExpr {
  1090. CARBON_CHECK(type->isPointerType());
  1091. if (auto nullability = type->getNullability();
  1092. !nullability.has_value() ||
  1093. *nullability != clang::NullabilityKind::NonNull) {
  1094. // If the type was produced by C++ template substitution, then we assume it
  1095. // was deduced from a Carbon pointer type, so it's non-null.
  1096. if (!type->getAs<clang::SubstTemplateTypeParmType>()) {
  1097. // TODO: Support nullable pointers.
  1098. return TypeExpr::None;
  1099. }
  1100. }
  1101. SemIR::TypeId pointer_type_id =
  1102. GetPointerType(context, pointee_type_expr.inst_id);
  1103. return {.inst_id = context.types().GetInstId(pointer_type_id),
  1104. .type_id = pointer_type_id};
  1105. }
  1106. // Maps a C++ type to a Carbon type. `type` should not be canonicalized because
  1107. // we check for pointer nullability and nullability will be lost by
  1108. // canonicalization.
  1109. static auto MapType(Context& context, SemIR::LocId loc_id, clang::QualType type)
  1110. -> TypeExpr {
  1111. // Unwrap any type modifiers and wrappers.
  1112. llvm::SmallVector<clang::QualType> wrapper_types;
  1113. while (true) {
  1114. clang::QualType orig_type = type;
  1115. if (type.hasQualifiers()) {
  1116. type = type.getUnqualifiedType();
  1117. } else if (type->isPointerType()) {
  1118. type = type->getPointeeType();
  1119. } else {
  1120. break;
  1121. }
  1122. wrapper_types.push_back(orig_type);
  1123. }
  1124. auto mapped = MapNonWrapperType(context, loc_id, type);
  1125. for (auto wrapper : llvm::reverse(wrapper_types)) {
  1126. if (!mapped.inst_id.has_value() ||
  1127. mapped.type_id == SemIR::ErrorInst::TypeId) {
  1128. break;
  1129. }
  1130. if (wrapper.hasQualifiers()) {
  1131. mapped = MapQualifiedType(context, wrapper, mapped);
  1132. } else if (wrapper->isPointerType()) {
  1133. mapped = MapPointerType(context, wrapper, mapped);
  1134. } else {
  1135. CARBON_FATAL("Unexpected wrapper type {0}", wrapper.getAsString());
  1136. }
  1137. }
  1138. return mapped;
  1139. }
  1140. // Returns a block for the implicit parameters of the given function
  1141. // declaration. Because function templates are not yet supported, this currently
  1142. // only contains the `self` parameter. On error, produces a diagnostic and
  1143. // returns None.
  1144. static auto MakeImplicitParamPatternsBlockId(
  1145. Context& context, SemIR::LocId loc_id,
  1146. const clang::FunctionDecl& clang_decl) -> SemIR::InstBlockId {
  1147. const auto* method_decl = dyn_cast<clang::CXXMethodDecl>(&clang_decl);
  1148. if (!method_decl || method_decl->isStatic() ||
  1149. isa<clang::CXXConstructorDecl>(clang_decl)) {
  1150. return SemIR::InstBlockId::Empty;
  1151. }
  1152. // Build a `self` parameter from the object parameter.
  1153. BeginSubpattern(context);
  1154. // Perform some special-case mapping for the object parameter:
  1155. //
  1156. // - If it's a const reference to T, produce a by-value `self: T` parameter.
  1157. // - If it's a non-const reference to T, produce an `addr self: T*`
  1158. // parameter.
  1159. // - Otherwise, map it directly, which will currently fail for `&&`-qualified
  1160. // methods.
  1161. //
  1162. // TODO: Some of this mapping should be performed for all parameters.
  1163. clang::QualType param_type =
  1164. method_decl->getFunctionObjectParameterReferenceType();
  1165. bool addr_self = false;
  1166. if (param_type->isLValueReferenceType()) {
  1167. param_type = param_type.getNonReferenceType();
  1168. if (param_type.isConstQualified()) {
  1169. // TODO: Consider only doing this if `const` is the only qualifier. For
  1170. // now, any other qualifier will fail when mapping the type.
  1171. auto split_type = param_type.getSplitUnqualifiedType();
  1172. split_type.Quals.removeConst();
  1173. param_type = method_decl->getASTContext().getQualifiedType(split_type);
  1174. } else {
  1175. addr_self = true;
  1176. }
  1177. }
  1178. auto [type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1179. SemIR::ExprRegionId type_expr_region_id =
  1180. EndSubpatternAsExpr(context, type_inst_id);
  1181. if (!type_id.has_value()) {
  1182. context.TODO(loc_id,
  1183. llvm::formatv("Unsupported: object parameter type: {0}",
  1184. param_type.getAsString()));
  1185. return SemIR::InstBlockId::None;
  1186. }
  1187. // TODO: Fill in a location once available.
  1188. auto pattern_id =
  1189. addr_self ? AddAddrSelfParamPattern(context, SemIR::LocId::None,
  1190. type_expr_region_id, type_inst_id)
  1191. : AddSelfParamPattern(context, SemIR::LocId::None,
  1192. type_expr_region_id, type_id);
  1193. return context.inst_blocks().Add({pattern_id});
  1194. }
  1195. // Returns a block id for the explicit parameters of the given function
  1196. // declaration. If the function declaration has no parameters, it returns
  1197. // `SemIR::InstBlockId::Empty`. In the case of an unsupported parameter type, it
  1198. // produces an error and returns `SemIR::InstBlockId::None`.
  1199. // TODO: Consider refactoring to extract and reuse more logic from
  1200. // `HandleAnyBindingPattern()`.
  1201. static auto MakeParamPatternsBlockId(Context& context, SemIR::LocId loc_id,
  1202. const clang::FunctionDecl& clang_decl)
  1203. -> SemIR::InstBlockId {
  1204. if (clang_decl.parameters().empty()) {
  1205. return SemIR::InstBlockId::Empty;
  1206. }
  1207. llvm::SmallVector<SemIR::InstId> params;
  1208. params.reserve(clang_decl.getNumNonObjectParams());
  1209. for (unsigned i : llvm::seq(clang_decl.getNumNonObjectParams())) {
  1210. const auto* param = clang_decl.getNonObjectParameter(i);
  1211. // TODO: Get the parameter type from the function, not from the
  1212. // `ParmVarDecl`. The type of the `ParmVarDecl` is the type within the
  1213. // function, and isn't in general the same as the type that's exposed to
  1214. // callers. In particular, the parameter type exposed to callers will never
  1215. // be cv-qualified.
  1216. clang::QualType param_type = param->getType();
  1217. // We map `T&` parameters to `addr param: T*`, and `T&&` parameters to
  1218. // `param: T`.
  1219. // TODO: Revisit this and decide what we really want to do here.
  1220. bool is_ref_param = param_type->isLValueReferenceType();
  1221. param_type = param_type.getNonReferenceType();
  1222. // Mark the start of a region of insts, needed for the type expression
  1223. // created later with the call of `EndSubpatternAsExpr()`.
  1224. BeginSubpattern(context);
  1225. auto [orig_type_inst_id, type_id] = MapType(context, loc_id, param_type);
  1226. // Type expression of the binding pattern - a single-entry/single-exit
  1227. // region that allows control flow in the type expression e.g. fn F(x: if C
  1228. // then i32 else i64).
  1229. SemIR::ExprRegionId type_expr_region_id =
  1230. EndSubpatternAsExpr(context, orig_type_inst_id);
  1231. if (!type_id.has_value()) {
  1232. context.TODO(loc_id, llvm::formatv("Unsupported: parameter type: {0}",
  1233. param->getType().getAsString()));
  1234. return SemIR::InstBlockId::None;
  1235. }
  1236. if (is_ref_param) {
  1237. type_id = GetPointerType(context, orig_type_inst_id);
  1238. }
  1239. llvm::StringRef param_name = param->getName();
  1240. SemIR::NameId name_id =
  1241. param_name.empty()
  1242. // Translate an unnamed parameter to an underscore to
  1243. // match Carbon's naming of unnamed/unused function params.
  1244. ? SemIR::NameId::Underscore
  1245. : AddIdentifierName(context, param_name);
  1246. // TODO: Fix this once templates are supported.
  1247. bool is_template = false;
  1248. // TODO: Fix this once generics are supported.
  1249. bool is_generic = false;
  1250. SemIR::InstId pattern_id =
  1251. // TODO: Fill in a location once available.
  1252. AddBindingPattern(context, SemIR::LocId::None, name_id, type_id,
  1253. type_expr_region_id, is_generic, is_template)
  1254. .pattern_id;
  1255. pattern_id = AddPatternInst(
  1256. context,
  1257. // TODO: Fill in a location once available.
  1258. SemIR::LocIdAndInst::NoLoc(SemIR::ValueParamPattern(
  1259. {.type_id = context.insts().Get(pattern_id).type_id(),
  1260. .subpattern_id = pattern_id,
  1261. .index = SemIR::CallParamIndex::None})));
  1262. if (is_ref_param) {
  1263. pattern_id = AddPatternInst(
  1264. context,
  1265. // TODO: Fill in a location once available.
  1266. SemIR::LocIdAndInst::NoLoc(SemIR::AddrPattern(
  1267. {.type_id = GetPatternType(
  1268. context,
  1269. context.types().GetTypeIdForTypeInstId(orig_type_inst_id)),
  1270. .inner_id = pattern_id})));
  1271. }
  1272. params.push_back(pattern_id);
  1273. }
  1274. return context.inst_blocks().Add(params);
  1275. }
  1276. // Returns the return `TypeExpr` of the given function declaration. In case of
  1277. // an unsupported return type, returns `SemIR::ErrorInst::InstId`. Constructors
  1278. // are treated as returning a class instance.
  1279. // TODO: Support more return types.
  1280. static auto GetReturnTypeExpr(Context& context, SemIR::LocId loc_id,
  1281. clang::FunctionDecl* clang_decl) -> TypeExpr {
  1282. clang::QualType ret_type = clang_decl->getReturnType();
  1283. if (!ret_type->isVoidType()) {
  1284. TypeExpr mapped_type = MapType(context, loc_id, ret_type);
  1285. if (!mapped_type.inst_id.has_value()) {
  1286. context.TODO(loc_id, llvm::formatv("Unsupported: return type: {0}",
  1287. ret_type.getAsString()));
  1288. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1289. .type_id = SemIR::ErrorInst::TypeId};
  1290. }
  1291. return mapped_type;
  1292. }
  1293. if (!isa<clang::CXXConstructorDecl>(clang_decl)) {
  1294. // void.
  1295. return TypeExpr::None;
  1296. }
  1297. // TODO: Make this a `PartialType`.
  1298. SemIR::TypeInstId record_type_inst_id = context.types().GetAsTypeInstId(
  1299. context.sem_ir()
  1300. .clang_decls()
  1301. .Get(context.clang_decls().Lookup(
  1302. cast<clang::Decl>(clang_decl->getParent())))
  1303. .inst_id);
  1304. return {
  1305. .inst_id = record_type_inst_id,
  1306. .type_id = context.types().GetTypeIdForTypeInstId(record_type_inst_id)};
  1307. }
  1308. // Returns the return pattern of the given function declaration. In case of an
  1309. // unsupported return type, it produces a diagnostic and returns
  1310. // `SemIR::ErrorInst::InstId`. Constructors are treated as returning a class
  1311. // instance.
  1312. static auto GetReturnPattern(Context& context, SemIR::LocId loc_id,
  1313. clang::FunctionDecl* clang_decl) -> SemIR::InstId {
  1314. auto [type_inst_id, type_id] = GetReturnTypeExpr(context, loc_id, clang_decl);
  1315. if (!type_inst_id.has_value()) {
  1316. // void.
  1317. return SemIR::InstId::None;
  1318. }
  1319. auto pattern_type_id = GetPatternType(context, type_id);
  1320. SemIR::InstId return_slot_pattern_id = AddPatternInst(
  1321. // TODO: Fill in a location for the return type once available.
  1322. context,
  1323. SemIR::LocIdAndInst::NoLoc(SemIR::ReturnSlotPattern(
  1324. {.type_id = pattern_type_id, .type_inst_id = type_inst_id})));
  1325. SemIR::InstId param_pattern_id = AddPatternInst(
  1326. // TODO: Fill in a location for the return type once available.
  1327. context, SemIR::LocIdAndInst::NoLoc(SemIR::OutParamPattern(
  1328. {.type_id = pattern_type_id,
  1329. .subpattern_id = return_slot_pattern_id,
  1330. .index = SemIR::CallParamIndex::None})));
  1331. return param_pattern_id;
  1332. }
  1333. namespace {
  1334. // Represents the parameter patterns block id, the return slot pattern id and
  1335. // the call parameters block id for a function declaration.
  1336. struct FunctionParamsInsts {
  1337. SemIR::InstBlockId implicit_param_patterns_id;
  1338. SemIR::InstBlockId param_patterns_id;
  1339. SemIR::InstId return_slot_pattern_id;
  1340. SemIR::InstBlockId call_params_id;
  1341. };
  1342. } // namespace
  1343. // Creates a block containing the parameter pattern instructions for the
  1344. // explicit parameters, a parameter pattern instruction for the return type and
  1345. // a block containing the call parameters of the function. Emits a callee
  1346. // pattern-match for the explicit parameter patterns and the return slot pattern
  1347. // to create the Call parameters instructions block. Currently the implicit
  1348. // parameter patterns are not taken into account. Returns the parameter patterns
  1349. // block id, the return slot pattern id, and the call parameters block id.
  1350. // Produces a diagnostic and returns `std::nullopt` if the function declaration
  1351. // has an unsupported parameter type.
  1352. static auto CreateFunctionParamsInsts(Context& context, SemIR::LocId loc_id,
  1353. clang::FunctionDecl* clang_decl)
  1354. -> std::optional<FunctionParamsInsts> {
  1355. if (isa<clang::CXXDestructorDecl>(clang_decl)) {
  1356. context.TODO(loc_id, "Unsupported: Destructor");
  1357. return std::nullopt;
  1358. }
  1359. auto implicit_param_patterns_id =
  1360. MakeImplicitParamPatternsBlockId(context, loc_id, *clang_decl);
  1361. if (!implicit_param_patterns_id.has_value()) {
  1362. return std::nullopt;
  1363. }
  1364. auto param_patterns_id =
  1365. MakeParamPatternsBlockId(context, loc_id, *clang_decl);
  1366. if (!param_patterns_id.has_value()) {
  1367. return std::nullopt;
  1368. }
  1369. auto return_slot_pattern_id = GetReturnPattern(context, loc_id, clang_decl);
  1370. if (SemIR::ErrorInst::InstId == return_slot_pattern_id) {
  1371. return std::nullopt;
  1372. }
  1373. auto call_params_id =
  1374. CalleePatternMatch(context, implicit_param_patterns_id, param_patterns_id,
  1375. return_slot_pattern_id);
  1376. return {{.implicit_param_patterns_id = implicit_param_patterns_id,
  1377. .param_patterns_id = param_patterns_id,
  1378. .return_slot_pattern_id = return_slot_pattern_id,
  1379. .call_params_id = call_params_id}};
  1380. }
  1381. // Returns the Carbon function name for the given function.
  1382. static auto GetFunctionName(Context& context, clang::FunctionDecl* clang_decl)
  1383. -> SemIR::NameId {
  1384. switch (clang_decl->getDeclName().getNameKind()) {
  1385. case clang::DeclarationName::CXXConstructorName: {
  1386. return context.classes()
  1387. .Get(context.insts()
  1388. .GetAs<SemIR::ClassDecl>(LookupClangDeclInstId(
  1389. context, cast<clang::Decl>(clang_decl->getParent())))
  1390. .class_id)
  1391. .name_id;
  1392. }
  1393. case clang::DeclarationName::CXXOperatorName: {
  1394. return SemIR::NameId::CppOperator;
  1395. }
  1396. default: {
  1397. return AddIdentifierName(context, clang_decl->getName());
  1398. }
  1399. }
  1400. }
  1401. // Creates a `FunctionDecl` and a `Function` without C++ thunk information.
  1402. // Returns std::nullopt on failure. The given Clang declaration is assumed to:
  1403. // * Have not been imported before.
  1404. // * Be of supported type (ignoring parameters).
  1405. static auto ImportFunction(Context& context, SemIR::LocId loc_id,
  1406. clang::FunctionDecl* clang_decl)
  1407. -> std::optional<SemIR::FunctionId> {
  1408. context.scope_stack().PushForDeclName();
  1409. context.inst_block_stack().Push();
  1410. context.pattern_block_stack().Push();
  1411. auto function_params_insts =
  1412. CreateFunctionParamsInsts(context, loc_id, clang_decl);
  1413. auto pattern_block_id = context.pattern_block_stack().Pop();
  1414. auto decl_block_id = context.inst_block_stack().Pop();
  1415. context.scope_stack().Pop();
  1416. if (!function_params_insts.has_value()) {
  1417. return std::nullopt;
  1418. }
  1419. auto function_decl = SemIR::FunctionDecl{
  1420. SemIR::TypeId::None, SemIR::FunctionId::None, decl_block_id};
  1421. auto decl_id =
  1422. AddPlaceholderInstInNoBlock(context, Parse::NodeId::None, function_decl);
  1423. context.imports().push_back(decl_id);
  1424. auto virtual_modifier = SemIR::Function::VirtualModifier::None;
  1425. int32_t virtual_index = -1;
  1426. if (auto* method_decl = dyn_cast<clang::CXXMethodDecl>(clang_decl)) {
  1427. if (method_decl->size_overridden_methods()) {
  1428. virtual_modifier = SemIR::Function::VirtualModifier::Override;
  1429. } else if (method_decl->isVirtual()) {
  1430. virtual_modifier = SemIR::Function::VirtualModifier::Virtual;
  1431. }
  1432. if (virtual_modifier != SemIR::Function::VirtualModifier::None) {
  1433. // TODO: Add support for Microsoft/non-Itanium vtables.
  1434. virtual_index = dyn_cast<clang::ItaniumVTableContext>(
  1435. context.ast_context().getVTableContext())
  1436. ->getMethodVTableIndex(method_decl);
  1437. }
  1438. }
  1439. auto function_info = SemIR::Function{
  1440. {.name_id = GetFunctionName(context, clang_decl),
  1441. .parent_scope_id = GetParentNameScopeId(context, clang_decl),
  1442. .generic_id = SemIR::GenericId::None,
  1443. .first_param_node_id = Parse::NodeId::None,
  1444. .last_param_node_id = Parse::NodeId::None,
  1445. .pattern_block_id = pattern_block_id,
  1446. .implicit_param_patterns_id =
  1447. function_params_insts->implicit_param_patterns_id,
  1448. .param_patterns_id = function_params_insts->param_patterns_id,
  1449. .is_extern = false,
  1450. .extern_library_id = SemIR::LibraryNameId::None,
  1451. .non_owning_decl_id = SemIR::InstId::None,
  1452. .first_owning_decl_id = decl_id,
  1453. .definition_id = SemIR::InstId::None},
  1454. {.call_params_id = function_params_insts->call_params_id,
  1455. .return_slot_pattern_id = function_params_insts->return_slot_pattern_id,
  1456. .virtual_modifier = virtual_modifier,
  1457. .virtual_index = virtual_index,
  1458. .self_param_id = FindSelfPattern(
  1459. context, function_params_insts->implicit_param_patterns_id),
  1460. .clang_decl_id = context.clang_decls().Add(
  1461. {.decl = clang_decl, .inst_id = decl_id})}};
  1462. function_decl.function_id = context.functions().Add(function_info);
  1463. function_decl.type_id = GetFunctionType(context, function_decl.function_id,
  1464. SemIR::SpecificId::None);
  1465. ReplaceInstBeforeConstantUse(context, decl_id, function_decl);
  1466. return function_decl.function_id;
  1467. }
  1468. auto ImportCppFunctionDecl(Context& context, SemIR::LocId loc_id,
  1469. clang::FunctionDecl* clang_decl) -> SemIR::InstId {
  1470. // Check if the declaration is already mapped.
  1471. if (SemIR::InstId existing_inst_id =
  1472. LookupClangDeclInstId(context, clang_decl);
  1473. existing_inst_id.has_value()) {
  1474. return existing_inst_id;
  1475. }
  1476. if (clang_decl->isVariadic()) {
  1477. context.TODO(loc_id, "Unsupported: Variadic function");
  1478. MarkFailedDecl(context, clang_decl);
  1479. return SemIR::ErrorInst::InstId;
  1480. }
  1481. if (clang_decl->getTemplatedKind() ==
  1482. clang::FunctionDecl::TK_FunctionTemplate) {
  1483. context.TODO(loc_id, "Unsupported: Template function");
  1484. MarkFailedDecl(context, clang_decl);
  1485. return SemIR::ErrorInst::InstId;
  1486. }
  1487. CARBON_CHECK(clang_decl->getFunctionType()->isFunctionProtoType(),
  1488. "Not Prototype function (non-C++ code)");
  1489. auto function_id = ImportFunction(context, loc_id, clang_decl);
  1490. if (!function_id) {
  1491. MarkFailedDecl(context, clang_decl);
  1492. return SemIR::ErrorInst::InstId;
  1493. }
  1494. SemIR::Function& function_info = context.functions().Get(*function_id);
  1495. if (IsCppThunkRequired(context, function_info)) {
  1496. clang::FunctionDecl* thunk_clang_decl =
  1497. BuildCppThunk(context, function_info);
  1498. if (thunk_clang_decl) {
  1499. SemIR::FunctionId thunk_function_id =
  1500. *ImportFunction(context, loc_id, thunk_clang_decl);
  1501. SemIR::InstId thunk_function_decl_id =
  1502. context.functions().Get(thunk_function_id).first_owning_decl_id;
  1503. function_info.SetHasCppThunk(thunk_function_decl_id);
  1504. }
  1505. }
  1506. return function_info.first_owning_decl_id;
  1507. }
  1508. namespace {
  1509. // An item to be imported in an import worklist.
  1510. // TODO: If worklists ever become particularly large, consider changing this
  1511. // to use a `PointerIntPair`.
  1512. struct ImportItem {
  1513. // A declaration that we want to import.
  1514. clang::Decl* decl;
  1515. // Whether we have added `decl`'s dependencies to the worklist.
  1516. bool added_dependencies;
  1517. };
  1518. // A worklist of declarations to import.
  1519. using ImportWorklist = llvm::SmallVector<ImportItem>;
  1520. } // namespace
  1521. // Adds the given declaration to our list of declarations to import.
  1522. static auto AddDependentDecl(const Context& context, clang::Decl* decl,
  1523. ImportWorklist& worklist) -> void {
  1524. if (!IsClangDeclImported(context, decl)) {
  1525. worklist.push_back({.decl = decl, .added_dependencies = false});
  1526. }
  1527. }
  1528. // Finds all decls that need to be imported before importing the given type and
  1529. // adds them to the given set.
  1530. static auto AddDependentUnimportedTypeDecls(const Context& context,
  1531. clang::QualType type,
  1532. ImportWorklist& worklist) -> void {
  1533. while (true) {
  1534. if (type->isPointerType() || type->isReferenceType()) {
  1535. type = type->getPointeeType();
  1536. } else if (const clang::ArrayType* array_type =
  1537. type->getAsArrayTypeUnsafe()) {
  1538. type = array_type->getElementType();
  1539. } else {
  1540. break;
  1541. }
  1542. }
  1543. if (const auto* tag_type = type->getAs<clang::TagType>()) {
  1544. AddDependentDecl(context, tag_type->getOriginalDecl(), worklist);
  1545. }
  1546. }
  1547. // Finds all decls that need to be imported before importing the given function
  1548. // and adds them to the given set.
  1549. static auto AddDependentUnimportedFunctionDecls(
  1550. const Context& context, const clang::FunctionDecl& clang_decl,
  1551. ImportWorklist& worklist) -> void {
  1552. for (const auto* param : clang_decl.parameters()) {
  1553. AddDependentUnimportedTypeDecls(context, param->getType(), worklist);
  1554. }
  1555. AddDependentUnimportedTypeDecls(context, clang_decl.getReturnType(),
  1556. worklist);
  1557. }
  1558. // Finds all decls that need to be imported before importing the given
  1559. // declaration and adds them to the given set.
  1560. static auto AddDependentUnimportedDecls(const Context& context,
  1561. clang::Decl* clang_decl,
  1562. ImportWorklist& worklist) -> void {
  1563. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1564. AddDependentUnimportedFunctionDecls(context, *clang_function_decl,
  1565. worklist);
  1566. } else if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1567. if (!isa<clang::TagDecl>(clang_decl)) {
  1568. AddDependentUnimportedTypeDecls(
  1569. context, type_decl->getASTContext().getTypeDeclType(type_decl),
  1570. worklist);
  1571. }
  1572. }
  1573. if (!isa<clang::TranslationUnitDecl>(clang_decl)) {
  1574. AddDependentDecl(context, GetParentDecl(clang_decl), worklist);
  1575. }
  1576. }
  1577. static auto ImportVarDecl(Context& context, SemIR::LocId loc_id,
  1578. clang::VarDecl* var_decl) -> SemIR::InstId {
  1579. if (SemIR::InstId existing_inst_id = LookupClangDeclInstId(context, var_decl);
  1580. existing_inst_id.has_value()) {
  1581. return existing_inst_id;
  1582. }
  1583. // Extract type and name.
  1584. clang::QualType var_type = var_decl->getType();
  1585. SemIR::TypeId var_type_id = MapType(context, loc_id, var_type).type_id;
  1586. if (!var_type_id.has_value()) {
  1587. context.TODO(loc_id, llvm::formatv("Unsupported: var type: {0}",
  1588. var_type.getAsString()));
  1589. return SemIR::ErrorInst::InstId;
  1590. }
  1591. SemIR::NameId var_name_id = AddIdentifierName(context, var_decl->getName());
  1592. SemIR::VarStorage var_storage{.type_id = var_type_id,
  1593. .pattern_id = SemIR::InstId::None};
  1594. // We can't use the convenience for `AddPlaceholderInstInNoBlock()` with typed
  1595. // nodes because it doesn't support insts with cleanup.
  1596. SemIR::InstId var_storage_inst_id =
  1597. AddPlaceholderInstInNoBlock(context, {loc_id, var_storage});
  1598. auto clang_decl_id = context.clang_decls().Add(
  1599. {.decl = var_decl, .inst_id = var_storage_inst_id});
  1600. // Entity name referring to a Clang decl for mangling.
  1601. SemIR::EntityNameId entity_name_id =
  1602. context.entity_names().AddSymbolicBindingName(
  1603. var_name_id, GetParentNameScopeId(context, var_decl),
  1604. SemIR::CompileTimeBindIndex::None, false, clang_decl_id);
  1605. // Create `BindingPattern` and `VarPattern` in a `NameBindingDecl`.
  1606. context.pattern_block_stack().Push();
  1607. SemIR::TypeId pattern_type_id = GetPatternType(context, var_type_id);
  1608. SemIR::InstId binding_pattern_inst_id = AddPatternInst<SemIR::BindingPattern>(
  1609. context, loc_id,
  1610. {.type_id = pattern_type_id, .entity_name_id = entity_name_id});
  1611. var_storage.pattern_id = AddPatternInst<SemIR::VarPattern>(
  1612. context, Parse::VariablePatternId::None,
  1613. {.type_id = pattern_type_id, .subpattern_id = binding_pattern_inst_id});
  1614. context.imports().push_back(AddInstInNoBlock<SemIR::NameBindingDecl>(
  1615. context, loc_id,
  1616. {.pattern_block_id = context.pattern_block_stack().Pop()}));
  1617. // Finalize the `VarStorage` instruction.
  1618. ReplaceInstBeforeConstantUse(context, var_storage_inst_id, var_storage);
  1619. context.imports().push_back(var_storage_inst_id);
  1620. return var_storage_inst_id;
  1621. }
  1622. // Imports a declaration from Clang to Carbon. Returns the instruction for the
  1623. // new Carbon declaration, which will be an ErrorInst on failure. Assumes all
  1624. // dependencies have already been imported.
  1625. static auto ImportDeclAfterDependencies(Context& context, SemIR::LocId loc_id,
  1626. clang::Decl* clang_decl)
  1627. -> SemIR::InstId {
  1628. if (auto* clang_function_decl = clang_decl->getAsFunction()) {
  1629. return ImportCppFunctionDecl(context, loc_id, clang_function_decl);
  1630. }
  1631. if (auto* clang_namespace_decl = dyn_cast<clang::NamespaceDecl>(clang_decl)) {
  1632. return ImportNamespaceDecl(context, clang_namespace_decl);
  1633. }
  1634. if (auto* type_decl = dyn_cast<clang::TypeDecl>(clang_decl)) {
  1635. auto type = clang_decl->getASTContext().getTypeDeclType(type_decl);
  1636. auto type_inst_id = MapType(context, loc_id, type).inst_id;
  1637. if (!type_inst_id.has_value()) {
  1638. context.TODO(AddImportIRInst(context.sem_ir(), type_decl->getLocation()),
  1639. llvm::formatv("Unsupported: Type declaration: {0}",
  1640. type.getAsString()));
  1641. return SemIR::ErrorInst::InstId;
  1642. }
  1643. context.clang_decls().Add({.decl = clang_decl, .inst_id = type_inst_id});
  1644. return type_inst_id;
  1645. }
  1646. if (isa<clang::FieldDecl, clang::IndirectFieldDecl>(clang_decl)) {
  1647. // Usable fields get imported as a side effect of importing the class.
  1648. if (SemIR::InstId existing_inst_id =
  1649. LookupClangDeclInstId(context, clang_decl);
  1650. existing_inst_id.has_value()) {
  1651. return existing_inst_id;
  1652. }
  1653. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1654. "Unsupported: field declaration has unhandled type or kind");
  1655. return SemIR::ErrorInst::InstId;
  1656. }
  1657. if (auto* enum_const_decl = dyn_cast<clang::EnumConstantDecl>(clang_decl)) {
  1658. return ImportEnumConstantDecl(context, enum_const_decl);
  1659. }
  1660. if (auto* var_decl = dyn_cast<clang::VarDecl>(clang_decl)) {
  1661. return ImportVarDecl(context, loc_id, var_decl);
  1662. }
  1663. context.TODO(AddImportIRInst(context.sem_ir(), clang_decl->getLocation()),
  1664. llvm::formatv("Unsupported: Declaration type {0}",
  1665. clang_decl->getDeclKindName()));
  1666. return SemIR::ErrorInst::InstId;
  1667. }
  1668. // Attempts to import a set of declarations. Returns `false` if an error was
  1669. // produced, `true` otherwise.
  1670. // TODO: Merge overload set and operators and remove the `is_overload_set`
  1671. // param.
  1672. static auto ImportDeclSet(Context& context, SemIR::LocId loc_id,
  1673. ImportWorklist& worklist,
  1674. bool is_overload_set = false) -> bool {
  1675. // Walk the dependency graph in depth-first order, and import declarations
  1676. // once we've imported all of their dependencies.
  1677. while (!worklist.empty()) {
  1678. auto& item = worklist.back();
  1679. if (!item.added_dependencies) {
  1680. // Skip items we've already imported. We checked this when initially
  1681. // adding the item to the worklist, but it might have been added to the
  1682. // worklist twice before the first time we visited it. For example, this
  1683. // happens for `fn F(a: Cpp.T, b: Cpp.T)`.
  1684. if (IsClangDeclImported(context, item.decl)) {
  1685. worklist.pop_back();
  1686. continue;
  1687. }
  1688. // First time visiting this declaration (preorder): add its dependencies
  1689. // to the work list.
  1690. item.added_dependencies = true;
  1691. AddDependentUnimportedDecls(context, item.decl, worklist);
  1692. } else {
  1693. // Second time visiting this declaration (postorder): its dependencies are
  1694. // already imported, so we can import it now.
  1695. auto* decl = worklist.pop_back_val().decl;
  1696. // Functions that are part of the overload set are imported at a later
  1697. // point, once the overload resolution has selected the suitable function
  1698. // for the call.
  1699. if (is_overload_set && decl->getAsFunction()) {
  1700. continue;
  1701. }
  1702. auto inst_id = ImportDeclAfterDependencies(context, loc_id, decl);
  1703. CARBON_CHECK(inst_id.has_value());
  1704. if (inst_id == SemIR::ErrorInst::InstId) {
  1705. return false;
  1706. }
  1707. CARBON_CHECK(IsClangDeclImported(context, decl));
  1708. }
  1709. }
  1710. return true;
  1711. }
  1712. // Imports a declaration from Clang to Carbon. If successful, returns the
  1713. // instruction for the new Carbon declaration. All unimported dependencies are
  1714. // imported first.
  1715. static auto ImportDeclAndDependencies(Context& context, SemIR::LocId loc_id,
  1716. clang::Decl* clang_decl)
  1717. -> SemIR::InstId {
  1718. // Collect dependencies by walking the dependency graph in depth-first order.
  1719. ImportWorklist worklist;
  1720. AddDependentDecl(context, clang_decl, worklist);
  1721. if (!ImportDeclSet(context, loc_id, worklist)) {
  1722. return SemIR::ErrorInst::InstId;
  1723. }
  1724. return LookupClangDeclInstId(context, clang_decl);
  1725. }
  1726. // Imports a type from Clang to Carbon. If successful, returns the imported
  1727. // TypeId. All unimported dependencies are imported first.
  1728. static auto ImportTypeAndDependencies(Context& context, SemIR::LocId loc_id,
  1729. clang::QualType type) -> TypeExpr {
  1730. // Collect dependencies by walking the dependency graph in depth-first order.
  1731. ImportWorklist worklist;
  1732. AddDependentUnimportedTypeDecls(context, type, worklist);
  1733. if (!ImportDeclSet(context, loc_id, worklist)) {
  1734. return {.inst_id = SemIR::ErrorInst::TypeInstId,
  1735. .type_id = SemIR::ErrorInst::TypeId};
  1736. }
  1737. return MapType(context, loc_id, type);
  1738. }
  1739. // Maps `clang::AccessSpecifier` to `SemIR::AccessKind`.
  1740. static auto MapAccess(clang::AccessSpecifier access_specifier)
  1741. -> SemIR::AccessKind {
  1742. switch (access_specifier) {
  1743. case clang::AS_public:
  1744. case clang::AS_none:
  1745. return SemIR::AccessKind::Public;
  1746. case clang::AS_protected:
  1747. return SemIR::AccessKind::Protected;
  1748. case clang::AS_private:
  1749. return SemIR::AccessKind::Private;
  1750. }
  1751. }
  1752. // Imports a `clang::NamedDecl` into Carbon and adds that name into the
  1753. // `NameScope`.
  1754. static auto ImportNameDeclIntoScope(Context& context, SemIR::LocId loc_id,
  1755. SemIR::NameScopeId scope_id,
  1756. SemIR::NameId name_id,
  1757. clang::NamedDecl* clang_decl,
  1758. clang::AccessSpecifier access)
  1759. -> SemIR::ScopeLookupResult {
  1760. SemIR::InstId inst_id =
  1761. ImportDeclAndDependencies(context, loc_id, clang_decl);
  1762. if (!inst_id.has_value()) {
  1763. return SemIR::ScopeLookupResult::MakeNotFound();
  1764. }
  1765. SemIR::AccessKind access_kind = MapAccess(access);
  1766. AddNameToScope(context, scope_id, name_id, access_kind, inst_id);
  1767. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1768. access_kind);
  1769. }
  1770. // Returns true if the scope is the top `Cpp` scope.
  1771. static auto IsTopCppScope(Context& context, SemIR::NameScopeId scope_id)
  1772. -> bool {
  1773. const SemIR::NameScope& name_scope = context.name_scopes().Get(scope_id);
  1774. CARBON_CHECK(name_scope.is_cpp_scope());
  1775. return name_scope.parent_scope_id() == SemIR::NameScopeId::Package;
  1776. }
  1777. // For builtin names like `Cpp.long`, return the associated types.
  1778. static auto LookupBuiltinTypes(Context& context, SemIR::LocId loc_id,
  1779. SemIR::NameScopeId scope_id,
  1780. SemIR::NameId name_id) -> SemIR::InstId {
  1781. if (!IsTopCppScope(context, scope_id)) {
  1782. return SemIR::InstId::None;
  1783. }
  1784. auto name = context.names().GetAsStringIfIdentifier(name_id);
  1785. if (!name) {
  1786. return SemIR::InstId::None;
  1787. }
  1788. const clang::ASTContext& ast_context = context.ast_context();
  1789. // List of types based on
  1790. // https://github.com/carbon-language/carbon-lang/blob/trunk/proposals/p5448.md#details
  1791. auto builtin_type =
  1792. llvm::StringSwitch<clang::QualType>(*name)
  1793. .Case("signed_char", ast_context.SignedCharTy)
  1794. .Case("short", ast_context.ShortTy)
  1795. .Case("int", ast_context.IntTy)
  1796. .Case("long", ast_context.LongTy)
  1797. .Case("long_long", ast_context.LongLongTy)
  1798. .Case("unsigned_char", ast_context.UnsignedCharTy)
  1799. .Case("unsigned_short", ast_context.UnsignedShortTy)
  1800. .Case("unsigned_int", ast_context.UnsignedIntTy)
  1801. .Case("unsigned_long", ast_context.UnsignedLongTy)
  1802. .Case("unsigned_long_long", ast_context.UnsignedLongLongTy)
  1803. .Case("float", ast_context.FloatTy)
  1804. .Case("double", ast_context.DoubleTy)
  1805. .Case("long_double", ast_context.LongDoubleTy)
  1806. .Default(clang::QualType());
  1807. if (builtin_type.isNull()) {
  1808. return SemIR::InstId::None;
  1809. }
  1810. SemIR::InstId inst_id =
  1811. MapNonWrapperType(context, loc_id, builtin_type).inst_id;
  1812. if (!inst_id.has_value()) {
  1813. context.TODO(loc_id, llvm::formatv("Unsupported: builtin type: {0}",
  1814. builtin_type.getAsString()));
  1815. return SemIR::ErrorInst::InstId;
  1816. }
  1817. return inst_id;
  1818. }
  1819. // Imports an overloaded function set from Clang to Carbon.
  1820. static auto ImportCppOverloadSet(Context& context, SemIR::NameScopeId scope_id,
  1821. SemIR::NameId name_id,
  1822. const clang::UnresolvedSet<4>& overload_set)
  1823. -> SemIR::InstId {
  1824. SemIR::CppOverloadSetId overload_set_id = context.cpp_overload_sets().Add(
  1825. SemIR::CppOverloadSet{.name_id = name_id,
  1826. .parent_scope_id = scope_id,
  1827. .candidate_functions = overload_set});
  1828. auto overload_set_inst_id =
  1829. // TODO: Add a location.
  1830. AddInstInNoBlock<SemIR::CppOverloadSetValue>(
  1831. context, Parse::NodeId::None,
  1832. {.type_id = GetCppOverloadSetType(context, overload_set_id,
  1833. SemIR::SpecificId::None),
  1834. .overload_set_id = overload_set_id});
  1835. context.imports().push_back(overload_set_inst_id);
  1836. return overload_set_inst_id;
  1837. }
  1838. // Gets the access for an overloaded function set. Returns std::nullopt
  1839. // if the access is not the same for all functions in the overload set.
  1840. // TODO: Fix to support functions with different access levels.
  1841. static auto GetOverloadSetAccess(Context& context, SemIR::LocId loc_id,
  1842. const clang::UnresolvedSet<4>& overload_set)
  1843. -> std::optional<SemIR::AccessKind> {
  1844. clang::AccessSpecifier access = overload_set.begin().getAccess();
  1845. for (auto it = overload_set.begin() + 1; it != overload_set.end(); ++it) {
  1846. if (it.getAccess() != access) {
  1847. context.TODO(loc_id, "Unsupported: Overloaded set with mixed access");
  1848. return std::nullopt;
  1849. }
  1850. }
  1851. return MapAccess(access);
  1852. }
  1853. static auto ImportOverloadSetAndDependencies(
  1854. Context& context, SemIR::LocId loc_id, SemIR::NameScopeId scope_id,
  1855. SemIR::NameId name_id, const clang::UnresolvedSet<4>& overloaded_set)
  1856. -> SemIR::InstId {
  1857. ImportWorklist worklist;
  1858. for (clang::NamedDecl* fn_decl : overloaded_set) {
  1859. AddDependentDecl(context, fn_decl, worklist);
  1860. }
  1861. if (!ImportDeclSet(context, loc_id, worklist, true)) {
  1862. return SemIR::ErrorInst::InstId;
  1863. }
  1864. return ImportCppOverloadSet(context, scope_id, name_id, overloaded_set);
  1865. }
  1866. // Imports an overloaded function set from Clang to Carbon and adds the
  1867. // name into the `NameScope`.
  1868. static auto ImportOverloadSetIntoScope(
  1869. Context& context, SemIR::LocId loc_id, SemIR::NameScopeId scope_id,
  1870. SemIR::NameId name_id, const clang::UnresolvedSet<4>& overload_set)
  1871. -> SemIR::ScopeLookupResult {
  1872. std::optional<SemIR::AccessKind> access_kind =
  1873. GetOverloadSetAccess(context, loc_id, overload_set);
  1874. if (!access_kind.has_value()) {
  1875. return SemIR::ScopeLookupResult::MakeError();
  1876. }
  1877. SemIR::InstId inst_id = ImportOverloadSetAndDependencies(
  1878. context, loc_id, scope_id, name_id, overload_set);
  1879. AddNameToScope(context, scope_id, name_id, access_kind.value(), inst_id);
  1880. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  1881. access_kind.value());
  1882. }
  1883. // TODO: Refactor this method.
  1884. // TODO: Do we need to import the dependences for all functions in the overload
  1885. // set?
  1886. auto ImportNameFromCpp(Context& context, SemIR::LocId loc_id,
  1887. SemIR::NameScopeId scope_id, SemIR::NameId name_id)
  1888. -> SemIR::ScopeLookupResult {
  1889. Diagnostics::AnnotationScope annotate_diagnostics(
  1890. &context.emitter(), [&](auto& builder) {
  1891. CARBON_DIAGNOSTIC(InCppNameLookup, Note,
  1892. "in `Cpp` name lookup for `{0}`", SemIR::NameId);
  1893. builder.Note(loc_id, InCppNameLookup, name_id);
  1894. });
  1895. if (auto class_decl = context.insts().TryGetAs<SemIR::ClassDecl>(
  1896. context.name_scopes().Get(scope_id).inst_id());
  1897. class_decl.has_value()) {
  1898. if (!context.types().IsComplete(
  1899. context.classes().Get(class_decl->class_id).self_type_id)) {
  1900. return SemIR::ScopeLookupResult::MakeError();
  1901. }
  1902. }
  1903. auto lookup = ClangLookupName(context, scope_id, name_id);
  1904. if (!lookup) {
  1905. SemIR::InstId builtin_inst_id =
  1906. LookupBuiltinTypes(context, loc_id, scope_id, name_id);
  1907. if (builtin_inst_id.has_value()) {
  1908. AddNameToScope(context, scope_id, name_id, SemIR::AccessKind::Public,
  1909. builtin_inst_id);
  1910. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(
  1911. builtin_inst_id, SemIR::AccessKind::Public);
  1912. }
  1913. return SemIR::ScopeLookupResult::MakeNotFound();
  1914. }
  1915. // Access checks are performed separately by the Carbon name lookup logic.
  1916. lookup->suppressAccessDiagnostics();
  1917. if (lookup->isOverloadedResult() ||
  1918. (lookup->isSingleResult() &&
  1919. lookup->getFoundDecl()->isFunctionOrFunctionTemplate())) {
  1920. clang::UnresolvedSet<4> overload_set;
  1921. overload_set.append(lookup->begin(), lookup->end());
  1922. return ImportOverloadSetIntoScope(context, loc_id, scope_id, name_id,
  1923. overload_set);
  1924. }
  1925. if (!lookup->isSingleResult()) {
  1926. // Clang will diagnose ambiguous lookup results for us.
  1927. if (!lookup->isAmbiguous()) {
  1928. context.TODO(loc_id,
  1929. llvm::formatv("Unsupported: Lookup succeeded but couldn't "
  1930. "find a single result; LookupResultKind: {0}",
  1931. static_cast<int>(lookup->getResultKind())));
  1932. }
  1933. context.name_scopes().AddRequiredName(scope_id, name_id,
  1934. SemIR::ErrorInst::InstId);
  1935. return SemIR::ScopeLookupResult::MakeError();
  1936. }
  1937. if (!IsDeclInjectedClassName(context, scope_id, name_id,
  1938. lookup->getFoundDecl())) {
  1939. return ImportNameDeclIntoScope(context, loc_id, scope_id, name_id,
  1940. lookup->getFoundDecl(),
  1941. lookup->begin().getAccess());
  1942. }
  1943. clang::DeclContextLookupResult constructors_lookup =
  1944. ClangConstructorLookup(context, scope_id);
  1945. clang::UnresolvedSet<4> overload_set;
  1946. for (clang::Decl* decl : constructors_lookup) {
  1947. auto* constructor = cast<clang::CXXConstructorDecl>(decl);
  1948. if (constructor->isDeleted() || constructor->isCopyOrMoveConstructor()) {
  1949. continue;
  1950. }
  1951. overload_set.addDecl(constructor, constructor->getAccess());
  1952. }
  1953. if (overload_set.empty()) {
  1954. return SemIR::ScopeLookupResult::MakeNotFound();
  1955. }
  1956. return ImportOverloadSetIntoScope(context, loc_id, scope_id, name_id,
  1957. overload_set);
  1958. }
  1959. static auto GetClangOperatorKind(Context& context, SemIR::LocId loc_id,
  1960. llvm::StringLiteral interface_name,
  1961. llvm::StringLiteral op_name)
  1962. -> std::optional<clang::OverloadedOperatorKind> {
  1963. // Unary operators.
  1964. if (interface_name == "Destroy" || interface_name == "As" ||
  1965. interface_name == "ImplicitAs") {
  1966. // TODO: Support destructors and conversions.
  1967. return std::nullopt;
  1968. }
  1969. // Increment and Decrement.
  1970. if (interface_name == "Inc") {
  1971. CARBON_CHECK(op_name == "Op");
  1972. return clang::OO_PlusPlus;
  1973. }
  1974. if (interface_name == "Dec") {
  1975. CARBON_CHECK(op_name == "Op");
  1976. return clang::OO_MinusMinus;
  1977. }
  1978. // Arithmetic.
  1979. if (interface_name == "Negate") {
  1980. CARBON_CHECK(op_name == "Op");
  1981. return clang::OO_Minus;
  1982. }
  1983. // Binary operators.
  1984. // Arithmetic Operators.
  1985. if (interface_name == "AddWith") {
  1986. CARBON_CHECK(op_name == "Op");
  1987. return clang::OO_Plus;
  1988. }
  1989. if (interface_name == "SubWith") {
  1990. CARBON_CHECK(op_name == "Op");
  1991. return clang::OO_Minus;
  1992. }
  1993. if (interface_name == "MulWith") {
  1994. CARBON_CHECK(op_name == "Op");
  1995. return clang::OO_Star;
  1996. }
  1997. if (interface_name == "DivWith") {
  1998. CARBON_CHECK(op_name == "Op");
  1999. return clang::OO_Slash;
  2000. }
  2001. if (interface_name == "ModWith") {
  2002. CARBON_CHECK(op_name == "Op");
  2003. return clang::OO_Percent;
  2004. }
  2005. // Bitwise Operators.
  2006. if (interface_name == "BitAndWith") {
  2007. CARBON_CHECK(op_name == "Op");
  2008. return clang::OO_Amp;
  2009. }
  2010. if (interface_name == "BitOrWith") {
  2011. CARBON_CHECK(op_name == "Op");
  2012. return clang::OO_Pipe;
  2013. }
  2014. if (interface_name == "BitXorWith") {
  2015. CARBON_CHECK(op_name == "Op");
  2016. return clang::OO_Caret;
  2017. }
  2018. if (interface_name == "LeftShiftWith") {
  2019. CARBON_CHECK(op_name == "Op");
  2020. return clang::OO_LessLess;
  2021. }
  2022. if (interface_name == "RightShiftWith") {
  2023. CARBON_CHECK(op_name == "Op");
  2024. return clang::OO_GreaterGreater;
  2025. }
  2026. // Compound Assignment Arithmetic Operators.
  2027. if (interface_name == "AddAssignWith") {
  2028. CARBON_CHECK(op_name == "Op");
  2029. return clang::OO_PlusEqual;
  2030. }
  2031. if (interface_name == "SubAssignWith") {
  2032. CARBON_CHECK(op_name == "Op");
  2033. return clang::OO_MinusEqual;
  2034. }
  2035. if (interface_name == "MulAssignWith") {
  2036. CARBON_CHECK(op_name == "Op");
  2037. return clang::OO_StarEqual;
  2038. }
  2039. if (interface_name == "DivAssignWith") {
  2040. CARBON_CHECK(op_name == "Op");
  2041. return clang::OO_SlashEqual;
  2042. }
  2043. if (interface_name == "ModAssignWith") {
  2044. CARBON_CHECK(op_name == "Op");
  2045. return clang::OO_PercentEqual;
  2046. }
  2047. // Compound Assignment Bitwise Operators.
  2048. if (interface_name == "BitAndAssignWith") {
  2049. CARBON_CHECK(op_name == "Op");
  2050. return clang::OO_AmpEqual;
  2051. }
  2052. if (interface_name == "BitOrAssignWith") {
  2053. CARBON_CHECK(op_name == "Op");
  2054. return clang::OO_PipeEqual;
  2055. }
  2056. if (interface_name == "BitXorAssignWith") {
  2057. CARBON_CHECK(op_name == "Op");
  2058. return clang::OO_CaretEqual;
  2059. }
  2060. // TODO: Add support for `LeftShiftAssignWith` (`OO_LessLessEqual`) and
  2061. // `RightShiftAssignWith` (`OO_GreaterGreaterEqual`) when references are
  2062. // supported.
  2063. // Relational Operators.
  2064. if (interface_name == "EqWith") {
  2065. if (op_name == "Equal") {
  2066. return clang::OO_EqualEqual;
  2067. }
  2068. CARBON_CHECK(op_name == "NotEqual");
  2069. return clang::OO_ExclaimEqual;
  2070. }
  2071. if (interface_name == "OrderedWith") {
  2072. if (op_name == "Less") {
  2073. return clang::OO_Less;
  2074. }
  2075. if (op_name == "Greater") {
  2076. return clang::OO_Greater;
  2077. }
  2078. if (op_name == "LessOrEquivalent") {
  2079. return clang::OO_LessEqual;
  2080. }
  2081. CARBON_CHECK(op_name == "GreaterOrEquivalent");
  2082. return clang::OO_GreaterEqual;
  2083. }
  2084. context.TODO(loc_id, llvm::formatv("Unsupported operator interface `{0}`",
  2085. interface_name));
  2086. return std::nullopt;
  2087. }
  2088. auto ImportOperatorFromCpp(Context& context, SemIR::LocId loc_id,
  2089. SemIR::NameScopeId scope_id, Operator op)
  2090. -> SemIR::ScopeLookupResult {
  2091. Diagnostics::AnnotationScope annotate_diagnostics(
  2092. &context.emitter(), [&](auto& builder) {
  2093. CARBON_DIAGNOSTIC(InCppOperatorLookup, Note,
  2094. "in `Cpp` operator `{0}` lookup", std::string);
  2095. builder.Note(loc_id, InCppOperatorLookup, op.interface_name.str());
  2096. });
  2097. auto op_kind =
  2098. GetClangOperatorKind(context, loc_id, op.interface_name, op.op_name);
  2099. if (!op_kind) {
  2100. return SemIR::ScopeLookupResult::MakeNotFound();
  2101. }
  2102. // TODO: We should do ADL-only lookup for operators
  2103. // (`Sema::ArgumentDependentLookup`), when we support mapping Carbon types
  2104. // into C++ types. See
  2105. // https://github.com/carbon-language/carbon-lang/pull/5996/files/5d01fa69511b76f87efbc0387f5e40abcf4c911a#r2316950123
  2106. auto decl_and_access = ClangLookupDeclarationName(
  2107. context, loc_id, scope_id,
  2108. context.ast_context().DeclarationNames.getCXXOperatorName(*op_kind));
  2109. if (!decl_and_access) {
  2110. return SemIR::ScopeLookupResult::MakeNotFound();
  2111. }
  2112. auto [decl, access] = *decl_and_access;
  2113. if (!decl) {
  2114. return SemIR::ScopeLookupResult::MakeError();
  2115. }
  2116. SemIR::InstId inst_id = ImportDeclAndDependencies(context, loc_id, decl);
  2117. if (!inst_id.has_value()) {
  2118. return SemIR::ScopeLookupResult::MakeNotFound();
  2119. }
  2120. SemIR::AccessKind access_kind = MapAccess(access);
  2121. return SemIR::ScopeLookupResult::MakeWrappedLookupResult(inst_id,
  2122. access_kind);
  2123. }
  2124. auto ImportClassDefinitionForClangDecl(Context& context, SemIR::LocId loc_id,
  2125. SemIR::ClassId class_id,
  2126. SemIR::ClangDeclId clang_decl_id)
  2127. -> bool {
  2128. clang::ASTUnit* ast = context.sem_ir().clang_ast_unit();
  2129. CARBON_CHECK(ast);
  2130. auto* clang_decl =
  2131. cast<clang::TagDecl>(context.clang_decls().Get(clang_decl_id).decl);
  2132. auto class_inst_id = context.types().GetAsTypeInstId(
  2133. context.classes().Get(class_id).first_owning_decl_id);
  2134. // TODO: Map loc_id into a clang location and use it for diagnostics if
  2135. // instantiation fails, instead of annotating the diagnostic with another
  2136. // location.
  2137. clang::SourceLocation loc = clang_decl->getLocation();
  2138. Diagnostics::AnnotationScope annotate_diagnostics(
  2139. &context.emitter(), [&](auto& builder) {
  2140. CARBON_DIAGNOSTIC(InCppTypeCompletion, Note,
  2141. "while completing C++ type {0}", SemIR::TypeId);
  2142. builder.Note(loc_id, InCppTypeCompletion,
  2143. context.classes().Get(class_id).self_type_id);
  2144. });
  2145. // Ask Clang whether the type is complete. This triggers template
  2146. // instantiation if necessary.
  2147. clang::DiagnosticErrorTrap trap(ast->getDiagnostics());
  2148. if (!ast->getSema().isCompleteType(
  2149. loc, context.ast_context().getCanonicalTagType(clang_decl))) {
  2150. // Type is incomplete. Nothing more to do, but tell the caller if we
  2151. // produced an error.
  2152. return !trap.hasErrorOccurred();
  2153. }
  2154. auto import_ir_inst_id =
  2155. context.insts().GetCanonicalLocId(class_inst_id).import_ir_inst_id();
  2156. if (auto* class_decl = dyn_cast<clang::CXXRecordDecl>(clang_decl)) {
  2157. auto* class_def = class_decl->getDefinition();
  2158. CARBON_CHECK(class_def, "Complete type has no definition");
  2159. if (class_def->getNumVBases()) {
  2160. // TODO: Handle virtual bases. We don't actually know where they go in the
  2161. // layout. We may also want to use a different size in the layout for
  2162. // `partial C`, excluding the virtual base. It's also not entirely safe to
  2163. // just skip over the virtual base, as the type we would construct would
  2164. // have a misleading size. For now, treat a C++ class with vbases as
  2165. // incomplete in Carbon.
  2166. context.TODO(loc_id, "class with virtual bases");
  2167. return false;
  2168. }
  2169. BuildClassDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  2170. class_def);
  2171. } else if (auto* enum_decl = dyn_cast<clang::EnumDecl>(clang_decl)) {
  2172. BuildEnumDefinition(context, import_ir_inst_id, class_id, class_inst_id,
  2173. enum_decl);
  2174. }
  2175. return true;
  2176. }
  2177. } // namespace Carbon::Check