file_context.cpp 28 KB

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