file_context.cpp 46 KB

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