file_context.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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/node_kind.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().Get(type_id).inst_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] = BuildFunctionDeclaration(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::BuildFunctionDeclaration(SemIR::FunctionId function_id)
  48. -> llvm::Function* {
  49. const auto& function = sem_ir().functions().Get(function_id);
  50. const bool has_return_slot = function.return_slot_id.is_valid();
  51. auto implicit_param_refs =
  52. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  53. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  54. SemIR::InitializingRepresentation return_rep =
  55. function.return_type_id.is_valid()
  56. ? SemIR::GetInitializingRepresentation(sem_ir(),
  57. function.return_type_id)
  58. : SemIR::InitializingRepresentation{
  59. .kind = SemIR::InitializingRepresentation::None};
  60. CARBON_CHECK(return_rep.has_return_slot() == has_return_slot);
  61. llvm::SmallVector<llvm::Type*> param_types;
  62. // TODO: Consider either storing `param_inst_ids` somewhere so that we can
  63. // reuse it from `BuildFunctionDefinition` and when building calls, or factor
  64. // out a mechanism to compute the mapping between parameters and arguments on
  65. // demand.
  66. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  67. auto max_llvm_params =
  68. has_return_slot + implicit_param_refs.size() + param_refs.size();
  69. param_types.reserve(max_llvm_params);
  70. param_inst_ids.reserve(max_llvm_params);
  71. if (has_return_slot) {
  72. param_types.push_back(GetType(function.return_type_id)->getPointerTo());
  73. param_inst_ids.push_back(function.return_slot_id);
  74. }
  75. for (auto param_ref_id :
  76. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  77. auto param_type_id = sem_ir().insts().Get(param_ref_id).type_id();
  78. switch (auto value_rep =
  79. SemIR::GetValueRepresentation(sem_ir(), param_type_id);
  80. value_rep.kind) {
  81. case SemIR::ValueRepresentation::Unknown:
  82. CARBON_FATAL()
  83. << "Incomplete parameter type lowering function declaration";
  84. case SemIR::ValueRepresentation::None:
  85. break;
  86. case SemIR::ValueRepresentation::Copy:
  87. case SemIR::ValueRepresentation::Custom:
  88. case SemIR::ValueRepresentation::Pointer:
  89. param_types.push_back(GetType(value_rep.type_id));
  90. param_inst_ids.push_back(param_ref_id);
  91. break;
  92. }
  93. }
  94. // If the initializing representation doesn't produce a value, set the return
  95. // type to void.
  96. llvm::Type* return_type =
  97. return_rep.kind == SemIR::InitializingRepresentation::ByCopy
  98. ? GetType(function.return_type_id)
  99. : llvm::Type::getVoidTy(llvm_context());
  100. std::string mangled_name;
  101. if (SemIR::IsEntryPoint(sem_ir(), function_id)) {
  102. // TODO: Add an implicit `return 0` if `Run` doesn't return `i32`.
  103. mangled_name = "main";
  104. } else {
  105. // TODO: Decide on a name mangling scheme.
  106. mangled_name = sem_ir().strings().Get(function.name_id);
  107. }
  108. llvm::FunctionType* function_type =
  109. llvm::FunctionType::get(return_type, param_types, /*isVarArg=*/false);
  110. auto* llvm_function =
  111. llvm::Function::Create(function_type, llvm::Function::ExternalLinkage,
  112. mangled_name, llvm_module());
  113. // Set up parameters and the return slot.
  114. for (auto [inst_id, arg] :
  115. llvm::zip_equal(param_inst_ids, llvm_function->args())) {
  116. auto inst = sem_ir().insts().Get(inst_id);
  117. if (inst_id == function.return_slot_id) {
  118. arg.setName("return");
  119. arg.addAttr(llvm::Attribute::getWithStructRetType(
  120. llvm_context(), GetType(function.return_type_id)));
  121. } else if (inst.Is<SemIR::SelfParameter>()) {
  122. arg.setName("self");
  123. } else {
  124. arg.setName(sem_ir().strings().Get(inst.As<SemIR::Parameter>().name_id));
  125. }
  126. }
  127. return llvm_function;
  128. }
  129. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  130. -> void {
  131. const auto& function = sem_ir().functions().Get(function_id);
  132. const auto& body_block_ids = function.body_block_ids;
  133. if (body_block_ids.empty()) {
  134. // Function is probably defined in another file; not an error.
  135. return;
  136. }
  137. llvm::Function* llvm_function = GetFunction(function_id);
  138. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  139. const bool has_return_slot = function.return_slot_id.is_valid();
  140. // Add parameters to locals.
  141. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  142. // function parameters that was already computed in BuildFunctionDeclaration.
  143. // We should only do that once.
  144. auto implicit_param_refs =
  145. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  146. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  147. int param_index = 0;
  148. if (has_return_slot) {
  149. function_lowering.SetLocal(function.return_slot_id,
  150. llvm_function->getArg(param_index));
  151. ++param_index;
  152. }
  153. for (auto param_ref_id :
  154. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  155. auto param_type_id = sem_ir().insts().Get(param_ref_id).type_id();
  156. if (SemIR::GetValueRepresentation(sem_ir(), param_type_id).kind ==
  157. SemIR::ValueRepresentation::None) {
  158. function_lowering.SetLocal(
  159. param_ref_id, llvm::PoisonValue::get(GetType(param_type_id)));
  160. } else {
  161. function_lowering.SetLocal(param_ref_id,
  162. llvm_function->getArg(param_index));
  163. ++param_index;
  164. }
  165. }
  166. // Lower all blocks.
  167. for (auto block_id : body_block_ids) {
  168. CARBON_VLOG() << "Lowering " << block_id << "\n";
  169. auto* llvm_block = function_lowering.GetBlock(block_id);
  170. // Keep the LLVM blocks in lexical order.
  171. llvm_block->moveBefore(llvm_function->end());
  172. function_lowering.builder().SetInsertPoint(llvm_block);
  173. function_lowering.LowerBlock(block_id);
  174. }
  175. // LLVM requires that the entry block has no predecessors.
  176. auto* entry_block = &llvm_function->getEntryBlock();
  177. if (entry_block->hasNPredecessorsOrMore(1)) {
  178. auto* new_entry_block = llvm::BasicBlock::Create(
  179. llvm_context(), "entry", llvm_function, entry_block);
  180. llvm::BranchInst::Create(entry_block, new_entry_block);
  181. }
  182. }
  183. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  184. switch (inst_id.index) {
  185. case SemIR::BuiltinKind::FloatingPointType.AsInt():
  186. // TODO: Handle different sizes.
  187. return llvm::Type::getDoubleTy(*llvm_context_);
  188. case SemIR::BuiltinKind::IntegerType.AsInt():
  189. // TODO: Handle different sizes.
  190. return llvm::Type::getInt32Ty(*llvm_context_);
  191. case SemIR::BuiltinKind::BoolType.AsInt():
  192. // TODO: We may want to have different representations for `bool` storage
  193. // (`i8`) versus for `bool` values (`i1`).
  194. return llvm::Type::getInt1Ty(*llvm_context_);
  195. case SemIR::BuiltinKind::FunctionType.AsInt():
  196. case SemIR::BuiltinKind::BoundMethodType.AsInt():
  197. case SemIR::BuiltinKind::NamespaceType.AsInt():
  198. // Return an empty struct as a placeholder.
  199. return llvm::StructType::get(*llvm_context_);
  200. default:
  201. // Handled below.
  202. break;
  203. }
  204. auto inst = sem_ir_->insts().Get(inst_id);
  205. switch (inst.kind()) {
  206. case SemIR::ArrayType::Kind: {
  207. auto array_type = inst.As<SemIR::ArrayType>();
  208. return llvm::ArrayType::get(
  209. GetType(array_type.element_type_id),
  210. sem_ir_->GetArrayBoundValue(array_type.bound_id));
  211. }
  212. case SemIR::ClassType::Kind: {
  213. auto object_representation_id =
  214. sem_ir_->classes()
  215. .Get(inst.As<SemIR::ClassType>().class_id)
  216. .object_representation_id;
  217. return GetType(object_representation_id);
  218. }
  219. case SemIR::ConstType::Kind:
  220. return GetType(inst.As<SemIR::ConstType>().inner_id);
  221. case SemIR::PointerType::Kind:
  222. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  223. case SemIR::StructType::Kind: {
  224. auto fields =
  225. sem_ir_->inst_blocks().Get(inst.As<SemIR::StructType>().fields_id);
  226. llvm::SmallVector<llvm::Type*> subtypes;
  227. subtypes.reserve(fields.size());
  228. for (auto field_id : fields) {
  229. auto field = sem_ir_->insts().GetAs<SemIR::StructTypeField>(field_id);
  230. // TODO: Handle recursive types. The restriction for builtins prevents
  231. // recursion while still letting them cache.
  232. CARBON_CHECK(field.field_type_id.index < SemIR::BuiltinKind::ValidCount)
  233. << field.field_type_id;
  234. subtypes.push_back(GetType(field.field_type_id));
  235. }
  236. return llvm::StructType::get(*llvm_context_, subtypes);
  237. }
  238. case SemIR::TupleType::Kind: {
  239. // TODO: Investigate special-casing handling of empty tuples so that they
  240. // can be collectively replaced with LLVM's void, particularly around
  241. // function returns. LLVM doesn't allow declaring variables with a void
  242. // type, so that may require significant special casing.
  243. auto elements =
  244. sem_ir_->type_blocks().Get(inst.As<SemIR::TupleType>().elements_id);
  245. llvm::SmallVector<llvm::Type*> subtypes;
  246. subtypes.reserve(elements.size());
  247. for (auto element_id : elements) {
  248. subtypes.push_back(GetType(element_id));
  249. }
  250. return llvm::StructType::get(*llvm_context_, subtypes);
  251. }
  252. case SemIR::UnboundFieldType::Kind: {
  253. // Return an empty struct as a placeholder.
  254. return llvm::StructType::get(*llvm_context_);
  255. }
  256. default: {
  257. CARBON_FATAL() << "Cannot use inst as type: " << inst_id << " " << inst;
  258. }
  259. }
  260. }
  261. } // namespace Carbon::Lower