import_cpp.cpp 89 KB

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