lowering_context.cpp 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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_kind.h"
  9. namespace Carbon {
  10. LoweringContext::LoweringContext(llvm::LLVMContext& llvm_context,
  11. llvm::StringRef module_name,
  12. const SemanticsIR& semantics_ir,
  13. llvm::raw_ostream* vlog_stream)
  14. : llvm_context_(&llvm_context),
  15. llvm_module_(std::make_unique<llvm::Module>(module_name, llvm_context)),
  16. semantics_ir_(&semantics_ir),
  17. vlog_stream_(vlog_stream) {
  18. CARBON_CHECK(!semantics_ir.has_errors())
  19. << "Generating LLVM IR from invalid SemanticsIR is unsupported.";
  20. }
  21. // TODO: Move this to lower_to_llvm.cpp.
  22. auto LoweringContext::Run() -> std::unique_ptr<llvm::Module> {
  23. CARBON_CHECK(llvm_module_) << "Run can only be called once.";
  24. // Lower types.
  25. auto types = semantics_ir_->types();
  26. types_.resize_for_overwrite(types.size());
  27. for (int i = 0; i < static_cast<int>(types.size()); ++i) {
  28. types_[i] = BuildType(types[i]);
  29. }
  30. // Lower function declarations.
  31. functions_.resize_for_overwrite(semantics_ir_->functions_size());
  32. for (int i = 0; i < semantics_ir_->functions_size(); ++i) {
  33. functions_[i] = BuildFunctionDeclaration(SemanticsFunctionId(i));
  34. }
  35. // TODO: Lower global variable declarations.
  36. // Lower function definitions.
  37. for (int i = 0; i < semantics_ir_->functions_size(); ++i) {
  38. BuildFunctionDefinition(SemanticsFunctionId(i));
  39. }
  40. // TODO: Lower global variable initializers.
  41. return std::move(llvm_module_);
  42. }
  43. auto LoweringContext::BuildFunctionDeclaration(SemanticsFunctionId function_id)
  44. -> llvm::Function* {
  45. auto function = semantics_ir().GetFunction(function_id);
  46. // TODO: Lower type information for the arguments prior to building args.
  47. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  48. llvm::SmallVector<llvm::Type*> args;
  49. args.resize_for_overwrite(param_refs.size());
  50. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  51. args[i] = GetType(semantics_ir().GetNode(param_refs[i]).type_id());
  52. }
  53. llvm::Type* return_type = GetType(function.return_type_id.is_valid()
  54. ? function.return_type_id
  55. : semantics_ir().empty_tuple_type_id());
  56. llvm::FunctionType* function_type =
  57. llvm::FunctionType::get(return_type, args, /*isVarArg=*/false);
  58. auto* llvm_function = llvm::Function::Create(
  59. function_type, llvm::Function::ExternalLinkage,
  60. semantics_ir().GetString(function.name_id), llvm_module());
  61. // Set parameter names.
  62. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  63. auto [param_name_id, _] =
  64. semantics_ir().GetNode(param_refs[i]).GetAsBindName();
  65. llvm_function->getArg(i)->setName(semantics_ir().GetString(param_name_id));
  66. }
  67. return llvm_function;
  68. }
  69. auto LoweringContext::BuildFunctionDefinition(SemanticsFunctionId function_id)
  70. -> void {
  71. auto function = semantics_ir().GetFunction(function_id);
  72. const auto& body_block_ids = function.body_block_ids;
  73. if (body_block_ids.empty()) {
  74. // Function is probably defined in another file; not an error.
  75. return;
  76. }
  77. llvm::Function* llvm_function = GetFunction(function_id);
  78. LoweringFunctionContext function_lowering(*this, llvm_function);
  79. // Add parameters to locals.
  80. auto param_refs = semantics_ir().GetNodeBlock(function.param_refs_id);
  81. for (int i = 0; i < static_cast<int>(param_refs.size()); ++i) {
  82. auto param_storage =
  83. semantics_ir().GetNode(param_refs[i]).GetAsBindName().second;
  84. function_lowering.SetLocal(param_storage, 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::EmptyTupleType.AsInt():
  110. // Represent empty types as empty structs.
  111. // TODO: Investigate special-casing handling of these so that they can be
  112. // collectively replaced with LLVM's void, particularly around function
  113. // returns. LLVM doesn't allow declaring variables with a void type, so
  114. // that may require significant special casing.
  115. return llvm::StructType::create(
  116. *llvm_context_, llvm::ArrayRef<llvm::Type*>(),
  117. SemanticsBuiltinKind::FromInt(node_id.index).name());
  118. case SemanticsBuiltinKind::FloatingPointType.AsInt():
  119. // TODO: Handle different sizes.
  120. return llvm::Type::getDoubleTy(*llvm_context_);
  121. case SemanticsBuiltinKind::IntegerType.AsInt():
  122. // TODO: Handle different sizes.
  123. return llvm::Type::getInt32Ty(*llvm_context_);
  124. case SemanticsBuiltinKind::BoolType.AsInt():
  125. // TODO: We may want to have different representations for `bool` storage
  126. // (`i8`) versus for `bool` values (`i1`).
  127. return llvm::Type::getInt1Ty(*llvm_context_);
  128. }
  129. auto node = semantics_ir_->GetNode(node_id);
  130. switch (node.kind()) {
  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 type_id = semantics_ir_->GetNode(ref_id).type_id();
  137. // TODO: Handle recursive types. The restriction for builtins prevents
  138. // recursion while still letting them cache.
  139. CARBON_CHECK(type_id.index < SemanticsBuiltinKind::ValidCount)
  140. << type_id;
  141. subtypes.push_back(GetType(type_id));
  142. }
  143. return llvm::StructType::create(*llvm_context_, subtypes,
  144. "StructLiteralType");
  145. }
  146. default: {
  147. CARBON_FATAL() << "Cannot use node as type: " << node_id;
  148. }
  149. }
  150. }
  151. } // namespace Carbon