file_context.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226
  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. #ifndef CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_
  5. #define CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_
  6. #include "llvm/IR/Constants.h"
  7. #include "llvm/IR/DIBuilder.h"
  8. #include "llvm/IR/LLVMContext.h"
  9. #include "llvm/IR/Module.h"
  10. #include "toolchain/parse/tree_and_subtrees.h"
  11. #include "toolchain/sem_ir/file.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/inst_namer.h"
  14. namespace Carbon::Lower {
  15. // Context and shared functionality for lowering handlers.
  16. class FileContext {
  17. public:
  18. // Location information for use with DebugInfo. The line_number and
  19. // column_number are >= 0, with 0 as unknown, so that they can be passed
  20. // directly to DebugInfo.
  21. struct LocForDI {
  22. llvm::StringRef filename;
  23. int32_t line_number;
  24. int32_t column_number;
  25. };
  26. explicit FileContext(
  27. llvm::LLVMContext& llvm_context,
  28. std::optional<llvm::ArrayRef<Parse::GetTreeAndSubtreesFn>>
  29. tree_and_subtrees_getters_for_debug_info,
  30. llvm::StringRef module_name, const SemIR::File& sem_ir,
  31. clang::ASTUnit* cpp_ast, const SemIR::InstNamer* inst_namer,
  32. llvm::raw_ostream* vlog_stream);
  33. // Lowers the SemIR::File to LLVM IR. Should only be called once, and handles
  34. // the main execution loop.
  35. auto Run() -> std::unique_ptr<llvm::Module>;
  36. // Create the DICompileUnit metadata for this compilation.
  37. auto BuildDICompileUnit(llvm::StringRef module_name,
  38. llvm::Module& llvm_module,
  39. llvm::DIBuilder& di_builder) -> llvm::DICompileUnit*;
  40. // Gets a callable's function. Returns nullptr for a builtin.
  41. auto GetFunction(SemIR::FunctionId function_id) -> llvm::Function* {
  42. return functions_[function_id.index];
  43. }
  44. // Gets a or creates callable's function. Returns nullptr for a builtin.
  45. auto GetOrCreateFunction(SemIR::FunctionId function_id,
  46. SemIR::SpecificId specific_id) -> llvm::Function*;
  47. // Returns a lowered type for the given type_id.
  48. auto GetType(SemIR::TypeId type_id) -> llvm::Type* {
  49. CARBON_CHECK(type_id.has_value(), "Should not be called with `None`");
  50. CARBON_CHECK(types_[type_id.index], "Missing type {0}: {1}", type_id,
  51. sem_ir().types().GetAsInst(type_id));
  52. return types_[type_id.index];
  53. }
  54. // Returns location information for use with DebugInfo.
  55. auto GetLocForDI(SemIR::InstId inst_id) -> LocForDI;
  56. // Returns a lowered value to use for a value of type `type`.
  57. auto GetTypeAsValue() -> llvm::Constant* {
  58. return llvm::ConstantStruct::get(GetTypeType());
  59. }
  60. // Returns a lowered value to use for a value of int literal type.
  61. auto GetIntLiteralAsValue() -> llvm::Constant* {
  62. // TODO: Consider adding a named struct type for integer literals.
  63. return llvm::ConstantStruct::get(llvm::StructType::get(llvm_context()));
  64. }
  65. // Returns a global value for the given instruction.
  66. auto GetGlobal(SemIR::InstId inst_id, SemIR::SpecificId specific_id)
  67. -> llvm::Value*;
  68. // Returns the empty LLVM struct type used to represent the type `type`.
  69. auto GetTypeType() -> llvm::StructType* {
  70. if (!type_type_) {
  71. // `type` is lowered to an empty LLVM StructType.
  72. type_type_ = llvm::StructType::create(*llvm_context_, {}, "type");
  73. }
  74. return type_type_;
  75. }
  76. auto llvm_context() -> llvm::LLVMContext& { return *llvm_context_; }
  77. auto llvm_module() -> llvm::Module& { return *llvm_module_; }
  78. auto sem_ir() -> const SemIR::File& { return *sem_ir_; }
  79. auto cpp_ast() -> clang::ASTUnit* { return cpp_ast_; }
  80. auto inst_namer() -> const SemIR::InstNamer* { return inst_namer_; }
  81. auto global_variables() -> const Map<SemIR::InstId, llvm::GlobalVariable*>& {
  82. return global_variables_;
  83. }
  84. auto printf_int_format_string() -> llvm::Value* {
  85. return printf_int_format_string_;
  86. }
  87. auto SetPrintfIntFormatString(llvm::Value* printf_int_format_string) {
  88. CARBON_CHECK(!printf_int_format_string_,
  89. "PrintInt formatting string already generated");
  90. printf_int_format_string_ = printf_int_format_string;
  91. }
  92. struct FunctionTypeInfo {
  93. llvm::FunctionType* type;
  94. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  95. llvm::Type* return_type = nullptr;
  96. SemIR::InstId return_param_id = SemIR::InstId::None;
  97. };
  98. // Retrieve various features of the function's type useful for constructing
  99. // the `llvm::Type` for the `llvm::Function`. If any part of the type can't be
  100. // manifest (eg: incomplete return or parameter types), then the result is as
  101. // if the type was `void()`.
  102. auto BuildFunctionTypeInfo(const SemIR::Function& function,
  103. SemIR::SpecificId specific_id) -> FunctionTypeInfo;
  104. private:
  105. // Builds the declaration for the given function, which should then be cached
  106. // by the caller.
  107. auto BuildFunctionDecl(SemIR::FunctionId function_id,
  108. SemIR::SpecificId specific_id =
  109. SemIR::SpecificId::None) -> llvm::Function*;
  110. // Builds the definition for the given function. If the function is only a
  111. // declaration with no definition, does nothing. If this is a generic it'll
  112. // only be lowered if the specific_id is specified. During this lowering of
  113. // a generic, more generic functions may be added for lowering.
  114. auto BuildFunctionDefinition(
  115. SemIR::FunctionId function_id,
  116. SemIR::SpecificId specific_id = SemIR::SpecificId::None) -> void;
  117. // Builds a functions body. Common functionality for all functions.
  118. auto BuildFunctionBody(
  119. SemIR::FunctionId function_id, const SemIR::Function& function,
  120. llvm::Function* llvm_function,
  121. SemIR::SpecificId specific_id = SemIR::SpecificId::None) -> void;
  122. // Build the DISubprogram metadata for the given function.
  123. auto BuildDISubprogram(const SemIR::Function& function,
  124. const llvm::Function* llvm_function)
  125. -> llvm::DISubprogram*;
  126. // Builds the type for the given instruction, which should then be cached by
  127. // the caller.
  128. auto BuildType(SemIR::InstId inst_id) -> llvm::Type*;
  129. // Builds the global for the given instruction, which should then be cached by
  130. // the caller.
  131. auto BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  132. -> llvm::GlobalVariable*;
  133. auto BuildVtable(const SemIR::Class& class_info) -> llvm::GlobalVariable*;
  134. // State for building the LLVM IR.
  135. llvm::LLVMContext* llvm_context_;
  136. std::unique_ptr<llvm::Module> llvm_module_;
  137. // State for building the LLVM IR debug info metadata.
  138. llvm::DIBuilder di_builder_;
  139. // The DICompileUnit, if any - null implies debug info is not being emitted.
  140. llvm::DICompileUnit* di_compile_unit_;
  141. // The trees are only provided when debug info should be emitted.
  142. std::optional<llvm::ArrayRef<Parse::GetTreeAndSubtreesFn>>
  143. tree_and_subtrees_getters_for_debug_info_;
  144. // The input SemIR.
  145. const SemIR::File* const sem_ir_;
  146. // A mutable Clang AST is necessary for lowering since using the AST in lower
  147. // modifies it.
  148. clang::ASTUnit* cpp_ast_;
  149. // The instruction namer, if given.
  150. const SemIR::InstNamer* const inst_namer_;
  151. // The optional vlog stream.
  152. llvm::raw_ostream* vlog_stream_;
  153. // Maps callables to lowered functions. SemIR treats callables as the
  154. // canonical form of a function, so lowering needs to do the same.
  155. // Vector indexes correspond to `FunctionId` indexes. We resize this directly
  156. // to the correct size.
  157. llvm::SmallVector<llvm::Function*, 0> functions_;
  158. // Maps specific callables to lowered functions. Vector indexes correspond to
  159. // `SpecificId` indexes. We resize this directly to the correct size.
  160. llvm::SmallVector<llvm::Function*, 0> specific_functions_;
  161. // Maps which specific functions are generics that need to have their
  162. // definitions lowered after the lowering of other definitions.
  163. // This list may grow while lowering generic definitions from this list.
  164. // The list uses the `SpecificId` to index into specific_functions_.
  165. llvm::SmallVector<std::pair<SemIR::FunctionId, SemIR::SpecificId>, 10>
  166. specific_function_definitions_;
  167. // Provides lowered versions of types.
  168. // Vector indexes correspond to `TypeId` indexes for non-symbolic types. We
  169. // resize this directly to the (often large) correct size.
  170. llvm::SmallVector<llvm::Type*, 0> types_;
  171. // Lowered version of the builtin type `type`.
  172. llvm::StructType* type_type_ = nullptr;
  173. // Maps constants to their lowered values.
  174. // Vector indexes correspond to `InstId` indexes for constant instructions. We
  175. // resize this directly to the (often large) correct size.
  176. llvm::SmallVector<llvm::Constant*, 0> constants_;
  177. // Maps global variables to their lowered variant.
  178. Map<SemIR::InstId, llvm::GlobalVariable*> global_variables_;
  179. // Global format string for `printf.int.format` used by the PrintInt builtin.
  180. llvm::Value* printf_int_format_string_ = nullptr;
  181. };
  182. } // namespace Carbon::Lower
  183. #endif // CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_