file_context.cpp 14 KB

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