lowering_context.cpp 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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/lowering/lowering_context.h"
  5. #include "common/vlog.h"
  6. #include "toolchain/lowering/lowering_function_context.h"
  7. #include "toolchain/semantics/semantics_ir.h"
  8. #include "toolchain/semantics/semantics_node.h"
  9. #include "toolchain/semantics/semantics_node_kind.h"
  10. namespace Carbon {
  11. LoweringContext::LoweringContext(llvm::LLVMContext& llvm_context,
  12. llvm::StringRef module_name,
  13. const SemanticsIR& semantics_ir,
  14. llvm::raw_ostream* vlog_stream)
  15. : llvm_context_(&llvm_context),
  16. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  17. semantics_ir_(&semantics_ir),
  18. vlog_stream_(vlog_stream) {
  19. CARBON_CHECK(!semantics_ir.has_errors())
  20. << "Generating LLVM IR from invalid SemanticsIR is unsupported.";
  21. }
  22. // TODO: Move this to lower_to_llvm.cpp.
  23. auto LoweringContext::Run() -> std::unique_ptr<llvm::Module> {
  24. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  25. // Lower types.
  26. auto types = semantics_ir_->types();
  27. types_.resize_for_overwrite(types.size());
  28. for (int i = 0; i < static_cast<int>(types.size()); ++i) {
  29. types_[i] = BuildType(types[i]);
  30. }
  31. // Lower function declarations.
  32. functions_.resize_for_overwrite(semantics_ir_->functions_size());
  33. for (int i = 0; i < semantics_ir_->functions_size(); ++i) {
  34. functions_[i] = BuildFunctionDeclaration(SemanticsFunctionId(i));
  35. }
  36. // TODO: Lower global variable declarations.
  37. // Lower function definitions.
  38. for (int i = 0; i < semantics_ir_->functions_size(); ++i) {
  39. BuildFunctionDefinition(SemanticsFunctionId(i));
  40. }
  41. // TODO: Lower global variable initializers.
  42. return std::move(llvm_module_);
  43. }
  44. auto LoweringContext::BuildFunctionDeclaration(SemanticsFunctionId function_id)
  45. -> llvm::Function* {
  46. auto function = semantics_ir().GetFunction(function_id);
  47. // TODO: Lower type information for the arguments prior to building args.
  48. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  49. llvm::SmallVector<llvm::Type*> args;
  50. args.resize_for_overwrite(param_refs.size());
  51. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  52. args[i] = GetType(semantics_ir().GetNode(param_refs[i]).type_id());
  53. }
  54. // If return type is not valid, the function does not have a return type.
  55. // Hence, set return type to void.
  56. llvm::Type* return_type = function.return_type_id.is_valid()
  57. ? GetType(function.return_type_id)
  58. : llvm::Type::getVoidTy(llvm_context());
  59. llvm::FunctionType* function_type =
  60. llvm::FunctionType::get(return_type, args, /*isVarArg=*/false);
  61. auto* llvm_function = llvm::Function::Create(
  62. function_type, llvm::Function::ExternalLinkage,
  63. semantics_ir().GetString(function.name_id), llvm_module());
  64. // Set parameter names.
  65. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  66. auto name_id = semantics_ir().GetNode(param_refs[i]).GetAsVarStorage();
  67. llvm_function->getArg(i)->setName(semantics_ir().GetString(name_id));
  68. }
  69. return llvm_function;
  70. }
  71. auto LoweringContext::BuildFunctionDefinition(SemanticsFunctionId function_id)
  72. -> void {
  73. auto function = semantics_ir().GetFunction(function_id);
  74. const auto& body_block_ids = function.body_block_ids;
  75. if (body_block_ids.empty()) {
  76. // Function is probably defined in another file; not an error.
  77. return;
  78. }
  79. llvm::Function* llvm_function = GetFunction(function_id);
  80. LoweringFunctionContext function_lowering(*this, llvm_function);
  81. // Add parameters to locals.
  82. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  83. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  84. function_lowering.SetLocal(param_refs[i], llvm_function->getArg(i));
  85. }
  86. // Lower all blocks.
  87. // TODO: Determine the set of reachable blocks, and only lower those ones.
  88. for (auto block_id : body_block_ids) {
  89. CARBON_VLOG() << "Lowering " << block_id << "\n";
  90. auto* llvm_block = function_lowering.GetBlock(block_id);
  91. // Keep the LLVM blocks in lexical order.
  92. llvm_block->moveBefore(llvm_function->end());
  93. function_lowering.builder().SetInsertPoint(llvm_block);
  94. for (const auto& node_id : semantics_ir().GetNodeBlock(block_id)) {
  95. auto node = semantics_ir().GetNode(node_id);
  96. CARBON_VLOG() << "Lowering " << node_id << ": " << node << "\n";
  97. switch (node.kind()) {
  98. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  99. case SemanticsNodeKind::Name: \
  100. LoweringHandle##Name(function_lowering, node_id, node); \
  101. break;
  102. #include "toolchain/semantics/semantics_node_kind.def"
  103. }
  104. }
  105. }
  106. }
  107. auto LoweringContext::BuildType(SemanticsNodeId node_id) -> llvm::Type* {
  108. switch (node_id.index) {
  109. case SemanticsBuiltinKind::FloatingPointType.AsInt():
  110. // TODO: Handle different sizes.
  111. return llvm::Type::getDoubleTy(*llvm_context_);
  112. case SemanticsBuiltinKind::IntegerType.AsInt():
  113. // TODO: Handle different sizes.
  114. return llvm::Type::getInt32Ty(*llvm_context_);
  115. case SemanticsBuiltinKind::BoolType.AsInt():
  116. // TODO: We may want to have different representations for `bool` storage
  117. // (`i8`) versus for `bool` values (`i1`).
  118. return llvm::Type::getInt1Ty(*llvm_context_);
  119. }
  120. auto node = semantics_ir_->GetNode(node_id);
  121. switch (node.kind()) {
  122. case SemanticsNodeKind::ArrayType: {
  123. auto [bound_node_id, type_id] = node.GetAsArrayType();
  124. return llvm::ArrayType::get(
  125. GetType(type_id), semantics_ir_->GetArrayBoundValue(bound_node_id));
  126. }
  127. case SemanticsNodeKind::ConstType:
  128. return GetType(node.GetAsConstType());
  129. case SemanticsNodeKind::PointerType:
  130. return llvm::PointerType::get(*llvm_context_, /*AddressSpace=*/0);
  131. case SemanticsNodeKind::StructType: {
  132. auto refs = semantics_ir_->GetNodeBlock(node.GetAsStructType());
  133. llvm::SmallVector<llvm::Type*> subtypes;
  134. subtypes.reserve(refs.size());
  135. for (auto ref_id : refs) {
  136. auto [field_name_id, field_type_id] =
  137. semantics_ir_->GetNode(ref_id).GetAsStructTypeField();
  138. // TODO: Handle recursive types. The restriction for builtins prevents
  139. // recursion while still letting them cache.
  140. CARBON_CHECK(field_type_id.index < SemanticsBuiltinKind::ValidCount)
  141. << field_type_id;
  142. subtypes.push_back(GetType(field_type_id));
  143. }
  144. return llvm::StructType::get(*llvm_context_, subtypes);
  145. }
  146. case SemanticsNodeKind::TupleType: {
  147. // TODO: Investigate special-casing handling of empty tuples so that they
  148. // can be collectively replaced with LLVM's void, particularly around
  149. // function returns. LLVM doesn't allow declaring variables with a void
  150. // type, so that may require significant special casing.
  151. auto refs = semantics_ir_->GetTypeBlock(node.GetAsTupleType());
  152. llvm::SmallVector<llvm::Type*> subtypes;
  153. subtypes.reserve(refs.size());
  154. for (auto ref_id : refs) {
  155. subtypes.push_back(GetType(ref_id));
  156. }
  157. return llvm::StructType::get(*llvm_context_, subtypes);
  158. }
  159. default: {
  160. CARBON_FATAL() << "Cannot use node as type: " << node_id;
  161. }
  162. }
  163. }
  164. } // namespace Carbon