file_context.cpp 25 KB

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