file_context.cpp 25 KB

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