file_context.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  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 "clang/CodeGen/ModuleBuilder.h"
  7. #include "clang/Lex/PreprocessorOptions.h"
  8. #include "toolchain/lower/context.h"
  9. #include "toolchain/lower/specific_coalescer.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. // Information about how a given function declaration is lowered.
  16. struct FunctionInfo {
  17. // The type of the lowered function.
  18. llvm::FunctionType* type;
  19. // The debug info type of the lowered function.
  20. llvm::DISubroutineType* di_type;
  21. // The indices of the `Call` parameter patterns that correspond to parameters
  22. // of the LLVM IR function, in the order of the LLVM IR parameter list. Some
  23. // `Call` parameters may be omitted (e.g. if they are stateless), and the
  24. // order may differ from the SemIR `Call` parameter list (e.g. the return
  25. // parameter, if any, always goes first).
  26. llvm::SmallVector<SemIR::CallParamIndex> lowered_param_indices;
  27. // The indices of any `Call` param patterns that aren't present in
  28. // lowered_param_pattern_ids.
  29. llvm::SmallVector<SemIR::CallParamIndex> unused_param_indices;
  30. // The lowered function declaration.
  31. llvm::Function* llvm_function;
  32. };
  33. // Context and shared functionality for lowering within a SemIR file.
  34. class FileContext {
  35. public:
  36. using LoweredConstantStore =
  37. FixedSizeValueStore<SemIR::InstId, llvm::Constant*,
  38. Tag<SemIR::CheckIRId>>;
  39. explicit FileContext(Context& context, const SemIR::File& sem_ir,
  40. const SemIR::InstNamer* inst_namer,
  41. llvm::raw_ostream* vlog_stream);
  42. // Prepares to lower code in this IR, by precomputing needed LLVM types,
  43. // constants, declarations, etc. Should only be called once, before we lower
  44. // anything in this file.
  45. auto PrepareToLower() -> void;
  46. // Lowers all the definitions provided by the SemIR::File to LLVM IR.
  47. auto LowerDefinitions() -> void;
  48. // Perform final cleanup tasks once all lowering has been completed.
  49. auto Finalize() -> void;
  50. // Gets a callable's function. Returns nullptr for a builtin or a function we
  51. // have not lowered.
  52. auto GetFunction(SemIR::FunctionId function_id,
  53. SemIR::SpecificId specific_id = SemIR::SpecificId::None)
  54. -> llvm::Function* {
  55. const auto& function_info = GetFunctionInfo(function_id, specific_id);
  56. return function_info ? function_info->llvm_function : nullptr;
  57. }
  58. // Returns the FunctionInfo for the given function in the given specific, if
  59. // it has already been computed.
  60. auto GetFunctionInfo(SemIR::FunctionId function_id,
  61. SemIR::SpecificId specific_id)
  62. -> std::optional<FunctionInfo>& {
  63. return specific_id.has_value() ? specific_functions_.Get(specific_id)
  64. : functions_.Get(function_id);
  65. }
  66. // Returns the FunctionInfo for the given function in the given specific. If
  67. // it's not already available, this function will compute it, including
  68. // creating the `llvm::Function` for it. Returns nullopt for a builtin.
  69. auto GetOrCreateFunctionInfo(SemIR::FunctionId function_id,
  70. SemIR::SpecificId specific_id)
  71. -> std::optional<FunctionInfo>&;
  72. // Returns a lowered type for the given type_id.
  73. auto GetType(SemIR::TypeId type_id) -> llvm::Type* {
  74. return GetTypeAndDIType(type_id).llvm_ir_type;
  75. }
  76. struct LoweredTypes {
  77. llvm::Type* llvm_ir_type;
  78. llvm::DIType* llvm_di_type;
  79. };
  80. // Returns both the lowered llvm IR type and the lowered llvm IR debug info
  81. // type for the given type_id.
  82. auto GetTypeAndDIType(SemIR::TypeId type_id) const -> LoweredTypes {
  83. CARBON_CHECK(type_id.has_value(), "Should not be called with `None`");
  84. CARBON_CHECK(type_id.is_concrete(), "Lowering symbolic type {0}: {1}",
  85. type_id, sem_ir().types().GetAsInst(type_id));
  86. auto result = types_.Get(type_id);
  87. if (!result.llvm_ir_type) {
  88. result.llvm_ir_type = context_->GetOpaqueType();
  89. }
  90. return result;
  91. }
  92. // Returns location information for use with DebugInfo.
  93. auto GetLocForDI(SemIR::InstId inst_id) -> Context::LocForDI;
  94. // Returns a lowered value to use for a value of type `type`.
  95. auto GetTypeAsValue() -> llvm::Constant* {
  96. return context().GetTypeAsValue();
  97. }
  98. // Returns a lowered value to use for a value of literal type.
  99. auto GetLiteralAsValue() -> llvm::Constant* {
  100. return context().GetLiteralAsValue();
  101. }
  102. // Returns a value for the given constant. If specified, `use_inst_id` is the
  103. // instruction that is using this constant.
  104. auto GetConstant(SemIR::ConstantId const_id, SemIR::InstId use_inst_id)
  105. -> llvm::Value*;
  106. auto GetVtable(SemIR::VtableId vtable_id, SemIR::SpecificId specific_id)
  107. -> llvm::GlobalVariable* {
  108. if (!specific_id.has_value()) {
  109. return vtables_.Get(vtable_id);
  110. }
  111. auto*& specific_vtable = specific_vtables_.Get(specific_id);
  112. if (!specific_vtable) {
  113. specific_vtable =
  114. BuildVtable(sem_ir().vtables().Get(vtable_id), specific_id);
  115. }
  116. return specific_vtable;
  117. }
  118. // Returns the empty LLVM struct type used to represent the type `type`.
  119. auto GetTypeType() -> llvm::StructType* { return context().GetTypeType(); }
  120. auto GetFormType() -> llvm::StructType* { return context().GetFormType(); }
  121. auto context() -> Context& { return *context_; }
  122. auto llvm_context() -> llvm::LLVMContext& { return context().llvm_context(); }
  123. auto llvm_module() -> llvm::Module& { return context().llvm_module(); }
  124. auto cpp_code_generator() -> clang::CodeGenerator& {
  125. CARBON_CHECK(cpp_code_generator_);
  126. return *cpp_code_generator_;
  127. }
  128. auto sem_ir() const -> const SemIR::File& { return *sem_ir_; }
  129. auto cpp_file() -> const SemIR::CppFile* { return sem_ir().cpp_file(); }
  130. auto inst_namer() -> const SemIR::InstNamer* { return inst_namer_; }
  131. auto global_variables() -> const Map<SemIR::InstId, llvm::GlobalVariable*>& {
  132. return global_variables_;
  133. }
  134. auto printf_int_format_string() -> llvm::Value* {
  135. return context().printf_int_format_string();
  136. }
  137. auto SetPrintfIntFormatString(llvm::Value* printf_int_format_string) {
  138. context().SetPrintfIntFormatString(printf_int_format_string);
  139. }
  140. // Builds the global for the given instruction, which should then be cached by
  141. // the caller.
  142. auto BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  143. -> llvm::Constant*;
  144. // Builds the global for the given instruction which is known to not be
  145. // imported from C++.
  146. auto BuildNonCppGlobalVariableDecl(SemIR::VarStorage var_storage)
  147. -> llvm::GlobalVariable*;
  148. // Builds the definition for the given function. If the function is only a
  149. // declaration with no definition, does nothing. If this is a generic it'll
  150. // only be lowered if the specific_id is specified. During this lowering of
  151. // a generic, more generic functions may be added for lowering.
  152. auto BuildFunctionDefinition(
  153. SemIR::FunctionId function_id,
  154. SemIR::SpecificId specific_id = SemIR::SpecificId::None) -> void;
  155. private:
  156. // Notes that a C++ function has been referenced for the first time, so we
  157. // should ask Clang to generate a definition for it if possible.
  158. auto HandleReferencedCppFunction(clang::FunctionDecl* cpp_decl)
  159. -> llvm::Function*;
  160. // Notes that a specific function has been referenced for the first time.
  161. // Updates the fingerprint to include the function's type, and adds the
  162. // function to the list of specific functions whose definitions should be
  163. // lowered.
  164. auto HandleReferencedSpecificFunction(SemIR::FunctionId function_id,
  165. SemIR::SpecificId specific_id,
  166. llvm::Type* llvm_type) -> void;
  167. // Information used to build a `FunctionInfo`.
  168. // TODO: Rename this, since it's not limited to type information, and/or
  169. // restructure the code so it's not needed.
  170. struct FunctionTypeInfo {
  171. // See documentation for the corresponding members of FunctionInfo.
  172. llvm::FunctionType* type;
  173. llvm::DISubroutineType* di_type;
  174. llvm::SmallVector<SemIR::CallParamIndex> lowered_param_indices;
  175. llvm::SmallVector<SemIR::CallParamIndex> unused_param_indices;
  176. // The names of the lowered `Call` parameters, in the same order as
  177. // `lowered_param_indices`.
  178. llvm::SmallVector<SemIR::NameId> param_name_ids;
  179. // When `return_param_id` is not `None`, the corresponding lowered parameter
  180. // should be given an `sret` attribute with this type.
  181. llvm::Type* sret_type = nullptr;
  182. };
  183. class FunctionTypeInfoBuilder;
  184. // Builds an LLVM function declaration for the given function, or returns an
  185. // existing one if we've already lowered another declaration of the same
  186. // function.
  187. auto GetOrCreateLLVMFunction(const FunctionTypeInfo& function_type_info,
  188. SemIR::FunctionId function_id,
  189. SemIR::SpecificId specific_id)
  190. -> llvm::Function*;
  191. // Builds the declaration for the given function, which should then be cached
  192. // by the caller.
  193. auto BuildFunctionDecl(
  194. SemIR::FunctionId function_id,
  195. SemIR::SpecificId specific_id = SemIR::SpecificId::None)
  196. -> std::optional<FunctionInfo>;
  197. // Builds a function's body. Common functionality for all functions.
  198. //
  199. // The `function_id` and `specific_id` identify the function within this
  200. // context's file. If the function was defined in a different file,
  201. // `definition_context` is a `FileContext` for that other file.
  202. // `definition_function` is the `Function` object within the file that owns
  203. // the definition.
  204. auto BuildFunctionBody(SemIR::FunctionId function_id,
  205. SemIR::SpecificId specific_id,
  206. const SemIR::Function& declaration_function,
  207. FileContext& definition_context,
  208. const SemIR::Function& definition_function) -> void;
  209. // Build the DISubprogram metadata for the given function.
  210. auto BuildDISubprogram(const SemIR::Function& function,
  211. const FunctionInfo& function_info)
  212. -> llvm::DISubprogram*;
  213. // Builds the `llvm::Type` and `llvm::DIType` for the given instruction, which
  214. // should then be cached by the caller.
  215. auto BuildType(SemIR::InstId inst_id) -> LoweredTypes;
  216. auto BuildVtable(const SemIR::Vtable& vtable, SemIR::SpecificId specific_id)
  217. -> llvm::GlobalVariable*;
  218. // Records a specific that was lowered for a generic. These are added one
  219. // by one while lowering their definitions.
  220. auto AddLoweredSpecificForGeneric(SemIR::GenericId generic_id,
  221. SemIR::SpecificId specific_id) {
  222. lowered_specifics_.Get(generic_id).push_back(specific_id);
  223. }
  224. // The overall lowering context.
  225. Context* context_;
  226. // The input SemIR.
  227. const SemIR::File* const sem_ir_;
  228. // The Clang `CodeGenerator` to generate LLVM module from imported C++
  229. // code. Can be null if no C++ code is imported.
  230. clang::CodeGenerator* cpp_code_generator_;
  231. // The instruction namer, if given.
  232. const SemIR::InstNamer* const inst_namer_;
  233. // The optional vlog stream.
  234. llvm::raw_ostream* vlog_stream_;
  235. // Maps callables to lowered functions. SemIR treats callables as the
  236. // canonical form of a function, so lowering needs to do the same.
  237. using LoweredFunctionStore =
  238. FixedSizeValueStore<SemIR::FunctionId, std::optional<FunctionInfo>,
  239. Tag<SemIR::CheckIRId>>;
  240. LoweredFunctionStore functions_;
  241. // Maps specific callables to lowered functions.
  242. FixedSizeValueStore<SemIR::SpecificId, std::optional<FunctionInfo>,
  243. Tag<SemIR::CheckIRId>>
  244. specific_functions_;
  245. // Provides lowered versions of types. Entries are non-symbolic types.
  246. //
  247. // TypeIds internally are concrete ConstantIds.
  248. using LoweredTypeStore =
  249. FixedSizeValueStore<SemIR::TypeId, LoweredTypes, Tag<SemIR::CheckIRId>>;
  250. LoweredTypeStore types_;
  251. // Maps constants to their lowered values. Indexes are the `InstId` for
  252. // constant instructions.
  253. LoweredConstantStore constants_;
  254. // Maps global variables to their lowered variant.
  255. Map<SemIR::InstId, llvm::GlobalVariable*> global_variables_;
  256. // For a generic function, keep track of the specifics for which LLVM
  257. // function declarations were created. Those can be retrieved then from
  258. // `specific_functions_`.
  259. FixedSizeValueStore<SemIR::GenericId, llvm::SmallVector<SemIR::SpecificId>,
  260. Tag<SemIR::CheckIRId>>
  261. lowered_specifics_;
  262. SpecificCoalescer coalescer_;
  263. FixedSizeValueStore<SemIR::VtableId, llvm::GlobalVariable*,
  264. Tag<SemIR::CheckIRId>>
  265. vtables_;
  266. FixedSizeValueStore<SemIR::SpecificId, llvm::GlobalVariable*,
  267. Tag<SemIR::CheckIRId>>
  268. specific_vtables_;
  269. };
  270. } // namespace Carbon::Lower
  271. #endif // CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_