cpp_import.cpp 95 KB

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