file_context.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  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/inst_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().identifiers().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(
  125. sem_ir().identifiers().Get(inst.As<SemIR::Parameter>().name_id));
  126. }
  127. }
  128. return llvm_function;
  129. }
  130. auto FileContext::BuildFunctionDefinition(SemIR::FunctionId function_id)
  131. -> void {
  132. const auto& function = sem_ir().functions().Get(function_id);
  133. const auto& body_block_ids = function.body_block_ids;
  134. if (body_block_ids.empty()) {
  135. // Function is probably defined in another file; not an error.
  136. return;
  137. }
  138. llvm::Function* llvm_function = GetFunction(function_id);
  139. FunctionContext function_lowering(*this, llvm_function, vlog_stream_);
  140. const bool has_return_slot = function.return_slot_id.is_valid();
  141. // Add parameters to locals.
  142. // TODO: This duplicates the mapping between sem_ir instructions and LLVM
  143. // function parameters that was already computed in BuildFunctionDeclaration.
  144. // We should only do that once.
  145. auto implicit_param_refs =
  146. sem_ir().inst_blocks().Get(function.implicit_param_refs_id);
  147. auto param_refs = sem_ir().inst_blocks().Get(function.param_refs_id);
  148. int param_index = 0;
  149. if (has_return_slot) {
  150. function_lowering.SetLocal(function.return_slot_id,
  151. llvm_function->getArg(param_index));
  152. ++param_index;
  153. }
  154. for (auto param_ref_id :
  155. llvm::concat<const SemIR::InstId>(implicit_param_refs, param_refs)) {
  156. auto param_type_id = sem_ir().insts().Get(param_ref_id).type_id();
  157. if (SemIR::GetValueRepresentation(sem_ir(), param_type_id).kind ==
  158. SemIR::ValueRepresentation::None) {
  159. function_lowering.SetLocal(
  160. param_ref_id, llvm::PoisonValue::get(GetType(param_type_id)));
  161. } else {
  162. function_lowering.SetLocal(param_ref_id,
  163. llvm_function->getArg(param_index));
  164. ++param_index;
  165. }
  166. }
  167. // Lower all blocks.
  168. for (auto block_id : body_block_ids) {
  169. CARBON_VLOG() << "Lowering " << block_id << "\n";
  170. auto* llvm_block = function_lowering.GetBlock(block_id);
  171. // Keep the LLVM blocks in lexical order.
  172. llvm_block->moveBefore(llvm_function->end());
  173. function_lowering.builder().SetInsertPoint(llvm_block);
  174. function_lowering.LowerBlock(block_id);
  175. }
  176. // LLVM requires that the entry block has no predecessors.
  177. auto* entry_block = &llvm_function->getEntryBlock();
  178. if (entry_block->hasNPredecessorsOrMore(1)) {
  179. auto* new_entry_block = llvm::BasicBlock::Create(
  180. llvm_context(), "entry", llvm_function, entry_block);
  181. llvm::BranchInst::Create(entry_block, new_entry_block);
  182. }
  183. }
  184. auto FileContext::BuildType(SemIR::InstId inst_id) -> llvm::Type* {
  185. switch (inst_id.index) {
  186. case SemIR::BuiltinKind::FloatingPointType.AsInt():
  187. // TODO: Handle different sizes.
  188. return llvm::Type::getDoubleTy(*llvm_context_);
  189. case SemIR::BuiltinKind::IntegerType.AsInt():
  190. // TODO: Handle different sizes.
  191. return llvm::Type::getInt32Ty(*llvm_context_);
  192. case SemIR::BuiltinKind::BoolType.AsInt():
  193. // TODO: We may want to have different representations for `bool` storage
  194. // (`i8`) versus for `bool` values (`i1`).
  195. return llvm::Type::getInt1Ty(*llvm_context_);
  196. case SemIR::BuiltinKind::FunctionType.AsInt():
  197. case SemIR::BuiltinKind::BoundMethodType.AsInt():
  198. case SemIR::BuiltinKind::NamespaceType.AsInt():
  199. // Return an empty struct as a placeholder.
  200. return llvm::StructType::get(*llvm_context_);
  201. default:
  202. // Handled below.
  203. break;
  204. }
  205. auto inst = sem_ir_->insts().Get(inst_id);
  206. switch (inst.kind()) {
  207. case SemIR::ArrayType::Kind: {
  208. auto array_type = inst.As<SemIR::ArrayType>();
  209. return llvm::ArrayType::get(
  210. GetType(array_type.element_type_id),
  211. sem_ir_->GetArrayBoundValue(array_type.bound_id));
  212. }
  213. case SemIR::ClassType::Kind: {
  214. auto object_representation_id =
  215. sem_ir_->classes()
  216. .Get(inst.As<SemIR::ClassType>().class_id)
  217. .object_representation_id;
  218. return GetType(object_representation_id);
  219. }
  220. case SemIR::ConstType::Kind:
  221. return GetType(inst.As<SemIR::ConstType>().inner_id);
  222. case SemIR::PointerType::Kind:
  223. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  224. case SemIR::StructType::Kind: {
  225. auto fields =
  226. sem_ir_->inst_blocks().Get(inst.As<SemIR::StructType>().fields_id);
  227. llvm::SmallVector<llvm::Type*> subtypes;
  228. subtypes.reserve(fields.size());
  229. for (auto field_id : fields) {
  230. auto field = sem_ir_->insts().GetAs<SemIR::StructTypeField>(field_id);
  231. // TODO: Handle recursive types. The restriction for builtins prevents
  232. // recursion while still letting them cache.
  233. CARBON_CHECK(field.field_type_id.index < SemIR::BuiltinKind::ValidCount)
  234. << field.field_type_id;
  235. subtypes.push_back(GetType(field.field_type_id));
  236. }
  237. return llvm::StructType::get(*llvm_context_, subtypes);
  238. }
  239. case SemIR::TupleType::Kind: {
  240. // TODO: Investigate special-casing handling of empty tuples so that they
  241. // can be collectively replaced with LLVM's void, particularly around
  242. // function returns. LLVM doesn't allow declaring variables with a void
  243. // type, so that may require significant special casing.
  244. auto elements =
  245. sem_ir_->type_blocks().Get(inst.As<SemIR::TupleType>().elements_id);
  246. llvm::SmallVector<llvm::Type*> subtypes;
  247. subtypes.reserve(elements.size());
  248. for (auto element_id : elements) {
  249. subtypes.push_back(GetType(element_id));
  250. }
  251. return llvm::StructType::get(*llvm_context_, subtypes);
  252. }
  253. case SemIR::UnboundFieldType::Kind: {
  254. // Return an empty struct as a placeholder.
  255. return llvm::StructType::get(*llvm_context_);
  256. }
  257. default: {
  258. CARBON_FATAL() << "Cannot use inst as type: " << inst_id << " " << inst;
  259. }
  260. }
  261. }
  262. } // namespace Carbon::Lower