import.cpp 100 KB

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