file_context.cpp 30 KB

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