file_context.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 "toolchain/base/kind_switch.h"
  9. #include "toolchain/lower/constant.h"
  10. #include "toolchain/lower/function_context.h"
  11. #include "toolchain/sem_ir/entry_point.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/function.h"
  14. #include "toolchain/sem_ir/inst.h"
  15. #include "toolchain/sem_ir/typed_insts.h"
  16. namespace Carbon::Lower {
  17. FileContext::FileContext(llvm::LLVMContext& llvm_context,
  18. llvm::StringRef module_name, const SemIR::File& sem_ir,
  19. const SemIR::InstNamer* inst_namer,
  20. llvm::raw_ostream* vlog_stream)
  21. : llvm_context_(&llvm_context),
  22. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  23. sem_ir_(&sem_ir),
  24. inst_namer_(inst_namer),
  25. vlog_stream_(vlog_stream) {
  26. CARBON_CHECK(!sem_ir.has_errors())
  27. << "Generating LLVM IR from invalid SemIR::File is unsupported.";
  28. }
  29. // TODO: Move this to lower.cpp.
  30. auto FileContext::Run() -> std::unique_ptr<llvm::Module> {
  31. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  32. // Lower all types that were required to be complete. Note that this may
  33. // leave some entries in `types_` null, if those types were mentioned but not
  34. // used.
  35. types_.resize(sem_ir_->types().size());
  36. for (auto type_id : sem_ir_->complete_types()) {
  37. types_[type_id.index] = BuildType(sem_ir_->types().GetInstId(type_id));
  38. }
  39. // Lower function declarations.
  40. functions_.resize_for_overwrite(sem_ir_->functions().size());
  41. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  42. functions_[i] = BuildFunctionDecl(SemIR::FunctionId(i));
  43. }
  44. // TODO: Lower global variable declarations.
  45. // Lower constants.
  46. constants_.resize(sem_ir_->insts().size());
  47. LowerConstants(*this, constants_);
  48. // Lower function definitions.
  49. for (auto i : llvm::seq(sem_ir_->functions().size())) {
  50. BuildFunctionDefinition(SemIR::FunctionId(i));
  51. }
  52. // TODO: Lower global variable initializers.
  53. return std::move(llvm_module_);
  54. }
  55. auto FileContext::GetGlobal(SemIR::InstId inst_id) -> llvm::Value* {
  56. auto inst = sem_ir().insts().Get(inst_id);
  57. auto const_id = sem_ir().constant_values().Get(inst_id);
  58. if (const_id.is_template()) {
  59. // For value expressions and initializing expressions, the value produced by
  60. // a constant instruction is a value representation of the constant. For
  61. // initializing expressions, `FinishInit` will perform a copy if needed.
  62. // TODO: Handle reference expression constants.
  63. auto* const_value = constants_[const_id.inst_id().index];
  64. // If we want a pointer to the constant, materialize a global to hold it.
  65. // TODO: We could reuse the same global if the constant is used more than
  66. // once.
  67. auto value_rep = SemIR::GetValueRepr(sem_ir(), inst.type_id());
  68. if (value_rep.kind == SemIR::ValueRepr::Pointer) {
  69. llvm::StringRef name =
  70. inst_namer_ ? inst_namer_->GetUnscopedNameFor(inst_id) : "";
  71. llvm::StringRef sep = (name.empty() || name[0] == '.') ? "" : ".";
  72. return new llvm::GlobalVariable(
  73. llvm_module(), GetType(sem_ir().GetPointeeType(value_rep.type_id)),
  74. /*isConstant=*/true, llvm::GlobalVariable::InternalLinkage,
  75. const_value, "const" + sep + name);
  76. }
  77. // Otherwise, we can use the constant value directly.
  78. return const_value;
  79. }
  80. // TODO: For generics, handle references to symbolic constants.
  81. CARBON_FATAL() << "Missing value: " << inst_id << " "
  82. << sem_ir().insts().Get(inst_id);
  83. }
  84. auto FileContext::BuildFunctionDecl(SemIR::FunctionId function_id)
  85. -> llvm::Function* {
  86. const auto& function = sem_ir().functions().Get(function_id);
  87. // Don't lower associated functions.
  88. // TODO: We shouldn't lower any function that has generic parameters.
  89. if (sem_ir().insts().Is<SemIR::InterfaceDecl>(
  90. sem_ir().name_scopes().Get(function.enclosing_scope_id).inst_id)) {
  91. return nullptr;
  92. }
  93. // Don't lower builtins.
  94. if (function.builtin_kind != SemIR::BuiltinFunctionKind::None) {
  95. return nullptr;
  96. }
  97. // Don't lower unused functions.
  98. if (function.return_slot == SemIR::Function::ReturnSlot::NotComputed) {
  99. return nullptr;
  100. }
  101. const bool has_return_slot = function.has_return_slot();
  102. auto implicit_param_refs =
  103. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  104. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  105. SemIR::InitRepr return_rep =
  106. function.return_type_id.is_valid()
  107. ? SemIR::GetInitRepr(sem_ir(), function.return_type_id)
  108. : SemIR::InitRepr{.kind = SemIR::InitRepr::None};
  109. CARBON_CHECK(return_rep.has_return_slot() == has_return_slot);
  110. llvm::SmallVector<llvm::Type*> param_types;
  111. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  112. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  113. // out a mechanism to compute the mapping between parameters and arguments on
  114. // demand.
  115. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  116. auto max_llvm_params =
  117. has_return_slot + implicit_param_refs.size() + param_refs.size();
  118. param_types.reserve(max_llvm_params);
  119. param_inst_ids.reserve(max_llvm_params);
  120. if (has_return_slot) {
  121. param_types.push_back(GetType(function.return_type_id)->getPointerTo());
  122. param_inst_ids.push_back(function.return_storage_id);
  123. }
  124. for (auto param_ref_id :
  125. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  126. auto param_type_id =
  127. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id)
  128. .second.type_id;
  129. switch (auto value_rep = SemIR::GetValueRepr(sem_ir(), param_type_id);
  130. value_rep.kind) {
  131. case SemIR::ValueRepr::Unknown:
  132. CARBON_FATAL()
  133. << "Incomplete parameter type lowering function declaration";
  134. case SemIR::ValueRepr::None:
  135. break;
  136. case SemIR::ValueRepr::Copy:
  137. case SemIR::ValueRepr::Custom:
  138. case SemIR::ValueRepr::Pointer:
  139. param_types.push_back(GetType(value_rep.type_id));
  140. param_inst_ids.push_back(param_ref_id);
  141. break;
  142. }
  143. }
  144. // If the initializing representation doesn't produce a value, set the return
  145. // type to void.
  146. llvm::Type* return_type = return_rep.kind == SemIR::InitRepr::ByCopy
  147. ? GetType(function.return_type_id)
  148. : llvm::Type::getVoidTy(llvm_context());
  149. std::string mangled_name;
  150. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  151. // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`.
  152. mangled_name = "main";
  153. } else if (auto name =
  154. sem_ir().names().GetAsStringIfIdentifier(function.name_id)) {
  155. // TODO: Decide on a name mangling scheme.
  156. mangled_name = *name;
  157. } else {
  158. CARBON_FATAL() << "Unexpected special name for function: "
  159. << function.name_id;
  160. }
  161. llvm::FunctionType* function_type =
  162. llvm::FunctionType::get(return_type, param_types, /*isVarArg=*/false);
  163. auto* llvm_function =
  164. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  165. mangled_name, llvm_module());
  166. // Set up parameters and the return slot.
  167. for (auto [inst_id, arg] :
  168. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  169. auto name_id = SemIR::NameId::Invalid;
  170. if (inst_id == function.return_storage_id) {
  171. name_id = SemIR::NameId::ReturnSlot;
  172. arg.addAttr(llvm::Attribute::getWithStructRetType(
  173. llvm_context(), GetType(function.return_type_id)));
  174. } else {
  175. name_id = SemIR::Function::GetParamFromParamRefId(sem_ir(), inst_id)
  176. .second.name_id;
  177. }
  178. arg.setName(sem_ir().names().GetIRBaseName(name_id));
  179. }
  180. return llvm_function;
  181. }
  182. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  183. -> void {
  184. const auto& function = sem_ir().functions().Get(function_id);
  185. const auto& body_block_ids = function.body_block_ids;
  186. if (body_block_ids.empty()) {
  187. // Function is probably defined in another file; not an error.
  188. return;
  189. }
  190. llvm::Function* llvm_function = GetFunction(function_id);
  191. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  192. const bool has_return_slot = function.has_return_slot();
  193. // Add parameters to locals.
  194. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  195. // function parameters that was already computed in BuildFunctionDecl.
  196. // We should only do that once.
  197. auto implicit_param_refs =
  198. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  199. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  200. int param_index = 0;
  201. if (has_return_slot) {
  202. function_lowering.SetLocal(function.return_storage_id,
  203. llvm_function->getArg(param_index));
  204. ++param_index;
  205. }
  206. for (auto param_ref_id :
  207. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  208. auto [param_id, param] =
  209. SemIR::Function::GetParamFromParamRefId(sem_ir(), param_ref_id);
  210. // Get the value of the parameter from the function argument.
  211. auto param_type_id = param.type_id;
  212. llvm::Value* param_value = llvm::PoisonValue::get(GetType(param_type_id));
  213. if (SemIR::GetValueRepr(sem_ir(), param_type_id).kind !=
  214. SemIR::ValueRepr::None) {
  215. param_value = llvm_function->getArg(param_index);
  216. ++param_index;
  217. }
  218. // The value of the parameter is the value of the argument.
  219. function_lowering.SetLocal(param_id, param_value);
  220. // Match the portion of the pattern corresponding to the parameter against
  221. // the parameter value. For now this is always a single name binding,
  222. // possibly wrapped in `addr`.
  223. //
  224. // TODO: Support general patterns here.
  225. auto bind_name_id = param_ref_id;
  226. if (auto addr =
  227. sem_ir().insts().TryGetAs<SemIR::AddrPattern>(param_ref_id)) {
  228. bind_name_id = addr->inner_id;
  229. }
  230. auto bind_name = sem_ir().insts().Get(bind_name_id);
  231. // TODO: Should we stop passing compile-time bindings at runtime?
  232. CARBON_CHECK(bind_name.Is<SemIR::AnyBindName>());
  233. function_lowering.SetLocal(bind_name_id, param_value);
  234. }
  235. // Lower all blocks.
  236. for (auto block_id : body_block_ids) {
  237. CARBON_VLOG() << "Lowering " << block_id << "\n";
  238. auto* llvm_block = function_lowering.GetBlock(block_id);
  239. // Keep the LLVM blocks in lexical order.
  240. llvm_block->moveBefore(llvm_function->end());
  241. function_lowering.builder().SetInsertPoint(llvm_block);
  242. function_lowering.LowerBlock(block_id);
  243. }
  244. // LLVM requires that the entry block has no predecessors.
  245. auto* entry_block = &llvm_function->getEntryBlock();
  246. if (entry_block->hasNPredecessorsOrMore(1)) {
  247. auto* new_entry_block = llvm::BasicBlock::Create(
  248. llvm_context(), "entry", llvm_function, entry_block);
  249. llvm::BranchInst::Create(entry_block, new_entry_block);
  250. }
  251. }
  252. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  253. CARBON_KIND_SWITCH(sem_ir_->insts().Get(inst_id)) {
  254. case CARBON_KIND(SemIR::ArrayType inst): {
  255. return llvm::ArrayType::get(GetType(inst.element_type_id),
  256. sem_ir_->GetArrayBoundValue(inst.bound_id));
  257. }
  258. case CARBON_KIND(SemIR::Builtin inst): {
  259. switch (inst.builtin_kind) {
  260. case SemIR::BuiltinKind::Invalid:
  261. case SemIR::BuiltinKind::Error:
  262. CARBON_FATAL() << "Unexpected builtin type in lowering.";
  263. case SemIR::BuiltinKind::TypeType:
  264. return GetTypeType();
  265. case SemIR::BuiltinKind::FloatType:
  266. return llvm::Type::getDoubleTy(*llvm_context_);
  267. case SemIR::BuiltinKind::IntType:
  268. return llvm::Type::getInt32Ty(*llvm_context_);
  269. case SemIR::BuiltinKind::BoolType:
  270. // TODO: We may want to have different representations for `bool`
  271. // storage
  272. // (`i8`) versus for `bool` values (`i1`).
  273. return llvm::Type::getInt1Ty(*llvm_context_);
  274. case SemIR::BuiltinKind::StringType:
  275. // TODO: Decide how we want to represent `StringType`.
  276. return llvm::PointerType::get(*llvm_context_, 0);
  277. case SemIR::BuiltinKind::BoundMethodType:
  278. case SemIR::BuiltinKind::FunctionType:
  279. case SemIR::BuiltinKind::NamespaceType:
  280. case SemIR::BuiltinKind::WitnessType:
  281. // Return an empty struct as a placeholder.
  282. return llvm::StructType::get(*llvm_context_);
  283. }
  284. }
  285. case CARBON_KIND(SemIR::ClassType inst): {
  286. auto object_repr_id =
  287. sem_ir_->classes().Get(inst.class_id).object_repr_id;
  288. return GetType(object_repr_id);
  289. }
  290. case CARBON_KIND(SemIR::ConstType inst): {
  291. return GetType(inst.inner_id);
  292. }
  293. case SemIR::FloatType::Kind: {
  294. // TODO: Handle different sizes.
  295. return llvm::Type::getDoubleTy(*llvm_context_);
  296. }
  297. case CARBON_KIND(SemIR::IntType inst): {
  298. auto width =
  299. sem_ir_->insts().TryGetAs<SemIR::IntLiteral>(inst.bit_width_id);
  300. CARBON_CHECK(width) << "Can't lower int type with symbolic width";
  301. return llvm::IntegerType::get(
  302. *llvm_context_, sem_ir_->ints().Get(width->int_id).getZExtValue());
  303. }
  304. case SemIR::PointerType::Kind: {
  305. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  306. }
  307. case CARBON_KIND(SemIR::StructType inst): {
  308. auto fields = sem_ir_->inst_blocks().Get(inst.fields_id);
  309. llvm::SmallVector<llvm::Type*> subtypes;
  310. subtypes.reserve(fields.size());
  311. for (auto field_id : fields) {
  312. auto field = sem_ir_->insts().GetAs<SemIR::StructTypeField>(field_id);
  313. subtypes.push_back(GetType(field.field_type_id));
  314. }
  315. return llvm::StructType::get(*llvm_context_, subtypes);
  316. }
  317. case CARBON_KIND(SemIR::TupleType inst): {
  318. // TODO: Investigate special-casing handling of empty tuples so that they
  319. // can be collectively replaced with LLVM's void, particularly around
  320. // function returns. LLVM doesn't allow declaring variables with a void
  321. // type, so that may require significant special casing.
  322. auto elements = sem_ir_->type_blocks().Get(inst.elements_id);
  323. llvm::SmallVector<llvm::Type*> subtypes;
  324. subtypes.reserve(elements.size());
  325. for (auto element_id : elements) {
  326. subtypes.push_back(GetType(element_id));
  327. }
  328. return llvm::StructType::get(*llvm_context_, subtypes);
  329. }
  330. case SemIR::AssociatedEntityType::Kind:
  331. case SemIR::InterfaceType::Kind:
  332. case SemIR::UnboundElementType::Kind: {
  333. // Return an empty struct as a placeholder.
  334. // TODO: Should we model an interface as a witness table, or an associated
  335. // entity as an index?
  336. return llvm::StructType::get(*llvm_context_);
  337. }
  338. // Treat non-monomorphized symbolic types as opaque.
  339. case SemIR::BindSymbolicName::Kind:
  340. case SemIR::InterfaceWitnessAccess::Kind: {
  341. return llvm::StructType::get(*llvm_context_);
  342. }
  343. #define CARBON_SEM_IR_INST_KIND_TYPE(...)
  344. #define CARBON_SEM_IR_INST_KIND_MAYBE_TYPE(...)
  345. #define CARBON_SEM_IR_INST_KIND(Name) case SemIR::Name::Kind:
  346. #include "toolchain/sem_ir/inst_kind.def"
  347. CARBON_FATAL() << "Cannot use inst as type: " << inst_id << " "
  348. << sem_ir_->insts().Get(inst_id);
  349. }
  350. }
  351. } // namespace Carbon::Lower