lowering_context.cpp 6.8 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. auto body_id = function.body_id;
  73. if (!body_id.is_valid()) {
  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. // Add the entry block to the worklist.
  87. function_lowering.GetBlock(function.body_id);
  88. while (!function_lowering.block_worklist().empty()) {
  89. SemanticsNodeBlockId block = function_lowering.block_worklist().Pop();
  90. CARBON_VLOG() << "Lowering " << block << "\n";
  91. function_lowering.builder().SetInsertPoint(
  92. function_lowering.GetBlock(block));
  93. for (const auto& node_id : semantics_ir().GetNodeBlock(block)) {
  94. auto node = semantics_ir().GetNode(node_id);
  95. CARBON_VLOG() << "Lowering " << node_id << ": " << node << "\n";
  96. switch (node.kind()) {
  97. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  98. case SemanticsNodeKind::Name: \
  99. LoweringHandle##Name(function_lowering, node_id, node); \
  100. break;
  101. #include "toolchain/semantics/semantics_node_kind.def"
  102. }
  103. }
  104. }
  105. }
  106. auto LoweringContext::BuildType(SemanticsNodeId node_id) -> llvm::Type* {
  107. switch (node_id.index) {
  108. case SemanticsBuiltinKind::EmptyTupleType.AsInt():
  109. // Represent empty types as empty structs.
  110. // TODO: Investigate special-casing handling of these so that they can be
  111. // collectively replaced with LLVM's void, particularly around function
  112. // returns. LLVM doesn't allow declaring variables with a void type, so
  113. // that may require significant special casing.
  114. return llvm::StructType::create(
  115. *llvm_context_, llvm::ArrayRef<llvm::Type*>(),
  116. SemanticsBuiltinKind::FromInt(node_id.index).name());
  117. case SemanticsBuiltinKind::FloatingPointType.AsInt():
  118. // TODO: Handle different sizes.
  119. return llvm::Type::getDoubleTy(*llvm_context_);
  120. case SemanticsBuiltinKind::IntegerType.AsInt():
  121. // TODO: Handle different sizes.
  122. return llvm::Type::getInt32Ty(*llvm_context_);
  123. case SemanticsBuiltinKind::BoolType.AsInt():
  124. // TODO: We may want to have different representations for `bool` storage
  125. // (`i8`) versus for `bool` values (`i1`).
  126. return llvm::Type::getInt1Ty(*llvm_context_);
  127. }
  128. auto node = semantics_ir_->GetNode(node_id);
  129. switch (node.kind()) {
  130. case SemanticsNodeKind::StructType: {
  131. auto refs = semantics_ir_->GetNodeBlock(node.GetAsStructType());
  132. llvm::SmallVector<llvm::Type*> subtypes;
  133. subtypes.reserve(refs.size());
  134. for (auto ref_id : refs) {
  135. auto type_id = semantics_ir_->GetNode(ref_id).type_id();
  136. // TODO: Handle recursive types. The restriction for builtins prevents
  137. // recursion while still letting them cache.
  138. CARBON_CHECK(type_id.index < SemanticsBuiltinKind::ValidCount)
  139. << type_id;
  140. subtypes.push_back(GetType(type_id));
  141. }
  142. return llvm::StructType::create(*llvm_context_, subtypes,
  143. "StructLiteralType");
  144. }
  145. default: {
  146. CARBON_FATAL() << "Cannot use node as type: " << node_id;
  147. }
  148. }
  149. }
  150. } // namespace Carbon