import.cpp 96 KB

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