import.cpp 92 KB

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