file_context.cpp 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  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 "common/check.h"
  10. #include "common/vlog.h"
  11. #include "llvm/ADT/STLExtras.h"
  12. #include "llvm/ADT/Sequence.h"
  13. #include "llvm/Transforms/Utils/ModuleUtils.h"
  14. #include "toolchain/base/kind_switch.h"
  15. #include "toolchain/lower/constant.h"
  16. #include "toolchain/lower/function_context.h"
  17. #include "toolchain/lower/mangler.h"
  18. #include "toolchain/sem_ir/absolute_node_id.h"
  19. #include "toolchain/sem_ir/entry_point.h"
  20. #include "toolchain/sem_ir/file.h"
  21. #include "toolchain/sem_ir/function.h"
  22. #include "toolchain/sem_ir/generic.h"
  23. #include "toolchain/sem_ir/ids.h"
  24. #include "toolchain/sem_ir/inst.h"
  25. #include "toolchain/sem_ir/inst_kind.h"
  26. #include "toolchain/sem_ir/pattern.h"
  27. #include "toolchain/sem_ir/typed_insts.h"
  28. namespace Carbon::Lower {
  29. FileContext::FileContext(
  30. llvm::LLVMContext& llvm_context,
  31. std::optional<llvm::ArrayRef<Parse::GetTreeAndSubtreesFn>>
  32. tree_and_subtrees_getters_for_debug_info,
  33. llvm::StringRef module_name, const SemIR::File& sem_ir,
  34. clang::ASTUnit* cpp_ast, const SemIR::InstNamer* inst_namer,
  35. llvm::raw_ostream* vlog_stream)
  36. : llvm_context_(&llvm_context),
  37. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  38. di_builder_(*llvm_module_),
  39. di_compile_unit_(
  40. tree_and_subtrees_getters_for_debug_info
  41. ? BuildDICompileUnit(module_name, *llvm_module_, di_builder_)
  42. : nullptr),
  43. tree_and_subtrees_getters_for_debug_info_(
  44. tree_and_subtrees_getters_for_debug_info),
  45. sem_ir_(&sem_ir),
  46. cpp_ast_(cpp_ast),
  47. inst_namer_(inst_namer),
  48. vlog_stream_(vlog_stream) {
  49. CARBON_CHECK(!sem_ir.has_errors(),
  50. "Generating LLVM IR from invalid SemIR::File is unsupported.");
  51. }
  52. // TODO: Move this to lower.cpp.
  53. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  54. CARBON_CHECK(llvm_module_, "Run can only be called once.");
  55. // Lower all types that were required to be complete.
  56. types_.resize(sem_ir_->insts().size());
  57. for (auto type_id : sem_ir_->types().complete_types()) {
  58. if (type_id.index >= 0) {
  59. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  60. }
  61. }
  62. // Lower function declarations.
  63. functions_.resize_for_overwrite(sem_ir_->functions().size());
  64. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  65. functions_[id.index] = BuildFunctionDecl(id);
  66. }
  67. for (const auto& class_info : sem_ir_->classes().array_ref()) {
  68. if (auto* llvm_vtable = BuildVtable(class_info)) {
  69. global_variables_.Insert(class_info.vtable_id, llvm_vtable);
  70. }
  71. }
  72. // Specific functions are lowered when we emit a reference to them.
  73. specific_functions_.resize(sem_ir_->specifics().size());
  74. // Lower global variable declarations.
  75. for (auto inst_id :
  76. sem_ir().inst_blocks().Get(sem_ir().top_inst_block_id())) {
  77. // Only `VarStorage` indicates a global variable declaration in the
  78. // top instruction block.
  79. if (auto var = sem_ir().insts().TryGetAs<SemIR::VarStorage>(inst_id)) {
  80. global_variables_.Insert(inst_id, BuildGlobalVariableDecl(*var));
  81. }
  82. }
  83. // Lower constants.
  84. constants_.resize(sem_ir_->insts().size());
  85. LowerConstants(*this, constants_);
  86. // Lower function definitions.
  87. for (auto [id, _] : sem_ir_->functions().enumerate()) {
  88. BuildFunctionDefinition(id);
  89. }
  90. // Lower function definitions for generics.
  91. // This cannot be a range-based loop, as new definitions can be added
  92. // while building other definitions.
  93. // NOLINTNEXTLINE
  94. for (size_t i = 0; i != specific_function_definitions_.size(); ++i) {
  95. auto [function_id, specific_id] = specific_function_definitions_[i];
  96. BuildFunctionDefinition(function_id, specific_id);
  97. }
  98. // Append `__global_init` to `llvm::global_ctors` to initialize global
  99. // variables.
  100. if (sem_ir().global_ctor_id().has_value()) {
  101. llvm::appendToGlobalCtors(llvm_module(),
  102. GetFunction(sem_ir().global_ctor_id()),
  103. /*Priority=*/0);
  104. }
  105. return std::move(llvm_module_);
  106. }
  107. auto FileContext::BuildDICompileUnit(llvm::StringRef module_name,
  108. llvm::Module& llvm_module,
  109. llvm::DIBuilder& di_builder)
  110. -> llvm::DICompileUnit* {
  111. llvm_module.addModuleFlag(llvm::Module::Max, "Dwarf Version", 5);
  112. llvm_module.addModuleFlag(llvm::Module::Warning, "Debug Info Version",
  113. llvm::DEBUG_METADATA_VERSION);
  114. // TODO: Include directory path in the compile_unit_file.
  115. llvm::DIFile* compile_unit_file = di_builder.createFile(module_name, "");
  116. // TODO: Introduce a new language code for Carbon. C works well for now since
  117. // it's something debuggers will already know/have support for at least.
  118. // Probably have to bump to C++ at some point for virtual functions,
  119. // templates, etc.
  120. return di_builder.createCompileUnit(llvm::dwarf::DW_LANG_C, compile_unit_file,
  121. "carbon",
  122. /*isOptimized=*/false, /*Flags=*/"",
  123. /*RV=*/0);
  124. }
  125. auto FileContext::GetGlobal(SemIR::InstId inst_id,
  126. SemIR::SpecificId specific_id) -> llvm::Value* {
  127. auto const_id = GetConstantValueInSpecific(sem_ir(), specific_id, inst_id);
  128. CARBON_CHECK(const_id.is_concrete(), "Missing value: {0} {1} {2}", inst_id,
  129. specific_id, sem_ir().insts().Get(inst_id));
  130. auto const_inst_id = sem_ir().constant_values().GetInstId(const_id);
  131. // For value expressions and initializing expressions, the value produced by
  132. // a constant instruction is a value representation of the constant. For
  133. // initializing expressions, `FinishInit` will perform a copy if needed.
  134. // TODO: Handle reference expression constants.
  135. auto* const_value = constants_[const_inst_id.index];
  136. auto value_rep = SemIR::ValueRepr::ForType(
  137. sem_ir(), sem_ir().insts().Get(const_inst_id).type_id());
  138. if (value_rep.kind != SemIR::ValueRepr::Pointer) {
  139. return const_value;
  140. }
  141. if (auto result = global_variables().Lookup(const_inst_id)) {
  142. return result.value();
  143. }
  144. // Include both the name of the constant, if any, and the point of use in
  145. // the name of the variable.
  146. llvm::StringRef const_name;
  147. llvm::StringRef use_name;
  148. if (inst_namer_) {
  149. const_name = inst_namer_->GetUnscopedNameFor(const_inst_id);
  150. use_name = inst_namer_->GetUnscopedNameFor(inst_id);
  151. }
  152. // We always need to give the global a name even if the instruction namer
  153. // doesn't have one to use.
  154. if (const_name.empty()) {
  155. const_name = "const";
  156. }
  157. if (use_name.empty()) {
  158. use_name = "anon";
  159. }
  160. llvm::StringRef sep = (use_name[0] == '.') ? "" : ".";
  161. auto* global_variable = new llvm::GlobalVariable(
  162. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  163. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage, const_value,
  164. const_name + sep + use_name);
  165. global_variables_.Insert(const_inst_id, global_variable);
  166. return global_variable;
  167. }
  168. auto FileContext::GetOrCreateFunction(SemIR::FunctionId function_id,
  169. SemIR::SpecificId specific_id)
  170. -> llvm::Function* {
  171. // Non-generic functions are declared eagerly.
  172. if (!specific_id.has_value()) {
  173. return GetFunction(function_id);
  174. }
  175. if (auto* result = specific_functions_[specific_id.index]) {
  176. return result;
  177. }
  178. auto* result = BuildFunctionDecl(function_id, specific_id);
  179. // TODO: Add this function to a list of specific functions whose definitions
  180. // we need to emit.
  181. specific_functions_[specific_id.index] = result;
  182. // TODO: Use this to generate definitions for these functions.
  183. specific_function_definitions_.push_back({function_id, specific_id});
  184. return result;
  185. }
  186. auto FileContext::BuildFunctionTypeInfo(const SemIR::Function& function,
  187. SemIR::SpecificId specific_id)
  188. -> FunctionTypeInfo {
  189. const auto return_info =
  190. SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id);
  191. if (!return_info.is_valid()) {
  192. // The return type has not been completed, create a trivial type instead.
  193. return {.type =
  194. llvm::FunctionType::get(llvm::Type::getVoidTy(llvm_context()),
  195. /*isVarArg=*/false)};
  196. }
  197. auto get_llvm_type = [&](SemIR::TypeId type_id) -> llvm::Type* {
  198. if (!type_id.has_value()) {
  199. return nullptr;
  200. }
  201. return GetType(type_id);
  202. };
  203. // TODO: expose the `Call` parameter patterns in `Function`, and use them here
  204. // instead of reconstructing them via the syntactic parameter lists.
  205. auto implicit_param_patterns =
  206. sem_ir().inst_blocks().GetOrEmpty(function.implicit_param_patterns_id);
  207. auto param_patterns =
  208. sem_ir().inst_blocks().GetOrEmpty(function.param_patterns_id);
  209. auto* return_type = get_llvm_type(return_info.type_id);
  210. llvm::SmallVector<llvm::Type*> param_types;
  211. // Compute the return type to use for the LLVM function. If the initializing
  212. // representation doesn't produce a value, set the return type to void.
  213. // TODO: For the `Run` entry point, remap return type to i32 if it doesn't
  214. // return a value.
  215. llvm::Type* function_return_type =
  216. (return_info.is_valid() &&
  217. return_info.init_repr.kind == SemIR::InitRepr::ByCopy)
  218. ? return_type
  219. : llvm::Type::getVoidTy(llvm_context());
  220. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  221. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  222. // out a mechanism to compute the mapping between parameters and arguments on
  223. // demand.
  224. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  225. auto max_llvm_params = (return_info.has_return_slot() ? 1 : 0) +
  226. implicit_param_patterns.size() + param_patterns.size();
  227. param_types.reserve(max_llvm_params);
  228. param_inst_ids.reserve(max_llvm_params);
  229. auto return_param_id = SemIR::InstId::None;
  230. if (return_info.has_return_slot()) {
  231. param_types.push_back(
  232. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0));
  233. return_param_id = function.return_slot_pattern_id;
  234. param_inst_ids.push_back(return_param_id);
  235. }
  236. for (auto param_pattern_id : llvm::concat<const SemIR::InstId>(
  237. implicit_param_patterns, param_patterns)) {
  238. auto param_pattern_info = SemIR::Function::GetParamPatternInfoFromPatternId(
  239. sem_ir(), param_pattern_id);
  240. if (!param_pattern_info) {
  241. continue;
  242. }
  243. auto param_type_id = ExtractScrutineeType(
  244. sem_ir(), SemIR::GetTypeOfInstInSpecific(sem_ir(), specific_id,
  245. param_pattern_info->inst_id));
  246. CARBON_CHECK(
  247. !param_type_id.AsConstantId().is_symbolic(),
  248. "Found symbolic type id after resolution when lowering type {0}.",
  249. param_pattern_info->inst.type_id);
  250. switch (auto value_rep = SemIR::ValueRepr::ForType(sem_ir(), param_type_id);
  251. value_rep.kind) {
  252. case SemIR::ValueRepr::Unknown:
  253. // This parameter type is incomplete. Fallback to describing the
  254. // function type as `void()`.
  255. return {.type = llvm::FunctionType::get(
  256. llvm::Type::getVoidTy(llvm_context()),
  257. /*isVarArg=*/false)};
  258. case SemIR::ValueRepr::None:
  259. break;
  260. case SemIR::ValueRepr::Copy:
  261. case SemIR::ValueRepr::Custom:
  262. case SemIR::ValueRepr::Pointer:
  263. auto* param_types_to_add = get_llvm_type(value_rep.type_id);
  264. param_types.push_back(param_types_to_add);
  265. param_inst_ids.push_back(param_pattern_id);
  266. break;
  267. }
  268. }
  269. return {.type = llvm::FunctionType::get(function_return_type, param_types,
  270. /*isVarArg=*/false),
  271. .param_inst_ids = std::move(param_inst_ids),
  272. .return_type = return_type,
  273. .return_param_id = return_param_id};
  274. }
  275. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id,
  276. SemIR::SpecificId specific_id)
  277. -> llvm::Function* {
  278. const auto& function = sem_ir().functions().Get(function_id);
  279. // Don't lower generic functions. Note that associated functions in interfaces
  280. // have `Self` in scope, so are implicitly generic functions.
  281. if (function.generic_id.has_value() && !specific_id.has_value()) {
  282. return nullptr;
  283. }
  284. // Don't lower builtins.
  285. if (function.builtin_function_kind != SemIR::BuiltinFunctionKind::None) {
  286. return nullptr;
  287. }
  288. // TODO: Consider tracking whether the function has been used, and only
  289. // lowering it if it's needed.
  290. auto function_type_info = BuildFunctionTypeInfo(function, specific_id);
  291. Mangler m(*this);
  292. std::string mangled_name = m.Mangle(function_id, specific_id);
  293. auto* llvm_function = llvm::Function::Create(function_type_info.type,
  294. llvm::Function::ExternalLinkage,
  295. mangled_name, llvm_module());
  296. CARBON_CHECK(llvm_function->getName() == mangled_name,
  297. "Mangled name collision: {0}", mangled_name);
  298. // Set up parameters and the return slot.
  299. for (auto [inst_id, arg] : llvm::zip_equal(function_type_info.param_inst_ids,
  300. llvm_function->args())) {
  301. auto name_id = SemIR::NameId::None;
  302. if (inst_id == function_type_info.return_param_id) {
  303. name_id = SemIR::NameId::ReturnSlot;
  304. arg.addAttr(llvm::Attribute::getWithStructRetType(
  305. llvm_context(), function_type_info.return_type));
  306. } else {
  307. name_id = SemIR::GetPrettyNameFromPatternId(sem_ir(), inst_id);
  308. }
  309. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  310. }
  311. return llvm_function;
  312. }
  313. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id,
  314. SemIR::SpecificId specific_id)
  315. -> void {
  316. const auto& function = sem_ir().functions().Get(function_id);
  317. const auto& body_block_ids = function.body_block_ids;
  318. if (body_block_ids.empty()) {
  319. // Function is probably defined in another file; not an error.
  320. return;
  321. }
  322. llvm::Function* llvm_function;
  323. if (specific_id.has_value()) {
  324. llvm_function = specific_functions_[specific_id.index];
  325. } else {
  326. llvm_function = GetFunction(function_id);
  327. if (!llvm_function) {
  328. // We chose not to lower this function at all, for example because it's a
  329. // generic function.
  330. return;
  331. }
  332. }
  333. // For non-generics we do not lower. For generics, the llvm function was
  334. // created via GetOrCreateFunction prior to this when building the
  335. // declaration.
  336. BuildFunctionBody(function_id, function, llvm_function, specific_id);
  337. }
  338. auto FileContext::BuildFunctionBody(SemIR::FunctionId function_id,
  339. const SemIR::Function& function,
  340. llvm::Function* llvm_function,
  341. SemIR::SpecificId specific_id) -> void {
  342. const auto& body_block_ids = function.body_block_ids;
  343. CARBON_DCHECK(llvm_function, "LLVM Function not found when lowering body.");
  344. CARBON_DCHECK(!body_block_ids.empty(),
  345. "No function body blocks found during lowering.");
  346. FunctionContext function_lowering(*this, llvm_function, specific_id,
  347. BuildDISubprogram(function, llvm_function),
  348. vlog_stream_);
  349. // Add parameters to locals.
  350. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  351. // function parameters that was already computed in BuildFunctionDecl.
  352. // We should only do that once.
  353. auto call_param_ids =
  354. sem_ir().inst_blocks().GetOrEmpty(function.call_params_id);
  355. int param_index = 0;
  356. // TODO: Find a way to ensure this code and the function-call lowering use
  357. // the same parameter ordering.
  358. // Lowers the given parameter. Must be called in LLVM calling convention
  359. // parameter order.
  360. auto lower_param = [&](SemIR::InstId param_id) {
  361. // Get the value of the parameter from the function argument.
  362. auto param_inst = sem_ir().insts().GetAs<SemIR::AnyParam>(param_id);
  363. llvm::Value* param_value;
  364. if (SemIR::ValueRepr::ForType(sem_ir(), param_inst.type_id).kind !=
  365. SemIR::ValueRepr::None) {
  366. param_value = llvm_function->getArg(param_index);
  367. ++param_index;
  368. } else {
  369. param_value = llvm::PoisonValue::get(GetType(
  370. SemIR::GetTypeOfInstInSpecific(sem_ir(), specific_id, param_id)));
  371. }
  372. // The value of the parameter is the value of the argument.
  373. function_lowering.SetLocal(param_id, param_value);
  374. };
  375. // The subset of call_param_ids that is already in the order that the LLVM
  376. // calling convention expects.
  377. llvm::ArrayRef<SemIR::InstId> sequential_param_ids;
  378. if (function.return_slot_pattern_id.has_value()) {
  379. // The LLVM calling convention has the return slot first rather than last.
  380. // Note that this queries whether there is a return slot at the LLVM level,
  381. // whereas `function.return_slot_pattern_id.has_value()` queries whether
  382. // there is a return slot at the SemIR level.
  383. if (SemIR::ReturnTypeInfo::ForFunction(sem_ir(), function, specific_id)
  384. .has_return_slot()) {
  385. lower_param(call_param_ids.back());
  386. }
  387. sequential_param_ids = call_param_ids.drop_back();
  388. } else {
  389. sequential_param_ids = call_param_ids;
  390. }
  391. for (auto param_id : sequential_param_ids) {
  392. lower_param(param_id);
  393. }
  394. auto decl_block_id = SemIR::InstBlockId::None;
  395. if (function_id == sem_ir().global_ctor_id()) {
  396. decl_block_id = SemIR::InstBlockId::Empty;
  397. } else {
  398. decl_block_id = sem_ir()
  399. .insts()
  400. .GetAs<SemIR::FunctionDecl>(function.latest_decl_id())
  401. .decl_block_id;
  402. }
  403. // Lowers the contents of block_id into the corresponding LLVM block,
  404. // creating it if it doesn't already exist.
  405. auto lower_block = [&](SemIR::InstBlockId block_id) {
  406. CARBON_VLOG("Lowering {0}\n", block_id);
  407. auto* llvm_block = function_lowering.GetBlock(block_id);
  408. // Keep the LLVM blocks in lexical order.
  409. llvm_block->moveBefore(llvm_function->end());
  410. function_lowering.builder().SetInsertPoint(llvm_block);
  411. function_lowering.LowerBlockContents(block_id);
  412. };
  413. lower_block(decl_block_id);
  414. // If the decl block is empty, reuse it as the first body block. We don't do
  415. // this when the decl block is non-empty so that any branches back to the
  416. // first body block don't also re-execute the decl.
  417. llvm::BasicBlock* block = function_lowering.builder().GetInsertBlock();
  418. if (block->empty() &&
  419. function_lowering.TryToReuseBlock(body_block_ids.front(), block)) {
  420. // Reuse this block as the first block of the function body.
  421. } else {
  422. function_lowering.builder().CreateBr(
  423. function_lowering.GetBlock(body_block_ids.front()));
  424. }
  425. // Lower all blocks.
  426. for (auto block_id : body_block_ids) {
  427. lower_block(block_id);
  428. }
  429. // LLVM requires that the entry block has no predecessors.
  430. auto* entry_block = &llvm_function->getEntryBlock();
  431. if (entry_block->hasNPredecessorsOrMore(1)) {
  432. auto* new_entry_block = llvm::BasicBlock::Create(
  433. llvm_context(), "entry", llvm_function, entry_block);
  434. llvm::BranchInst::Create(entry_block, new_entry_block);
  435. }
  436. }
  437. auto FileContext::BuildDISubprogram(const SemIR::Function& function,
  438. const llvm::Function* llvm_function)
  439. -> llvm::DISubprogram* {
  440. if (!di_compile_unit_) {
  441. return nullptr;
  442. }
  443. auto name = sem_ir().names().GetAsStringIfIdentifier(function.name_id);
  444. CARBON_CHECK(name, "Unexpected special name for function: {0}",
  445. function.name_id);
  446. auto loc = GetLocForDI(function.definition_id);
  447. // TODO: Add more details here, including real subroutine type (once type
  448. // information is built), etc.
  449. return di_builder_.createFunction(
  450. di_compile_unit_, *name, llvm_function->getName(),
  451. /*File=*/di_builder_.createFile(loc.filename, ""),
  452. /*LineNo=*/loc.line_number,
  453. di_builder_.createSubroutineType(
  454. di_builder_.getOrCreateTypeArray(std::nullopt)),
  455. /*ScopeLine=*/0, llvm::DINode::FlagZero,
  456. llvm::DISubprogram::SPFlagDefinition);
  457. }
  458. // BuildTypeForInst is used to construct types for FileContext::BuildType below.
  459. // Implementations return the LLVM type for the instruction. This first overload
  460. // is the fallback handler for non-type instructions.
  461. template <typename InstT>
  462. requires(InstT::Kind.is_type() == SemIR::InstIsType::Never)
  463. static auto BuildTypeForInst(FileContext& /*context*/, InstT inst)
  464. -> llvm::Type* {
  465. CARBON_FATAL("Cannot use inst as type: {0}", inst);
  466. }
  467. template <typename InstT>
  468. requires(InstT::Kind.constant_kind() ==
  469. SemIR::InstConstantKind::SymbolicOnly &&
  470. InstT::Kind.is_type() != SemIR::InstIsType::Never)
  471. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  472. -> llvm::Type* {
  473. // Treat non-monomorphized symbolic types as opaque.
  474. return llvm::StructType::get(context.llvm_context());
  475. }
  476. static auto BuildTypeForInst(FileContext& context, SemIR::ArrayType inst)
  477. -> llvm::Type* {
  478. return llvm::ArrayType::get(
  479. context.GetType(context.sem_ir().types().GetTypeIdForTypeInstId(
  480. inst.element_type_inst_id)),
  481. *context.sem_ir().GetArrayBoundValue(inst.bound_id));
  482. }
  483. static auto BuildTypeForInst(FileContext& /*context*/, SemIR::AutoType inst)
  484. -> llvm::Type* {
  485. CARBON_FATAL("Unexpected builtin type in lowering: {0}", inst);
  486. }
  487. static auto BuildTypeForInst(FileContext& context, SemIR::BoolType /*inst*/)
  488. -> llvm::Type* {
  489. // TODO: We may want to have different representations for `bool` storage
  490. // (`i8`) versus for `bool` values (`i1`).
  491. return llvm::Type::getInt1Ty(context.llvm_context());
  492. }
  493. static auto BuildTypeForInst(FileContext& context, SemIR::ClassType inst)
  494. -> llvm::Type* {
  495. auto object_repr_id = context.sem_ir()
  496. .classes()
  497. .Get(inst.class_id)
  498. .GetObjectRepr(context.sem_ir(), inst.specific_id);
  499. return context.GetType(object_repr_id);
  500. }
  501. static auto BuildTypeForInst(FileContext& context, SemIR::ConstType inst)
  502. -> llvm::Type* {
  503. return context.GetType(
  504. context.sem_ir().types().GetTypeIdForTypeInstId(inst.inner_id));
  505. }
  506. static auto BuildTypeForInst(FileContext& context,
  507. SemIR::ImplWitnessAssociatedConstant inst)
  508. -> llvm::Type* {
  509. return context.GetType(inst.type_id);
  510. }
  511. static auto BuildTypeForInst(FileContext& /*context*/,
  512. SemIR::ErrorInst /*inst*/) -> llvm::Type* {
  513. // This is a complete type but uses of it should never be lowered.
  514. return nullptr;
  515. }
  516. static auto BuildTypeForInst(FileContext& context, SemIR::FloatType /*inst*/)
  517. -> llvm::Type* {
  518. // TODO: Handle different sizes.
  519. return llvm::Type::getDoubleTy(context.llvm_context());
  520. }
  521. static auto BuildTypeForInst(FileContext& context, SemIR::IntType inst)
  522. -> llvm::Type* {
  523. auto width =
  524. context.sem_ir().insts().TryGetAs<SemIR::IntValue>(inst.bit_width_id);
  525. CARBON_CHECK(width, "Can't lower int type with symbolic width");
  526. return llvm::IntegerType::get(
  527. context.llvm_context(),
  528. context.sem_ir().ints().Get(width->int_id).getZExtValue());
  529. }
  530. static auto BuildTypeForInst(FileContext& context,
  531. SemIR::LegacyFloatType /*inst*/) -> llvm::Type* {
  532. return llvm::Type::getDoubleTy(context.llvm_context());
  533. }
  534. static auto BuildTypeForInst(FileContext& context, SemIR::PointerType /*inst*/)
  535. -> llvm::Type* {
  536. return llvm::PointerType::get(context.llvm_context(), /*AddressSpace=*/0);
  537. }
  538. static auto BuildTypeForInst(FileContext& /*context*/,
  539. SemIR::PatternType /*inst*/) -> llvm::Type* {
  540. CARBON_FATAL("Unexpected pattern type in lowering");
  541. }
  542. static auto BuildTypeForInst(FileContext& context, SemIR::StructType inst)
  543. -> llvm::Type* {
  544. auto fields = context.sem_ir().struct_type_fields().Get(inst.fields_id);
  545. llvm::SmallVector<llvm::Type*> subtypes;
  546. subtypes.reserve(fields.size());
  547. for (auto field : fields) {
  548. subtypes.push_back(context.GetType(
  549. context.sem_ir().types().GetTypeIdForTypeInstId(field.type_inst_id)));
  550. }
  551. return llvm::StructType::get(context.llvm_context(), subtypes);
  552. }
  553. static auto BuildTypeForInst(FileContext& context, SemIR::TupleType inst)
  554. -> llvm::Type* {
  555. // TODO: Investigate special-casing handling of empty tuples so that they
  556. // can be collectively replaced with LLVM's void, particularly around
  557. // function returns. LLVM doesn't allow declaring variables with a void
  558. // type, so that may require significant special casing.
  559. auto elements = context.sem_ir().inst_blocks().Get(inst.type_elements_id);
  560. llvm::SmallVector<llvm::Type*> subtypes;
  561. subtypes.reserve(elements.size());
  562. for (auto type_id : context.sem_ir().types().GetBlockAsTypeIds(elements)) {
  563. subtypes.push_back(context.GetType(type_id));
  564. }
  565. return llvm::StructType::get(context.llvm_context(), subtypes);
  566. }
  567. static auto BuildTypeForInst(FileContext& context, SemIR::TypeType /*inst*/)
  568. -> llvm::Type* {
  569. return context.GetTypeType();
  570. }
  571. static auto BuildTypeForInst(FileContext& context, SemIR::VtableType /*inst*/)
  572. -> llvm::Type* {
  573. return llvm::Type::getVoidTy(context.llvm_context());
  574. }
  575. template <typename InstT>
  576. requires(InstT::Kind.template IsAnyOf<SemIR::SpecificFunctionType,
  577. SemIR::StringType>())
  578. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  579. -> llvm::Type* {
  580. // TODO: Decide how we want to represent `StringType`.
  581. return llvm::PointerType::get(context.llvm_context(), 0);
  582. }
  583. template <typename InstT>
  584. requires(InstT::Kind
  585. .template IsAnyOf<SemIR::BoundMethodType, SemIR::IntLiteralType,
  586. SemIR::NamespaceType, SemIR::WitnessType>())
  587. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  588. -> llvm::Type* {
  589. // Return an empty struct as a placeholder.
  590. return llvm::StructType::get(context.llvm_context());
  591. }
  592. template <typename InstT>
  593. requires(InstT::Kind.template IsAnyOf<
  594. SemIR::AssociatedEntityType, SemIR::FacetType, SemIR::FunctionType,
  595. SemIR::FunctionTypeWithSelfType, SemIR::GenericClassType,
  596. SemIR::GenericInterfaceType, SemIR::InstType,
  597. SemIR::UnboundElementType, SemIR::WhereExpr>())
  598. static auto BuildTypeForInst(FileContext& context, InstT /*inst*/)
  599. -> llvm::Type* {
  600. // Return an empty struct as a placeholder.
  601. // TODO: Should we model an interface as a witness table, or an associated
  602. // entity as an index?
  603. return llvm::StructType::get(context.llvm_context());
  604. }
  605. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  606. // Use overload resolution to select the implementation, producing compile
  607. // errors when BuildTypeForInst isn't defined for a given instruction.
  608. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  609. #define CARBON_SEM_IR_INST_KIND(Name) \
  610. case CARBON_KIND(SemIR::Name inst): { \
  611. return BuildTypeForInst(*this, inst); \
  612. }
  613. #include "toolchain/sem_ir/inst_kind.def"
  614. }
  615. }
  616. auto FileContext::BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  617. -> llvm::GlobalVariable* {
  618. // TODO: Mangle name.
  619. auto mangled_name =
  620. *sem_ir().names().GetAsStringIfIdentifier(var_storage.pretty_name_id);
  621. auto* type = GetType(var_storage.type_id);
  622. return new llvm::GlobalVariable(
  623. llvm_module(), type,
  624. /*isConstant=*/false, llvm::GlobalVariable::InternalLinkage,
  625. llvm::Constant::getNullValue(type), mangled_name);
  626. }
  627. auto FileContext::GetLocForDI(SemIR::InstId inst_id) -> LocForDI {
  628. SemIR::AbsoluteNodeId resolved =
  629. GetAbsoluteNodeId(sem_ir_, SemIR::LocId(inst_id)).back();
  630. const auto& tree_and_subtrees =
  631. (*tree_and_subtrees_getters_for_debug_info_)[resolved.check_ir_id
  632. .index]();
  633. const auto& tokens = tree_and_subtrees.tree().tokens();
  634. if (resolved.node_id.has_value()) {
  635. auto token = tree_and_subtrees.GetSubtreeTokenRange(resolved.node_id).begin;
  636. return {.filename = tokens.source().filename(),
  637. .line_number = tokens.GetLineNumber(token),
  638. .column_number = tokens.GetColumnNumber(token)};
  639. } else {
  640. return {.filename = tokens.source().filename(),
  641. .line_number = 0,
  642. .column_number = 0};
  643. }
  644. }
  645. auto FileContext::BuildVtable(const SemIR::Class& class_info)
  646. -> llvm::GlobalVariable* {
  647. // Bail out if this class is not dynamic (this will account for classes that
  648. // are declared-and-not-defined (including extern declarations) as well).
  649. if (!class_info.is_dynamic) {
  650. return nullptr;
  651. }
  652. // Vtables can't be generated for generics, only for their specifics - and
  653. // must be done lazily based on the use of those specifics.
  654. if (class_info.generic_id != SemIR::GenericId::None) {
  655. return nullptr;
  656. }
  657. Mangler m(*this);
  658. std::string mangled_name = m.MangleVTable(class_info);
  659. auto first_owning_decl_loc =
  660. sem_ir().insts().GetCanonicalLocId(class_info.first_owning_decl_id);
  661. if (first_owning_decl_loc.kind() == SemIR::LocId::Kind::ImportIRInstId) {
  662. // Emit a declaration of an imported vtable using a(n opaque) pointer type.
  663. // This doesn't have to match the definition that appears elsewhere, it'll
  664. // still get merged correctly.
  665. auto* gv = new llvm::GlobalVariable(
  666. llvm_module(),
  667. llvm::PointerType::get(llvm_context(), /*AddressSpace=*/0),
  668. /*isConstant=*/true, llvm::GlobalValue::ExternalLinkage, nullptr,
  669. mangled_name);
  670. gv->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  671. return gv;
  672. }
  673. auto canonical_vtable_id =
  674. sem_ir().constant_values().GetConstantInstId(class_info.vtable_id);
  675. auto vtable_inst_block =
  676. sem_ir().inst_blocks().Get(sem_ir()
  677. .insts()
  678. .GetAs<SemIR::Vtable>(canonical_vtable_id)
  679. .virtual_functions_id);
  680. auto* entry_type = llvm::IntegerType::getInt32Ty(llvm_context());
  681. auto* table_type = llvm::ArrayType::get(entry_type, vtable_inst_block.size());
  682. auto* llvm_vtable = new llvm::GlobalVariable(
  683. llvm_module(), table_type, /*isConstant=*/true,
  684. llvm::GlobalValue::ExternalLinkage, nullptr, mangled_name);
  685. auto* i32_type = llvm::IntegerType::getInt32Ty(llvm_context());
  686. auto* i64_type = llvm::IntegerType::getInt64Ty(llvm_context());
  687. auto* vtable_const_int =
  688. llvm::ConstantExpr::getPtrToInt(llvm_vtable, i64_type);
  689. llvm::SmallVector<llvm::Constant*> vfuncs;
  690. vfuncs.reserve(vtable_inst_block.size());
  691. for (auto fn_decl_id : vtable_inst_block) {
  692. auto fn_decl = GetCalleeFunction(sem_ir(), fn_decl_id);
  693. vfuncs.push_back(llvm::ConstantExpr::getTrunc(
  694. llvm::ConstantExpr::getSub(
  695. llvm::ConstantExpr::getPtrToInt(
  696. GetOrCreateFunction(fn_decl.function_id,
  697. SemIR::SpecificId::None),
  698. i64_type),
  699. vtable_const_int),
  700. i32_type));
  701. }
  702. llvm_vtable->setInitializer(llvm::ConstantArray::get(table_type, vfuncs));
  703. llvm_vtable->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
  704. return llvm_vtable;
  705. }
  706. } // namespace Carbon::Lower