import.cpp 103 KB

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