import.cpp 92 KB

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