import.cpp 99 KB

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