file_context.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196
  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/lower/file_context.h"
  5. #include <memory>
  6. #include <optional>
  7. #include <string>
  8. #include <utility>
  9. #include "clang/CodeGen/ModuleBuilder.h"
  10. #include "common/check.h"
  11. #include "common/vlog.h"
  12. #include "llvm/ADT/STLExtras.h"
  13. #include "llvm/ADT/Sequence.h"
  14. #include "llvm/Linker/Linker.h"
  15. #include "llvm/Support/BLAKE3.h"
  16. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  17. #include "llvm/Transforms/Utils/ModuleUtils.h"
  18. #include "toolchain/base/kind_switch.h"
  19. #include "toolchain/lower/constant.h"
  20. #include "toolchain/lower/function_context.h"
  21. #include "toolchain/lower/mangler.h"
  22. #include "toolchain/sem_ir/absolute_node_id.h"
  23. #include "toolchain/sem_ir/entry_point.h"
  24. #include "toolchain/sem_ir/expr_info.h"
  25. #include "toolchain/sem_ir/file.h"
  26. #include "toolchain/sem_ir/function.h"
  27. #include "toolchain/sem_ir/generic.h"
  28. #include "toolchain/sem_ir/ids.h"
  29. #include "toolchain/sem_ir/inst.h"
  30. #include "toolchain/sem_ir/inst_categories.h"
  31. #include "toolchain/sem_ir/inst_kind.h"
  32. #include "toolchain/sem_ir/pattern.h"
  33. #include "toolchain/sem_ir/typed_insts.h"
  34. namespace Carbon::Lower {
  35. FileContext::FileContext(Context& context, const SemIR::File& sem_ir,
  36. const SemIR::InstNamer* inst_namer,
  37. llvm::raw_ostream* vlog_stream)
  38. : context_(&context),
  39. sem_ir_(&sem_ir),
  40. inst_namer_(inst_namer),
  41. vlog_stream_(vlog_stream),
  42. functions_(LoweredFunctionStore::MakeForOverwrite(sem_ir.functions())),
  43. specific_functions_(sem_ir.specifics(), nullptr),
  44. types_(LoweredTypeStore::MakeWithExplicitSize(sem_ir.insts().size(),
  45. nullptr)),
  46. constants_(LoweredConstantStore::MakeWithExplicitSize(
  47. sem_ir.insts().size(), nullptr)),
  48. lowered_specifics_(sem_ir.generics(), {}),
  49. lowered_specifics_type_fingerprint_(sem_ir.specifics(), {}),
  50. lowered_specific_fingerprint_(sem_ir.specifics(), {}),
  51. equivalent_specifics_(sem_ir.specifics(), SemIR::SpecificId::None) {
  52. // Initialization that relies on invariants of the class.
  53. cpp_code_generator_ = CreateCppCodeGenerator();
  54. CARBON_CHECK(!sem_ir.has_errors(),
  55. "Generating LLVM IR from invalid SemIR::File is unsupported.");
  56. }
  57. // TODO: Move this to lower.cpp.
  58. auto FileContext::PrepareToLower() -> void {
  59. if (cpp_code_generator_) {
  60. // Clang code generation should not actually modify the AST, but isn't
  61. // const-correct.
  62. cpp_code_generator_->Initialize(
  63. const_cast<clang::ASTContext&>(cpp_ast()->getASTContext()));
  64. }
  65. // Lower all types that were required to be complete.
  66. for (auto type_id : sem_ir_->types().complete_types()) {
  67. if (type_id.index >= 0) {
  68. types_.Set(type_id, BuildType(sem_ir_->types().GetInstId(type_id)));
  69. }
  70. }
  71. // Lower function declarations.
  72. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  73. functions_.Set(id, BuildFunctionDecl(id));
  74. }
  75. // Lower constants.
  76. LowerConstants(*this, constants_);
  77. }
  78. // TODO: Move this to lower.cpp.
  79. auto FileContext::LowerDefinitions() -> void {
  80. for (const auto& class_info : sem_ir_->classes().values()) {
  81. if (auto* llvm_vtable = BuildVtable(class_info)) {
  82. global_variables_.Insert(class_info.vtable_id, llvm_vtable);
  83. }
  84. }
  85. // Lower global variable definitions.
  86. // TODO: Storing both a `constants_` array and a separate `global_variables_`
  87. // map is redundant.
  88. for (auto inst_id :
  89. sem_ir().inst_blocks().Get(sem_ir().top_inst_block_id())) {
  90. // Only `VarStorage` indicates a global variable declaration in the
  91. // top instruction block.
  92. if (auto var = sem_ir().insts().TryGetAs<SemIR::VarStorage>(inst_id)) {
  93. // Get the global variable declaration. We created this when lowering the
  94. // constant unless the variable is unnamed, in which case we need to
  95. // create it now.
  96. llvm::GlobalVariable* llvm_var = nullptr;
  97. if (auto const_id = sem_ir().constant_values().Get(inst_id);
  98. const_id.is_constant()) {
  99. llvm_var = cast<llvm::GlobalVariable>(GetConstant(const_id, inst_id));
  100. } else {
  101. llvm_var = BuildGlobalVariableDecl(*var);
  102. }
  103. // Convert the declaration of this variable into a definition by adding an
  104. // initializer.
  105. global_variables_.Insert(inst_id, llvm_var);
  106. llvm_var->setInitializer(
  107. llvm::Constant::getNullValue(llvm_var->getValueType()));
  108. }
  109. }
  110. // Lower function definitions.
  111. for (auto [id, fn_info] : sem_ir_->functions().enumerate()) {
  112. // If we created a declaration and the function definition is not imported,
  113. // build a definition.
  114. if (functions_.Get(id) && fn_info.definition_id.has_value() &&
  115. !sem_ir().insts().GetImportSource(fn_info.definition_id).has_value()) {
  116. BuildFunctionDefinition(id);
  117. }
  118. }
  119. // Append `__global_init` to `llvm::global_ctors` to initialize global
  120. // variables.
  121. if (auto global_ctor_id = sem_ir().global_ctor_id();
  122. global_ctor_id.has_value()) {
  123. const auto& global_ctor = sem_ir().functions().Get(global_ctor_id);
  124. BuildFunctionBody(global_ctor_id, SemIR::SpecificId::None, global_ctor,
  125. *this, global_ctor);
  126. llvm::appendToGlobalCtors(llvm_module(),
  127. GetFunction(sem_ir().global_ctor_id()),
  128. /*Priority=*/0);
  129. }
  130. }
  131. auto FileContext::Finalize() -> void {
  132. if (cpp_code_generator_) {
  133. // Clang code generation should not actually modify the AST, but isn't
  134. // const-correct.
  135. cpp_code_generator_->HandleTranslationUnit(
  136. const_cast<clang::ASTContext&>(cpp_ast()->getASTContext()));
  137. bool link_error = llvm::Linker::linkModules(
  138. /*Dest=*/llvm_module(),
  139. /*Src=*/std::unique_ptr<llvm::Module>(
  140. cpp_code_generator_->ReleaseModule()));
  141. CARBON_CHECK(!link_error);
  142. }
  143. // Find equivalent specifics (from the same generic), replace all uses and
  144. // remove duplicately lowered function definitions.
  145. CoalesceEquivalentSpecifics();
  146. }
  147. auto FileContext::InsertPair(
  148. SemIR::SpecificId specific_id1, SemIR::SpecificId specific_id2,
  149. Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>& set_of_pairs)
  150. -> bool {
  151. if (specific_id1.index > specific_id2.index) {
  152. std::swap(specific_id1.index, specific_id2.index);
  153. }
  154. auto insert_result =
  155. set_of_pairs.Insert(std::make_pair(specific_id1, specific_id2));
  156. return insert_result.is_inserted();
  157. }
  158. auto FileContext::ContainsPair(
  159. SemIR::SpecificId specific_id1, SemIR::SpecificId specific_id2,
  160. const Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>& set_of_pairs)
  161. -> bool {
  162. if (specific_id1.index > specific_id2.index) {
  163. std::swap(specific_id1.index, specific_id2.index);
  164. }
  165. return set_of_pairs.Contains(std::make_pair(specific_id1, specific_id2));
  166. }
  167. auto FileContext::CoalesceEquivalentSpecifics() -> void {
  168. for (auto& specifics : lowered_specifics_.values()) {
  169. // i cannot be unsigned due to the comparison with a negative number when
  170. // the specifics vector is empty.
  171. for (int i = 0; i < static_cast<int>(specifics.size()) - 1; ++i) {
  172. // This specific was already replaced, skip it.
  173. if (equivalent_specifics_.Get(specifics[i]).has_value() &&
  174. equivalent_specifics_.Get(specifics[i]) != specifics[i]) {
  175. specifics[i] = specifics[specifics.size() - 1];
  176. specifics.pop_back();
  177. --i;
  178. continue;
  179. }
  180. // TODO: Improve quadratic behavior by using a single hash based on
  181. // `lowered_specifics_type_fingerprint_` and `common_fingerprint`.
  182. for (int j = i + 1; j < static_cast<int>(specifics.size()); ++j) {
  183. // When the specific was already replaced, skip it.
  184. if (equivalent_specifics_.Get(specifics[j]).has_value() &&
  185. equivalent_specifics_.Get(specifics[j]) != specifics[j]) {
  186. specifics[j] = specifics[specifics.size() - 1];
  187. specifics.pop_back();
  188. --j;
  189. continue;
  190. }
  191. // When the two specifics are not equivalent due to the function type
  192. // info stored in lowered_specifics_types, mark non-equivalance. This
  193. // can be reused to short-cut another path and continue the search for
  194. // other equivalences.
  195. if (!AreFunctionTypesEquivalent(specifics[i], specifics[j])) {
  196. InsertPair(specifics[i], specifics[j], non_equivalent_specifics_);
  197. continue;
  198. }
  199. Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>
  200. visited_equivalent_specifics;
  201. InsertPair(specifics[i], specifics[j], visited_equivalent_specifics);
  202. // Function type information matches; check usages inside the function
  203. // body that are dependent on the specific. This information has been
  204. // stored in lowered_states while lowering each function body.
  205. if (AreFunctionBodiesEquivalent(specifics[i], specifics[j],
  206. visited_equivalent_specifics)) {
  207. // When processing equivalences, we may change the canonical specific
  208. // multiple times, so we don't delete replaced specifics until the
  209. // end.
  210. llvm::SmallVector<SemIR::SpecificId> specifics_to_delete;
  211. visited_equivalent_specifics.ForEach(
  212. [&](std::pair<SemIR::SpecificId, SemIR::SpecificId>
  213. equivalent_entry) {
  214. CARBON_VLOG("Found equivalent specifics: {0}, {1}",
  215. equivalent_entry.first, equivalent_entry.second);
  216. ProcessSpecificEquivalence(equivalent_entry,
  217. specifics_to_delete);
  218. });
  219. // Delete function bodies for already replaced functions.
  220. for (auto specific_id : specifics_to_delete) {
  221. specific_functions_.Get(specific_id)->eraseFromParent();
  222. specific_functions_.Get(specific_id) =
  223. specific_functions_.Get(equivalent_specifics_.Get(specific_id));
  224. }
  225. // Removed the replaced specific from the list of emitted specifics.
  226. // Only the top level, since the others are somewhere else in the
  227. // vector, they will be found and removed during processing.
  228. specifics[j] = specifics[specifics.size() - 1];
  229. specifics.pop_back();
  230. --j;
  231. } else {
  232. // Only mark non-equivalence based on state for starting specifics.
  233. InsertPair(specifics[i], specifics[j], non_equivalent_specifics_);
  234. }
  235. }
  236. }
  237. }
  238. }
  239. auto FileContext::ProcessSpecificEquivalence(
  240. std::pair<SemIR::SpecificId, SemIR::SpecificId> pair,
  241. llvm::SmallVector<SemIR::SpecificId>& specifics_to_delete) -> void {
  242. auto [specific_id1, specific_id2] = pair;
  243. CARBON_CHECK(specific_id1.has_value() && specific_id2.has_value(),
  244. "Expected values in equivalence check");
  245. auto get_canon = [&](SemIR::SpecificId specific_id) {
  246. return equivalent_specifics_.Get(specific_id).has_value()
  247. ? std::make_pair(
  248. equivalent_specifics_.Get(specific_id),
  249. (equivalent_specifics_.Get(specific_id) != specific_id))
  250. : std::make_pair(specific_id, false);
  251. };
  252. auto [canon_id1, replaced_before1] = get_canon(specific_id1);
  253. auto [canon_id2, replaced_before2] = get_canon(specific_id2);
  254. if (canon_id1 == canon_id2) {
  255. // Already equivalent, there was a previous replacement.
  256. return;
  257. }
  258. if (canon_id1.index >= canon_id2.index) {
  259. // Prefer the earlier index for canonical values.
  260. std::swap(canon_id1, canon_id2);
  261. std::swap(replaced_before1, replaced_before2);
  262. }
  263. // Update equivalent_specifics_ for all. This is used as an indicator that
  264. // this specific_id may be the canonical one when reducing the equivalence
  265. // chains in `IsKnownEquivalence`.
  266. equivalent_specifics_.Set(specific_id1, canon_id1);
  267. equivalent_specifics_.Set(specific_id2, canon_id1);
  268. specific_functions_.Get(canon_id2)->replaceAllUsesWith(
  269. specific_functions_.Get(canon_id1));
  270. if (!replaced_before2) {
  271. specifics_to_delete.push_back(canon_id2);
  272. }
  273. }
  274. auto FileContext::IsKnownEquivalence(SemIR::SpecificId specific_id1,
  275. SemIR::SpecificId specific_id2) -> bool {
  276. if (!equivalent_specifics_.Get(specific_id1).has_value() ||
  277. !equivalent_specifics_.Get(specific_id2).has_value()) {
  278. return false;
  279. }
  280. auto update_equivalent_specific = [&](SemIR::SpecificId specific_id) {
  281. llvm::SmallVector<SemIR::SpecificId> stack;
  282. SemIR::SpecificId specific_to_update = specific_id;
  283. while (equivalent_specifics_.Get(
  284. equivalent_specifics_.Get(specific_to_update)) !=
  285. equivalent_specifics_.Get(specific_to_update)) {
  286. stack.push_back(specific_to_update);
  287. specific_to_update = equivalent_specifics_.Get(specific_to_update);
  288. }
  289. for (auto specific : llvm::reverse(stack)) {
  290. equivalent_specifics_.Set(
  291. specific,
  292. equivalent_specifics_.Get(equivalent_specifics_.Get(specific)));
  293. }
  294. };
  295. update_equivalent_specific(specific_id1);
  296. update_equivalent_specific(specific_id2);
  297. return equivalent_specifics_.Get(specific_id1) ==
  298. equivalent_specifics_.Get(specific_id2);
  299. }
  300. auto FileContext::AreFunctionTypesEquivalent(SemIR::SpecificId specific_id1,
  301. SemIR::SpecificId specific_id2)
  302. -> bool {
  303. CARBON_CHECK(specific_id1.has_value() && specific_id2.has_value());
  304. return lowered_specifics_type_fingerprint_.Get(specific_id1) ==
  305. lowered_specifics_type_fingerprint_.Get(specific_id2);
  306. }
  307. auto FileContext::AreFunctionBodiesEquivalent(
  308. SemIR::SpecificId specific_id1, SemIR::SpecificId specific_id2,
  309. Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>&
  310. visited_equivalent_specifics) -> bool {
  311. llvm::SmallVector<std::pair<SemIR::SpecificId, SemIR::SpecificId>> worklist;
  312. worklist.push_back({specific_id1, specific_id2});
  313. while (!worklist.empty()) {
  314. auto outer_pair = worklist.pop_back_val();
  315. auto [specific_id1, specific_id2] = outer_pair;
  316. auto state1 = lowered_specific_fingerprint_.Get(specific_id1);
  317. auto state2 = lowered_specific_fingerprint_.Get(specific_id2);
  318. if (state1.common_fingerprint != state2.common_fingerprint) {
  319. InsertPair(specific_id1, specific_id2, non_equivalent_specifics_);
  320. return false;
  321. }
  322. if (state1.specific_fingerprint == state2.specific_fingerprint) {
  323. continue;
  324. }
  325. // A size difference should have been detected by the common fingerprint.
  326. CARBON_CHECK(state1.calls.size() == state2.calls.size(),
  327. "Number of specific calls expected to be the same.");
  328. for (auto [state1_call, state2_call] :
  329. llvm::zip(state1.calls, state2.calls)) {
  330. if (state1_call != state2_call) {
  331. if (ContainsPair(state1_call, state2_call, non_equivalent_specifics_)) {
  332. return false;
  333. }
  334. if (IsKnownEquivalence(state1_call, state2_call)) {
  335. continue;
  336. }
  337. if (!InsertPair(state1_call, state2_call,
  338. visited_equivalent_specifics)) {
  339. continue;
  340. }
  341. // Leave the added equivalence pair in place and continue.
  342. worklist.push_back({state1_call, state2_call});
  343. }
  344. }
  345. }
  346. return true;
  347. }
  348. auto FileContext::CreateCppCodeGenerator()
  349. -> std::unique_ptr<clang::CodeGenerator> {
  350. if (!cpp_ast()) {
  351. return nullptr;
  352. }
  353. RawStringOstream clang_module_name_stream;
  354. clang_module_name_stream << llvm_module().getName() << ".clang";
  355. // Do not emit Clang's name and version as the creator of the output file.
  356. cpp_code_gen_options_.EmitVersionIdentMetadata = false;
  357. return std::unique_ptr<clang::CodeGenerator>(clang::CreateLLVMCodeGen(
  358. cpp_ast()->getASTContext().getDiagnostics(),
  359. clang_module_name_stream.TakeStr(), context().file_system(),
  360. cpp_header_search_options_, cpp_preprocessor_options_,
  361. cpp_code_gen_options_, llvm_context()));
  362. }
  363. auto FileContext::GetConstant(SemIR::ConstantId const_id,
  364. SemIR::InstId use_inst_id) -> llvm::Value* {
  365. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  366. auto* const_value = constants_.Get(const_inst_id);
  367. // For value expressions and initializing expressions, the value produced by
  368. // a constant instruction is a value representation of the constant. For
  369. // initializing expressions, `FinishInit` will perform a copy if needed.
  370. switch (auto cat = SemIR::GetExprCategory(sem_ir(), const_inst_id)) {
  371. case SemIR::ExprCategory::Value:
  372. case SemIR::ExprCategory::Initializing:
  373. break;
  374. case SemIR::ExprCategory::DurableRef:
  375. case SemIR::ExprCategory::EphemeralRef:
  376. // Constant reference expressions lower to an address.
  377. return const_value;
  378. case SemIR::ExprCategory::NotExpr:
  379. case SemIR::ExprCategory::Error:
  380. case SemIR::ExprCategory::Mixed:
  381. CARBON_FATAL("Unexpected category {0} for lowered constant {1}", cat,
  382. sem_ir().insts().Get(const_inst_id));
  383. };
  384. auto value_rep = SemIR::ValueRepr::ForType(
  385. sem_ir(), sem_ir().insts().Get(const_inst_id).type_id());
  386. if (value_rep.kind != SemIR::ValueRepr::Pointer) {
  387. return const_value;
  388. }
  389. // The value representation is a pointer. Generate a variable to hold the
  390. // value, or find and reuse an existing one.
  391. if (auto result = global_variables().Lookup(const_inst_id)) {
  392. return result.value();
  393. }
  394. // Include both the name of the constant, if any, and the point of use in
  395. // the name of the variable.
  396. llvm::StringRef const_name;
  397. llvm::StringRef use_name;
  398. if (inst_namer_) {
  399. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  400. if (use_inst_id.has_value()) {
  401. use_name = inst_namer_->GetUnscopedNameFor(use_inst_id);
  402. }
  403. }
  404. // We always need to give the global a name even if the instruction namer
  405. // doesn't have one to use.
  406. if (const_name.empty()) {
  407. const_name = "const";
  408. }
  409. if (use_name.empty()) {
  410. use_name = "anon";
  411. }
  412. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  413. auto* global_variable = new llvm::GlobalVariable(
  414. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  415. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage, const_value,
  416. const_name + sep + use_name);
  417. global_variables_.Insert(const_inst_id, global_variable);
  418. return global_variable;
  419. }
  420. auto FileContext::GetOrCreateFunction(SemIR::FunctionId function_id,
  421. SemIR::SpecificId specific_id)
  422. -> llvm::Function* {
  423. // If we have already lowered a declaration of this function, just return it.
  424. auto** result = GetFunctionAddr(function_id, specific_id);
  425. if (!*result) {
  426. *result = BuildFunctionDecl(function_id, specific_id);
  427. }
  428. return *result;
  429. }
  430. auto FileContext::BuildFunctionTypeInfo(const SemIR::Function& function,
  431. SemIR::SpecificId specific_id)
  432. -> FunctionTypeInfo {
  433. const auto return_info =
  434. SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id);
  435. if (!return_info.is_valid()) {
  436. // The return type has not been completed, create a trivial type instead.
  437. return {.type =
  438. llvm::FunctionType::get(llvm::Type::getVoidTy(llvm_context()),
  439. /*isVarArg=*/false)};
  440. }
  441. auto get_llvm_type = [&](SemIR::TypeId type_id) -> llvm::Type* {
  442. if (!type_id.has_value()) {
  443. return nullptr;
  444. }
  445. return GetType(type_id);
  446. };
  447. // TODO: expose the `Call` parameter patterns in `Function`, and use them here
  448. // instead of reconstructing them via the syntactic parameter lists.
  449. auto implicit_param_patterns =
  450. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_patterns_id);
  451. auto param_patterns =
  452. sem_ir().inst_blocks().GetOrEmpty(function.param_patterns_id);
  453. auto* return_type = get_llvm_type(return_info.type_id);
  454. llvm::SmallVector<llvm::Type*> param_types;
  455. // Compute the return type to use for the LLVM function. If the initializing
  456. // representation doesn't produce a value, set the return type to void.
  457. // TODO: For the `Run` entry point, remap return type to i32 if it doesn't
  458. // return a value.
  459. llvm::Type* function_return_type =
  460. (return_info.is_valid() &&
  461. return_info.init_repr.kind == SemIR::InitRepr::ByCopy)
  462. ? return_type
  463. : llvm::Type::getVoidTy(llvm_context());
  464. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  465. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  466. // out a mechanism to compute the mapping between parameters and arguments on
  467. // demand.
  468. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  469. auto max_llvm_params = (return_info.has_return_slot() ? 1 : 0) +
  470. implicit_param_patterns.size() + param_patterns.size();
  471. param_types.reserve(max_llvm_params);
  472. param_inst_ids.reserve(max_llvm_params);
  473. auto return_param_id = SemIR::InstId::None;
  474. if (return_info.has_return_slot()) {
  475. param_types.push_back(
  476. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0));
  477. return_param_id = function.return_slot_pattern_id;
  478. param_inst_ids.push_back(return_param_id);
  479. }
  480. for (auto param_pattern_id : llvm::concat<const SemIR::InstId>(
  481. implicit_param_patterns, param_patterns)) {
  482. auto param_pattern_info = SemIR::Function::GetParamPatternInfoFromPatternId(
  483. sem_ir(), param_pattern_id);
  484. if (!param_pattern_info) {
  485. continue;
  486. }
  487. auto param_type_id = ExtractScrutineeType(
  488. sem_ir(), SemIR::GetTypeOfInstInSpecific(sem_ir(), specific_id,
  489. param_pattern_info->inst_id));
  490. CARBON_CHECK(
  491. !param_type_id.AsConstantId().is_symbolic(),
  492. "Found symbolic type id after resolution when lowering type {0}.",
  493. param_pattern_info->inst.type_id);
  494. switch (auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), param_type_id);
  495. value_rep.kind) {
  496. case SemIR::ValueRepr::Unknown:
  497. // This parameter type is incomplete. Fallback to describing the
  498. // function type as `void()`.
  499. return {.type = llvm::FunctionType::get(
  500. llvm::Type::getVoidTy(llvm_context()),
  501. /*isVarArg=*/false)};
  502. case SemIR::ValueRepr::None:
  503. break;
  504. case SemIR::ValueRepr::Copy:
  505. case SemIR::ValueRepr::Custom:
  506. case SemIR::ValueRepr::Pointer:
  507. auto* param_types_to_add = get_llvm_type(value_rep.type_id);
  508. param_types.push_back(param_types_to_add);
  509. param_inst_ids.push_back(param_pattern_id);
  510. break;
  511. }
  512. }
  513. return {.type = llvm::FunctionType::get(function_return_type, param_types,
  514. /*isVarArg=*/false),
  515. .param_inst_ids = std::move(param_inst_ids),
  516. .return_type = return_type,
  517. .return_param_id = return_param_id};
  518. }
  519. auto FileContext::HandleReferencedCppFunction(clang::FunctionDecl* cpp_decl)
  520. -> void {
  521. // TODO: To support recursive inline functions, collect all calls to
  522. // `HandleTopLevelDecl()` in a custom `ASTConsumer` configured in the
  523. // `ASTUnit`, and replay them in lowering in the `CodeGenerator`. See
  524. // https://discord.com/channels/655572317891461132/768530752592805919/1370509111585935443
  525. clang::FunctionDecl* cpp_def = cpp_decl->getDefinition();
  526. if (!cpp_def) {
  527. return;
  528. }
  529. // Create the LLVM function (`CodeGenModule::GetOrCreateLLVMFunction()`)
  530. // so that code generation (`CodeGenModule::EmitGlobal()`) would see this
  531. // function name (`CodeGenModule::getMangledName()`), and will generate
  532. // its definition.
  533. llvm::Constant* function_address =
  534. cpp_code_generator_->GetAddrOfGlobal(clang::GlobalDecl(cpp_def),
  535. /*isForDefinition=*/false);
  536. CARBON_CHECK(function_address);
  537. // Emit the function code.
  538. cpp_code_generator_->HandleTopLevelDecl(clang::DeclGroupRef(cpp_def));
  539. }
  540. auto FileContext::HandleReferencedSpecificFunction(
  541. SemIR::FunctionId function_id, SemIR::SpecificId specific_id,
  542. llvm::Type* llvm_type) -> void {
  543. CARBON_CHECK(specific_id.has_value());
  544. // Add this specific function to a list of specific functions whose
  545. // definitions we need to emit.
  546. // TODO: Don't do this if we know this function is emitted as a
  547. // non-discardable symbol in the IR for some other file.
  548. context().AddPendingSpecificFunctionDefinition({.context = this,
  549. .function_id = function_id,
  550. .specific_id = specific_id});
  551. // Create a unique fingerprint for the function type.
  552. // For now, we compute the function type fingerprint only for specifics,
  553. // though we might need it for all functions in order to create a canonical
  554. // fingerprint across translation units.
  555. llvm::BLAKE3 function_type_fingerprint;
  556. RawStringOstream os;
  557. llvm_type->print(os);
  558. function_type_fingerprint.update(os.TakeStr());
  559. function_type_fingerprint.final(
  560. lowered_specifics_type_fingerprint_.Get(specific_id));
  561. }
  562. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id,
  563. SemIR::SpecificId specific_id)
  564. -> llvm::Function* {
  565. const auto& function = sem_ir().functions().Get(function_id);
  566. // Don't lower generic functions. Note that associated functions in interfaces
  567. // have `Self` in scope, so are implicitly generic functions.
  568. if (function.generic_id.has_value() && !specific_id.has_value()) {
  569. return nullptr;
  570. }
  571. // Don't lower builtins.
  572. if (function.builtin_function_kind() != SemIR::BuiltinFunctionKind::None) {
  573. return nullptr;
  574. }
  575. // TODO: Consider tracking whether the function has been used, and only
  576. // lowering it if it's needed.
  577. auto function_type_info = BuildFunctionTypeInfo(function, specific_id);
  578. // TODO: For an imported inline function, consider generating an
  579. // `available_externally` definition.
  580. auto linkage = specific_id.has_value() ? llvm::Function::LinkOnceODRLinkage
  581. : llvm::Function::ExternalLinkage;
  582. Mangler m(*this);
  583. std::string mangled_name = m.Mangle(function_id, specific_id);
  584. if (auto* existing = llvm_module().getFunction(mangled_name)) {
  585. // We might have already lowered this function while lowering a different
  586. // file. That's OK.
  587. // TODO: Check-fail or maybe diagnose if the two LLVM functions are not
  588. // produced by declarations of the same Carbon function. Name collisions
  589. // between non-private members of the same library should have been
  590. // diagnosed by check if detected, but it's not clear that check will always
  591. // be able to see this problem. In theory, name collisions could also occur
  592. // due to fingerprint collision.
  593. return existing;
  594. }
  595. // If this is a C++ function, tell Clang that we referenced it.
  596. if (auto clang_decl_id = sem_ir().functions().Get(function_id).clang_decl_id;
  597. clang_decl_id.has_value()) {
  598. CARBON_CHECK(!specific_id.has_value(),
  599. "Specific functions cannot have C++ definitions");
  600. HandleReferencedCppFunction(clang::dyn_cast<clang::FunctionDecl>(
  601. sem_ir().clang_decls().Get(clang_decl_id)));
  602. // TODO: Check that the signature and mangling generated by Clang and the
  603. // one we generated are the same.
  604. }
  605. // If this is a specific function, we may need to do additional work to emit
  606. // its definition.
  607. if (specific_id.has_value()) {
  608. HandleReferencedSpecificFunction(function_id, specific_id,
  609. function_type_info.type);
  610. }
  611. auto* llvm_function = llvm::Function::Create(function_type_info.type, linkage,
  612. mangled_name, llvm_module());
  613. CARBON_CHECK(llvm_function->getName() == mangled_name,
  614. "Mangled name collision: {0}", mangled_name);
  615. // Set up parameters and the return slot.
  616. for (auto [inst_id, arg] : llvm::zip_equal(function_type_info.param_inst_ids,
  617. llvm_function->args())) {
  618. auto name_id = SemIR::NameId::None;
  619. if (inst_id == function_type_info.return_param_id) {
  620. name_id = SemIR::NameId::ReturnSlot;
  621. arg.addAttr(llvm::Attribute::getWithStructRetType(
  622. llvm_context(), function_type_info.return_type));
  623. } else {
  624. name_id = SemIR::GetPrettyNameFromPatternId(sem_ir(), inst_id);
  625. }
  626. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  627. }
  628. return llvm_function;
  629. }
  630. // Find the file and function ID describing the definition of a function.
  631. static auto GetFunctionDefinition(const SemIR::File* decl_ir,
  632. SemIR::FunctionId function_id)
  633. -> std::pair<const SemIR::File*, SemIR::FunctionId> {
  634. // Find the file containing the definition.
  635. auto decl_id = decl_ir->functions().Get(function_id).definition_id;
  636. if (!decl_id.has_value()) {
  637. // Function is not defined.
  638. return {nullptr, SemIR::FunctionId::None};
  639. }
  640. // Find the function declaration this function was originally imported from.
  641. while (true) {
  642. auto import_inst_id = decl_ir->insts().GetImportSource(decl_id);
  643. if (!import_inst_id.has_value()) {
  644. break;
  645. }
  646. auto import_inst = decl_ir->import_ir_insts().Get(import_inst_id);
  647. decl_ir = decl_ir->import_irs().Get(import_inst.ir_id()).sem_ir;
  648. decl_id = import_inst.inst_id();
  649. }
  650. auto decl_ir_function_id =
  651. decl_ir->insts().GetAs<SemIR::FunctionDecl>(decl_id).function_id;
  652. return {decl_ir, decl_ir_function_id};
  653. }
  654. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id,
  655. SemIR::SpecificId specific_id)
  656. -> void {
  657. auto [definition_ir, definition_ir_function_id] =
  658. GetFunctionDefinition(&sem_ir(), function_id);
  659. if (!definition_ir) {
  660. // Function is probably defined in another file; not an error.
  661. return;
  662. }
  663. const auto& definition_function =
  664. definition_ir->functions().Get(definition_ir_function_id);
  665. BuildFunctionBody(
  666. function_id, specific_id, sem_ir().functions().Get(function_id),
  667. context().GetFileContext(definition_ir), definition_function);
  668. }
  669. auto FileContext::BuildFunctionBody(SemIR::FunctionId function_id,
  670. SemIR::SpecificId specific_id,
  671. const SemIR::Function& declaration_function,
  672. FileContext& definition_context,
  673. const SemIR::Function& definition_function)
  674. -> void {
  675. // Note that `definition_function` is potentially from a different SemIR::File
  676. // than the one that this file context represents. Any lowering done for
  677. // values derived from `definition_function` should use `definition_context`
  678. // instead of our context.
  679. const auto& definition_ir = definition_context.sem_ir();
  680. auto* llvm_function = GetFunction(function_id, specific_id);
  681. CARBON_CHECK(llvm_function,
  682. "Attempting to define function that was not declared");
  683. const auto& body_block_ids = definition_function.body_block_ids;
  684. CARBON_DCHECK(!body_block_ids.empty(),
  685. "No function body blocks found during lowering.");
  686. // Store which specifics were already lowered (with definitions) for each
  687. // generic.
  688. if (declaration_function.generic_id.has_value() && specific_id.has_value()) {
  689. // TODO: We should track this in the definition context instead so that we
  690. // can deduplicate specifics from different files.
  691. AddLoweredSpecificForGeneric(declaration_function.generic_id, specific_id);
  692. }
  693. FunctionContext function_lowering(
  694. definition_context, llvm_function, *this, specific_id,
  695. InitializeFingerprintForSpecific(specific_id),
  696. definition_context.BuildDISubprogram(definition_function, llvm_function),
  697. vlog_stream_);
  698. // Add parameters to locals.
  699. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  700. // function parameters that was already computed in BuildFunctionDecl.
  701. // We should only do that once.
  702. auto call_param_ids = definition_ir.inst_blocks().GetOrEmpty(
  703. definition_function.call_params_id);
  704. int param_index = 0;
  705. // TODO: Find a way to ensure this code and the function-call lowering use
  706. // the same parameter ordering.
  707. // Lowers the given parameter. Must be called in LLVM calling convention
  708. // parameter order.
  709. auto lower_param = [&](SemIR::InstId param_id) {
  710. // Get the value of the parameter from the function argument.
  711. auto param_inst = definition_ir.insts().GetAs<SemIR::AnyParam>(param_id);
  712. llvm::Value* param_value;
  713. if (SemIR::ValueRepr::ForType(definition_ir, param_inst.type_id).kind !=
  714. SemIR::ValueRepr::None) {
  715. param_value = llvm_function->getArg(param_index);
  716. ++param_index;
  717. } else {
  718. param_value = llvm::PoisonValue::get(
  719. function_lowering.GetTypeOfInstInSpecific(param_id));
  720. }
  721. // The value of the parameter is the value of the argument.
  722. function_lowering.SetLocal(param_id, param_value);
  723. };
  724. // The subset of call_param_ids that is already in the order that the LLVM
  725. // calling convention expects.
  726. llvm::ArrayRef<SemIR::InstId> sequential_param_ids;
  727. if (declaration_function.return_slot_pattern_id.has_value()) {
  728. // The LLVM calling convention has the return slot first rather than last.
  729. // Note that this queries whether there is a return slot at the LLVM level,
  730. // whereas `function.return_slot_pattern_id.has_value()` queries whether
  731. // there is a return slot at the SemIR level.
  732. if (SemIR::ReturnTypeInfo::ForFunction(sem_ir(), declaration_function,
  733. specific_id)
  734. .has_return_slot()) {
  735. lower_param(call_param_ids.back());
  736. }
  737. sequential_param_ids = call_param_ids.drop_back();
  738. } else {
  739. sequential_param_ids = call_param_ids;
  740. }
  741. for (auto param_id : sequential_param_ids) {
  742. lower_param(param_id);
  743. }
  744. auto decl_block_id = SemIR::InstBlockId::None;
  745. if (function_id == sem_ir().global_ctor_id()) {
  746. decl_block_id = SemIR::InstBlockId::Empty;
  747. } else {
  748. decl_block_id =
  749. definition_ir.insts()
  750. .GetAs<SemIR::FunctionDecl>(definition_function.latest_decl_id())
  751. .decl_block_id;
  752. }
  753. // Lowers the contents of decl_block_id into the corresponding LLVM block,
  754. // creating it if it doesn't already exist.
  755. auto lower_block = [&](SemIR::InstBlockId block_id) {
  756. CARBON_VLOG("Lowering {0}\n", block_id);
  757. auto* llvm_block = function_lowering.GetBlock(block_id);
  758. // Keep the LLVM blocks in lexical order.
  759. llvm_block->moveBefore(llvm_function->end());
  760. function_lowering.builder().SetInsertPoint(llvm_block);
  761. function_lowering.LowerBlockContents(block_id);
  762. };
  763. lower_block(decl_block_id);
  764. // If the decl block is empty, reuse it as the first body block. We don't do
  765. // this when the decl block is non-empty so that any branches back to the
  766. // first body block don't also re-execute the decl.
  767. llvm::BasicBlock* block = function_lowering.builder().GetInsertBlock();
  768. if (block->empty() &&
  769. function_lowering.TryToReuseBlock(body_block_ids.front(), block)) {
  770. // Reuse this block as the first block of the function body.
  771. } else {
  772. function_lowering.builder().CreateBr(
  773. function_lowering.GetBlock(body_block_ids.front()));
  774. }
  775. // Lower all blocks.
  776. for (auto block_id : body_block_ids) {
  777. lower_block(block_id);
  778. }
  779. // LLVM requires that the entry block has no predecessors.
  780. auto* entry_block = &llvm_function->getEntryBlock();
  781. if (entry_block->hasNPredecessorsOrMore(1)) {
  782. auto* new_entry_block = llvm::BasicBlock::Create(
  783. llvm_context(), "entry", llvm_function, entry_block);
  784. llvm::BranchInst::Create(entry_block, new_entry_block);
  785. }
  786. // Emit fingerprint accumulated inside the function context.
  787. function_lowering.EmitFinalFingerprint();
  788. }
  789. auto FileContext::BuildDISubprogram(const SemIR::Function& function,
  790. const llvm::Function* llvm_function)
  791. -> llvm::DISubprogram* {
  792. if (!context().di_compile_unit()) {
  793. return nullptr;
  794. }
  795. auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
  796. CARBON_CHECK(name, "Unexpected special name for function: {0}",
  797. function.name_id);
  798. auto loc = GetLocForDI(function.definition_id);
  799. // TODO: Add more details here, including real subroutine type (once type
  800. // information is built), etc.
  801. return context().di_builder().createFunction(
  802. context().di_compile_unit(), *name, llvm_function->getName(),
  803. /*File=*/context().di_builder().createFile(loc.filename, ""),
  804. /*LineNo=*/loc.line_number,
  805. context().di_builder().createSubroutineType(
  806. context().di_builder().getOrCreateTypeArray(std::nullopt)),
  807. /*ScopeLine=*/0, llvm::DINode::FlagZero,
  808. llvm::DISubprogram::SPFlagDefinition);
  809. }
  810. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  811. // Implementations return the LLVM type for the instruction. This first overload
  812. // is the fallback handler for non-type instructions.
  813. template <typename InstT>
  814. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  815. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  816. -> llvm::Type* {
  817. CARBON_FATAL("Cannot use inst as type: {0}", inst);
  818. }
  819. template <typename InstT>
  820. requires(InstT::Kind.is_symbolic_when_type())
  821. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  822. -> llvm::Type* {
  823. // Treat non-monomorphized symbolic types as opaque.
  824. return llvm::StructType::get(context.llvm_context());
  825. }
  826. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  827. -> llvm::Type* {
  828. return llvm::ArrayType::get(
  829. context.GetType(context.sem_ir().types().GetTypeIdForTypeInstId(
  830. inst.element_type_inst_id)),
  831. *context.sem_ir().GetArrayBoundValue(inst.bound_id));
  832. }
  833. static auto BuildTypeForInst(FileContext& /*context*/, SemIR::AutoType inst)
  834. -> llvm::Type* {
  835. CARBON_FATAL("Unexpected builtin type in lowering: {0}", inst);
  836. }
  837. static auto BuildTypeForInst(FileContext& context, SemIR::BoolType /*inst*/)
  838. -> llvm::Type* {
  839. // TODO: We may want to have different representations for `bool` storage
  840. // (`i8`) versus for `bool` values (`i1`).
  841. return llvm::Type::getInt1Ty(context.llvm_context());
  842. }
  843. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  844. -> llvm::Type* {
  845. auto object_repr_id = context.sem_ir()
  846. .classes()
  847. .Get(inst.class_id)
  848. .GetObjectRepr(context.sem_ir(), inst.specific_id);
  849. return context.GetType(object_repr_id);
  850. }
  851. static auto BuildTypeForInst(FileContext& context, SemIR::ConstType inst)
  852. -> llvm::Type* {
  853. return context.GetType(
  854. context.sem_ir().types().GetTypeIdForTypeInstId(inst.inner_id));
  855. }
  856. static auto BuildTypeForInst(FileContext& context,
  857. SemIR::ImplWitnessAssociatedConstant inst)
  858. -> llvm::Type* {
  859. return context.GetType(inst.type_id);
  860. }
  861. static auto BuildTypeForInst(FileContext& /*context*/,
  862. SemIR::ErrorInst /*inst*/) -> llvm::Type* {
  863. // This is a complete type but uses of it should never be lowered.
  864. return nullptr;
  865. }
  866. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType /*inst*/)
  867. -> llvm::Type* {
  868. // TODO: Handle different sizes.
  869. return llvm::Type::getDoubleTy(context.llvm_context());
  870. }
  871. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  872. -> llvm::Type* {
  873. auto width =
  874. context.sem_ir().insts().TryGetAs<SemIR::IntValue>(inst.bit_width_id);
  875. CARBON_CHECK(width, "Can't lower int type with symbolic width");
  876. return llvm::IntegerType::get(
  877. context.llvm_context(),
  878. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  879. }
  880. static auto BuildTypeForInst(FileContext& context,
  881. SemIR::LegacyFloatType /*inst*/) -> llvm::Type* {
  882. return llvm::Type::getDoubleTy(context.llvm_context());
  883. }
  884. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  885. -> llvm::Type* {
  886. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  887. }
  888. static auto BuildTypeForInst(FileContext& /*context*/,
  889. SemIR::PatternType /*inst*/) -> llvm::Type* {
  890. CARBON_FATAL("Unexpected pattern type in lowering");
  891. }
  892. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  893. -> llvm::Type* {
  894. auto fields = context.sem_ir().struct_type_fields().Get(inst.fields_id);
  895. llvm::SmallVector<llvm::Type*> subtypes;
  896. subtypes.reserve(fields.size());
  897. for (auto field : fields) {
  898. subtypes.push_back(context.GetType(
  899. context.sem_ir().types().GetTypeIdForTypeInstId(field.type_inst_id)));
  900. }
  901. return llvm::StructType::get(context.llvm_context(), subtypes);
  902. }
  903. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  904. -> llvm::Type* {
  905. // TODO: Investigate special-casing handling of empty tuples so that they
  906. // can be collectively replaced with LLVM's void, particularly around
  907. // function returns. LLVM doesn't allow declaring variables with a void
  908. // type, so that may require significant special casing.
  909. auto elements = context.sem_ir().inst_blocks().Get(inst.type_elements_id);
  910. llvm::SmallVector<llvm::Type*> subtypes;
  911. subtypes.reserve(elements.size());
  912. for (auto type_id : context.sem_ir().types().GetBlockAsTypeIds(elements)) {
  913. subtypes.push_back(context.GetType(type_id));
  914. }
  915. return llvm::StructType::get(context.llvm_context(), subtypes);
  916. }
  917. static auto BuildTypeForInst(FileContext& context, SemIR::TypeType /*inst*/)
  918. -> llvm::Type* {
  919. return context.GetTypeType();
  920. }
  921. static auto BuildTypeForInst(FileContext& context, SemIR::VtableType /*inst*/)
  922. -> llvm::Type* {
  923. return llvm::Type::getVoidTy(context.llvm_context());
  924. }
  925. template <typename InstT>
  926. requires(InstT::Kind.template IsAnyOf<SemIR::SpecificFunctionType,
  927. SemIR::StringType>())
  928. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  929. -> llvm::Type* {
  930. // TODO: Decide how we want to represent `StringType`.
  931. return llvm::PointerType::get(context.llvm_context(), 0);
  932. }
  933. template <typename InstT>
  934. requires(InstT::Kind
  935. .template IsAnyOf<SemIR::BoundMethodType, SemIR::IntLiteralType,
  936. SemIR::NamespaceType, SemIR::WitnessType>())
  937. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  938. -> llvm::Type* {
  939. // Return an empty struct as a placeholder.
  940. return llvm::StructType::get(context.llvm_context());
  941. }
  942. template <typename InstT>
  943. requires(InstT::Kind.template IsAnyOf<
  944. SemIR::AssociatedEntityType, SemIR::FacetType, SemIR::FunctionType,
  945. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  946. SemIR::GenericInterfaceType, SemIR::InstType,
  947. SemIR::UnboundElementType, SemIR::WhereExpr>())
  948. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  949. -> llvm::Type* {
  950. // Return an empty struct as a placeholder.
  951. // TODO: Should we model an interface as a witness table, or an associated
  952. // entity as an index?
  953. return llvm::StructType::get(context.llvm_context());
  954. }
  955. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  956. // Use overload resolution to select the implementation, producing compile
  957. // errors when BuildTypeForInst isn't defined for a given instruction.
  958. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  959. #define CARBON_SEM_IR_INST_KIND(Name) \
  960. case CARBON_KIND(SemIR::Name inst): { \
  961. return BuildTypeForInst(*this, inst); \
  962. }
  963. #include "toolchain/sem_ir/inst_kind.def"
  964. }
  965. }
  966. auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  967. -> llvm::GlobalVariable* {
  968. Mangler m(*this);
  969. auto mangled_name = m.MangleGlobalVariable(var_storage.pattern_id);
  970. auto linkage = llvm::GlobalVariable::ExternalLinkage;
  971. // If the variable doesn't have an externally-visible name, demote it to
  972. // internal linkage and invent a plausible name that shouldn't collide with
  973. // any of our real manglings.
  974. if (mangled_name.empty()) {
  975. linkage = llvm::GlobalVariable::InternalLinkage;
  976. if (inst_namer_) {
  977. mangled_name =
  978. ("var.anon" + inst_namer_->GetUnscopedNameFor(var_storage.pattern_id))
  979. .str();
  980. }
  981. }
  982. auto* type = GetType(var_storage.type_id);
  983. return new llvm::GlobalVariable(llvm_module(), type,
  984. /*isConstant=*/false, linkage,
  985. /*Initializer=*/nullptr, mangled_name);
  986. }
  987. auto FileContext::GetLocForDI(SemIR::InstId inst_id) -> Context::LocForDI {
  988. return context().GetLocForDI(
  989. GetAbsoluteNodeId(sem_ir_, SemIR::LocId(inst_id)).back());
  990. }
  991. auto FileContext::BuildVtable(const SemIR::Class& class_info)
  992. -> llvm::GlobalVariable* {
  993. // Bail out if this class is not dynamic (this will account for classes that
  994. // are declared-and-not-defined (including extern declarations) as well).
  995. if (!class_info.is_dynamic) {
  996. return nullptr;
  997. }
  998. // Vtables can't be generated for generics, only for their specifics - and
  999. // must be done lazily based on the use of those specifics.
  1000. if (class_info.generic_id != SemIR::GenericId::None) {
  1001. return nullptr;
  1002. }
  1003. Mangler m(*this);
  1004. std::string mangled_name = m.MangleVTable(class_info);
  1005. if (sem_ir()
  1006. .insts()
  1007. .GetImportSource(class_info.first_owning_decl_id)
  1008. .has_value()) {
  1009. // Emit a declaration of an imported vtable using a(n opaque) pointer type.
  1010. // This doesn't have to match the definition that appears elsewhere, it'll
  1011. // still get merged correctly.
  1012. auto* gv = new llvm::GlobalVariable(
  1013. llvm_module(),
  1014. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0),
  1015. /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
  1016. mangled_name);
  1017. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1018. return gv;
  1019. }
  1020. auto canonical_vtable_id =
  1021. sem_ir().constant_values().GetConstantInstId(class_info.vtable_id);
  1022. auto vtable_inst_block =
  1023. sem_ir().inst_blocks().Get(sem_ir()
  1024. .insts()
  1025. .GetAs<SemIR::Vtable>(canonical_vtable_id)
  1026. .virtual_functions_id);
  1027. auto* entry_type = llvm::IntegerType::getInt32Ty(llvm_context());
  1028. auto* table_type = llvm::ArrayType::get(entry_type, vtable_inst_block.size());
  1029. auto* llvm_vtable = new llvm::GlobalVariable(
  1030. llvm_module(), table_type, /*isConstant=*/true,
  1031. llvm::GlobalValue::ExternalLinkage, nullptr, mangled_name);
  1032. auto* i32_type = llvm::IntegerType::getInt32Ty(llvm_context());
  1033. auto* i64_type = llvm::IntegerType::getInt64Ty(llvm_context());
  1034. auto* vtable_const_int =
  1035. llvm::ConstantExpr::getPtrToInt(llvm_vtable, i64_type);
  1036. llvm::SmallVector<llvm::Constant*> vfuncs;
  1037. vfuncs.reserve(vtable_inst_block.size());
  1038. for (auto fn_decl_id : vtable_inst_block) {
  1039. auto fn_decl = GetCalleeFunction(sem_ir(), fn_decl_id);
  1040. vfuncs.push_back(llvm::ConstantExpr::getTrunc(
  1041. llvm::ConstantExpr::getSub(
  1042. llvm::ConstantExpr::getPtrToInt(
  1043. GetOrCreateFunction(fn_decl.function_id,
  1044. SemIR::SpecificId::None),
  1045. i64_type),
  1046. vtable_const_int),
  1047. i32_type));
  1048. }
  1049. llvm_vtable->setInitializer(llvm::ConstantArray::get(table_type, vfuncs));
  1050. llvm_vtable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  1051. return llvm_vtable;
  1052. }
  1053. } // namespace Carbon::Lower