lowering_context.cpp 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  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 [param_name_id, _] =
  67. semantics_ir().GetNode(param_refs[i]).GetAsBindName();
  68. llvm_function->getArg(i)->setName(semantics_ir().GetString(param_name_id));
  69. }
  70. return llvm_function;
  71. }
  72. auto LoweringContext::BuildFunctionDefinition(SemanticsFunctionId function_id)
  73. -> void {
  74. auto function = semantics_ir().GetFunction(function_id);
  75. const auto& body_block_ids = function.body_block_ids;
  76. if (body_block_ids.empty()) {
  77. // Function is probably defined in another file; not an error.
  78. return;
  79. }
  80. llvm::Function* llvm_function = GetFunction(function_id);
  81. LoweringFunctionContext function_lowering(*this, llvm_function);
  82. // Add parameters to locals.
  83. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  84. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  85. auto param_storage =
  86. semantics_ir().GetNode(param_refs[i]).GetAsBindName().second;
  87. function_lowering.SetLocal(param_storage, llvm_function->getArg(i));
  88. }
  89. // Lower all blocks.
  90. // TODO: Determine the set of reachable blocks, and only lower those ones.
  91. for (auto block_id : body_block_ids) {
  92. CARBON_VLOG() << "Lowering " << block_id << "\n";
  93. auto* llvm_block = function_lowering.GetBlock(block_id);
  94. // Keep the LLVM blocks in lexical order.
  95. llvm_block->moveBefore(llvm_function->end());
  96. function_lowering.builder().SetInsertPoint(llvm_block);
  97. for (const auto& node_id : semantics_ir().GetNodeBlock(block_id)) {
  98. auto node = semantics_ir().GetNode(node_id);
  99. CARBON_VLOG() << "Lowering " << node_id << ": " << node << "\n";
  100. switch (node.kind()) {
  101. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  102. case SemanticsNodeKind::Name: \
  103. LoweringHandle##Name(function_lowering, node_id, node); \
  104. break;
  105. #include "toolchain/semantics/semantics_node_kind.def"
  106. }
  107. }
  108. }
  109. }
  110. auto LoweringContext::BuildType(SemanticsNodeId node_id) -> llvm::Type* {
  111. switch (node_id.index) {
  112. case SemanticsBuiltinKind::FloatingPointType.AsInt():
  113. // TODO: Handle different sizes.
  114. return llvm::Type::getDoubleTy(*llvm_context_);
  115. case SemanticsBuiltinKind::IntegerType.AsInt():
  116. // TODO: Handle different sizes.
  117. return llvm::Type::getInt32Ty(*llvm_context_);
  118. case SemanticsBuiltinKind::BoolType.AsInt():
  119. // TODO: We may want to have different representations for `bool` storage
  120. // (`i8`) versus for `bool` values (`i1`).
  121. return llvm::Type::getInt1Ty(*llvm_context_);
  122. }
  123. auto node = semantics_ir_->GetNode(node_id);
  124. switch (node.kind()) {
  125. case SemanticsNodeKind::StructType: {
  126. auto refs = semantics_ir_->GetNodeBlock(node.GetAsStructType());
  127. llvm::SmallVector<llvm::Type*> subtypes;
  128. subtypes.reserve(refs.size());
  129. for (auto ref_id : refs) {
  130. auto [field_name_id, field_type_id] =
  131. semantics_ir_->GetNode(ref_id).GetAsStructTypeField();
  132. // TODO: Handle recursive types. The restriction for builtins prevents
  133. // recursion while still letting them cache.
  134. CARBON_CHECK(field_type_id.index < SemanticsBuiltinKind::ValidCount)
  135. << field_type_id;
  136. subtypes.push_back(GetType(field_type_id));
  137. }
  138. return llvm::StructType::create(*llvm_context_, subtypes,
  139. "StructLiteralType");
  140. }
  141. case SemanticsNodeKind::TupleType: {
  142. // TODO: Investigate special-casing handling of empty tuples so that they
  143. // can be collectively replaced with LLVM's void, particularly around
  144. // function returns. LLVM doesn't allow declaring variables with a void
  145. // type, so that may require significant special casing.
  146. auto refs = semantics_ir_->GetTypeBlock(node.GetAsTupleType());
  147. llvm::SmallVector<llvm::Type*> subtypes;
  148. subtypes.reserve(refs.size());
  149. for (auto ref_id : refs) {
  150. subtypes.push_back(GetType(ref_id));
  151. }
  152. return llvm::StructType::create(*llvm_context_, subtypes,
  153. "TupleLiteralType");
  154. }
  155. default: {
  156. CARBON_FATAL() << "Cannot use node as type: " << node_id;
  157. }
  158. }
  159. }
  160. } // namespace Carbon