file_context.cpp 47 KB

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