file_context.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  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/Basic/CodeGenOptions.h"
  7. #include "clang/CodeGen/ModuleBuilder.h"
  8. #include "clang/Lex/PreprocessorOptions.h"
  9. #include "llvm/Support/BLAKE3.h"
  10. #include "toolchain/lower/context.h"
  11. #include "toolchain/parse/tree_and_subtrees.h"
  12. #include "toolchain/sem_ir/file.h"
  13. #include "toolchain/sem_ir/ids.h"
  14. #include "toolchain/sem_ir/inst_namer.h"
  15. namespace Carbon::Lower {
  16. // Context and shared functionality for lowering within a SemIR file.
  17. class FileContext {
  18. public:
  19. using LoweredConstantStore =
  20. FixedSizeValueStore<SemIR::InstId, llvm::Constant*>;
  21. // Describes a specific function's body fingerprint.
  22. struct SpecificFunctionFingerprint {
  23. // Fingerprint with all specific-dependent instructions, except specific
  24. // calls. This is built by the `FunctionContext` while lowering each
  25. // instruction in the definition of a specific function.
  26. // TODO: This can be merged with the function type fingerprint, for a
  27. // single upfront non-equivalence check, and hash bucketing for deeper
  28. // equivalence evaluation.
  29. llvm::BLAKE3Result<32> common_fingerprint;
  30. // Fingerprint for all calls to specific functions (hashes all calls to
  31. // other specifics). This is built by the `FunctionContext` while lowering.
  32. llvm::BLAKE3Result<32> specific_fingerprint;
  33. // All non-hashed specific_ids of functions called.
  34. llvm::SmallVector<SemIR::SpecificId> calls;
  35. };
  36. explicit FileContext(Context& context, const SemIR::File& sem_ir,
  37. const SemIR::InstNamer* inst_namer,
  38. llvm::raw_ostream* vlog_stream);
  39. // Creates the Clang `CodeGenerator` to generate LLVM module from imported C++
  40. // code. Returns null when not importing C++.
  41. auto CreateCppCodeGenerator() -> std::unique_ptr<clang::CodeGenerator>;
  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. return *GetFunctionAddr(function_id, specific_id);
  56. }
  57. // Gets a or creates callable's function. Returns nullptr for a builtin.
  58. auto GetOrCreateFunction(SemIR::FunctionId function_id,
  59. SemIR::SpecificId specific_id) -> llvm::Function*;
  60. // Returns a lowered type for the given type_id.
  61. auto GetType(SemIR::TypeId type_id) -> llvm::Type* {
  62. CARBON_CHECK(type_id.has_value(), "Should not be called with `None`");
  63. CARBON_CHECK(type_id.is_concrete(), "Lowering symbolic type {0}: {1}",
  64. type_id, sem_ir().types().GetAsInst(type_id));
  65. CARBON_CHECK(types_.Get(type_id), "Missing type {0}: {1}", type_id,
  66. sem_ir().types().GetAsInst(type_id));
  67. return types_.Get(type_id);
  68. }
  69. // Returns location information for use with DebugInfo.
  70. auto GetLocForDI(SemIR::InstId inst_id) -> Context::LocForDI;
  71. // Returns a lowered value to use for a value of type `type`.
  72. auto GetTypeAsValue() -> llvm::Constant* {
  73. return context().GetTypeAsValue();
  74. }
  75. // Returns a lowered value to use for a value of int literal type.
  76. auto GetIntLiteralAsValue() -> llvm::Constant* {
  77. return context().GetIntLiteralAsValue();
  78. }
  79. // Returns a value for the given constant. If specified, `use_inst_id` is the
  80. // instruction that is using this constant.
  81. auto GetConstant(SemIR::ConstantId const_id, SemIR::InstId use_inst_id)
  82. -> llvm::Value*;
  83. // Returns the empty LLVM struct type used to represent the type `type`.
  84. auto GetTypeType() -> llvm::StructType* { return context().GetTypeType(); }
  85. auto context() -> Context& { return *context_; }
  86. auto llvm_context() -> llvm::LLVMContext& { return context().llvm_context(); }
  87. auto llvm_module() -> llvm::Module& { return context().llvm_module(); }
  88. auto sem_ir() -> const SemIR::File& { return *sem_ir_; }
  89. auto cpp_ast() -> const clang::ASTUnit* { return sem_ir().cpp_ast(); }
  90. auto inst_namer() -> const SemIR::InstNamer* { return inst_namer_; }
  91. auto global_variables() -> const Map<SemIR::InstId, llvm::GlobalVariable*>& {
  92. return global_variables_;
  93. }
  94. auto printf_int_format_string() -> llvm::Value* {
  95. return context().printf_int_format_string();
  96. }
  97. auto SetPrintfIntFormatString(llvm::Value* printf_int_format_string) {
  98. context().SetPrintfIntFormatString(printf_int_format_string);
  99. }
  100. struct FunctionTypeInfo {
  101. llvm::FunctionType* type;
  102. llvm::SmallVector<SemIR::InstId> param_inst_ids;
  103. llvm::Type* return_type = nullptr;
  104. SemIR::InstId return_param_id = SemIR::InstId::None;
  105. };
  106. // Retrieve various features of the function's type useful for constructing
  107. // the `llvm::Type` for the `llvm::Function`. If any part of the type can't be
  108. // manifest (eg: incomplete return or parameter types), then the result is as
  109. // if the type was `void()`.
  110. auto BuildFunctionTypeInfo(const SemIR::Function& function,
  111. SemIR::SpecificId specific_id) -> FunctionTypeInfo;
  112. // Builds the global for the given instruction, which should then be cached by
  113. // the caller.
  114. auto BuildGlobalVariableDecl(SemIR::VarStorage var_storage)
  115. -> llvm::GlobalVariable*;
  116. // Builds the definition for the given function. If the function is only a
  117. // declaration with no definition, does nothing. If this is a generic it'll
  118. // only be lowered if the specific_id is specified. During this lowering of
  119. // a generic, more generic functions may be added for lowering.
  120. auto BuildFunctionDefinition(
  121. SemIR::FunctionId function_id,
  122. SemIR::SpecificId specific_id = SemIR::SpecificId::None) -> void;
  123. private:
  124. // Gets the location in which a callable's function is stored.
  125. auto GetFunctionAddr(SemIR::FunctionId function_id,
  126. SemIR::SpecificId specific_id) -> llvm::Function** {
  127. return specific_id.has_value() ? &specific_functions_.Get(specific_id)
  128. : &functions_.Get(function_id);
  129. }
  130. // Notes that a C++ function has been referenced for the first time, so we
  131. // should ask Clang to generate a definition for it if possible.
  132. auto HandleReferencedCppFunction(clang::FunctionDecl* cpp_decl) -> void;
  133. // Notes that a specific function has been referenced for the first time.
  134. // Updates the fingerprint to include the function's type, and adds the
  135. // function to the list of specific functions whose definitions should be
  136. // lowered.
  137. auto HandleReferencedSpecificFunction(SemIR::FunctionId function_id,
  138. SemIR::SpecificId specific_id,
  139. llvm::Type* llvm_type) -> void;
  140. // Builds the declaration for the given function, which should then be cached
  141. // by the caller.
  142. auto BuildFunctionDecl(SemIR::FunctionId function_id,
  143. SemIR::SpecificId specific_id =
  144. SemIR::SpecificId::None) -> llvm::Function*;
  145. // Builds a function's body. Common functionality for all functions.
  146. //
  147. // The `function_id` and `specific_id` identify the function within this
  148. // context's file. If the function was defined in a different file,
  149. // `definition_context` is a `FileContext` for that other file.
  150. // `definition_function` is the `Function` object within the file that owns
  151. // the definition.
  152. auto BuildFunctionBody(SemIR::FunctionId function_id,
  153. SemIR::SpecificId specific_id,
  154. const SemIR::Function& declaration_function,
  155. FileContext& definition_context,
  156. const SemIR::Function& definition_function) -> void;
  157. // Build the DISubprogram metadata for the given function.
  158. auto BuildDISubprogram(const SemIR::Function& function,
  159. const llvm::Function* llvm_function)
  160. -> llvm::DISubprogram*;
  161. // Builds the type for the given instruction, which should then be cached by
  162. // the caller.
  163. auto BuildType(SemIR::InstId inst_id) -> llvm::Type*;
  164. auto BuildVtable(const SemIR::Class& class_info) -> llvm::GlobalVariable*;
  165. // Records a specific that was lowered for a generic. These are added one
  166. // by one while lowering their definitions.
  167. auto AddLoweredSpecificForGeneric(SemIR::GenericId generic_id,
  168. SemIR::SpecificId specific_id) {
  169. lowered_specifics_.Get(generic_id).push_back(specific_id);
  170. }
  171. // Initializes and returns a SpecificFunctionFingerprint* instance for a
  172. // specific. The internal of the fingerprint are populated during and after
  173. // lowering the function body of that specific.
  174. auto InitializeFingerprintForSpecific(SemIR::SpecificId specific_id)
  175. -> SpecificFunctionFingerprint* {
  176. if (!specific_id.has_value()) {
  177. return nullptr;
  178. }
  179. return &lowered_specific_fingerprint_.Get(specific_id);
  180. }
  181. // Entry point for coalescing equivalent specifics. Two function definitions,
  182. // from the same generic, with different specific_ids are considered
  183. // equivalent if, at the LLVM level, one can be replaced with the other, with
  184. // no change in behavior. All LLVM types and instructions must be equivalent.
  185. auto CoalesceEquivalentSpecifics() -> void;
  186. // While coalescing specifics, returns whether the function types for two
  187. // specifics are equivalent. This uses a fingerprint generated for each
  188. // function type.
  189. auto AreFunctionTypesEquivalent(SemIR::SpecificId specific_id1,
  190. SemIR::SpecificId specific_id2) -> bool;
  191. // While coalescing specifics, compare the function bodies for two specifics.
  192. // This uses fingerprints generated during lowering of the function body.
  193. // The `visited_equivalent_specifics` parameter is used to track cycles in
  194. // the function callgraph, and will also return equivalent pairs of specifics
  195. // found, if the two specifics given as arguments are found to be equivalent.
  196. auto AreFunctionBodiesEquivalent(
  197. SemIR::SpecificId specific_id1, SemIR::SpecificId specific_id2,
  198. Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>&
  199. visited_equivalent_specifics) -> bool;
  200. // Given an equivalent pair of specifics, updates the canonical specific to
  201. // use for each of the two Specifics found to be equivalent.
  202. auto ProcessSpecificEquivalence(
  203. std::pair<SemIR::SpecificId, SemIR::SpecificId> pair) -> void;
  204. // Checks if two specific_ids are equivalent and also reduces the equivalence
  205. // chains/paths. This update ensures the canonical specific is always "one
  206. // hop away".
  207. auto IsKnownEquivalence(SemIR::SpecificId specific_id1,
  208. SemIR::SpecificId specific_id2) -> bool;
  209. // Update the tracked equivalent specific for the `SpecificId`. This may
  210. // occur a replacement was performed and a chain of such replacements needs
  211. // to be followed to discover the canonical specific for the given argument.
  212. auto UpdateEquivalentSpecific(SemIR::SpecificId specific_id) -> void;
  213. // Update the LLVM function to use for a `SpecificId` that has been found to
  214. // have another equivalent LLVM function. Replace all uses of the original
  215. // LLVM function with the equivalent one found, and delete the previous LLVM
  216. // function body.
  217. auto UpdateAndDeleteLLVMFunction(SemIR::SpecificId specific_id) -> void;
  218. // Inserts a pair into a set of pairs in canonical form. Also implicitly
  219. // checks entry already existed if it cannot be inserted.
  220. auto InsertPair(
  221. SemIR::SpecificId specific_id1, SemIR::SpecificId specific_id2,
  222. Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>& set_of_pairs)
  223. -> bool;
  224. // Checks if a pair is contained into a set of pairs, in canonical form.
  225. auto ContainsPair(
  226. SemIR::SpecificId specific_id1, SemIR::SpecificId specific_id2,
  227. const Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>& set_of_pairs)
  228. -> bool;
  229. // The overall lowering context.
  230. Context* context_;
  231. // The input SemIR.
  232. const SemIR::File* const sem_ir_;
  233. // The options used to create the Clang Code Generator.
  234. clang::HeaderSearchOptions cpp_header_search_options_;
  235. clang::PreprocessorOptions cpp_preprocessor_options_;
  236. clang::CodeGenOptions cpp_code_gen_options_;
  237. // The Clang `CodeGenerator` to generate LLVM module from imported C++
  238. // code. Should be initialized using `CreateCppCodeGenerator()`. Can be null
  239. // if no C++ code is imported.
  240. std::unique_ptr<clang::CodeGenerator> cpp_code_generator_;
  241. // The instruction namer, if given.
  242. const SemIR::InstNamer* const inst_namer_;
  243. // The optional vlog stream.
  244. llvm::raw_ostream* vlog_stream_;
  245. // Maps callables to lowered functions. SemIR treats callables as the
  246. // canonical form of a function, so lowering needs to do the same.
  247. using LoweredFunctionStore =
  248. FixedSizeValueStore<SemIR::FunctionId, llvm::Function*>;
  249. LoweredFunctionStore functions_;
  250. // Maps specific callables to lowered functions.
  251. FixedSizeValueStore<SemIR::SpecificId, llvm::Function*> specific_functions_;
  252. // Provides lowered versions of types. Entries are non-symbolic types.
  253. using LoweredTypeStore = FixedSizeValueStore<SemIR::TypeId, llvm::Type*>;
  254. LoweredTypeStore types_;
  255. // Maps constants to their lowered values. Indexes are the `InstId` for
  256. // constant instructions.
  257. LoweredConstantStore constants_;
  258. // Maps global variables to their lowered variant.
  259. Map<SemIR::InstId, llvm::GlobalVariable*> global_variables_;
  260. // For a generic function, keep track of the specifics for which LLVM
  261. // function declarations were created. Those can be retrieved then from
  262. // `specific_functions_`.
  263. FixedSizeValueStore<SemIR::GenericId, llvm::SmallVector<SemIR::SpecificId>>
  264. lowered_specifics_;
  265. // For specifics that exist in lowered_specifics, a hash of their function
  266. // type information: return and parameter types.
  267. // TODO: Hashing all members of `FunctionTypeInfo` may not be necessary.
  268. FixedSizeValueStore<SemIR::SpecificId, llvm::BLAKE3Result<32>>
  269. lowered_specifics_type_fingerprint_;
  270. // This is initialized and populated while lowering a specific.
  271. FixedSizeValueStore<SemIR::SpecificId, SpecificFunctionFingerprint>
  272. lowered_specific_fingerprint_;
  273. // Equivalent specifics that have been found. For each specific, this points
  274. // to the canonical equivalent specific, which may also be self. We currently
  275. // define the canonical specific as the one with the lowest
  276. // `SpecificId.index`.
  277. //
  278. // Entries are initialized to `SpecificId::None`, which defines that there is
  279. // no other equivalent specific to this `SpecificId`.
  280. FixedSizeValueStore<SemIR::SpecificId, SemIR::SpecificId>
  281. equivalent_specifics_;
  282. // Non-equivalent specifics found.
  283. // TODO: Revisit this due to its quadratic space growth.
  284. Set<std::pair<SemIR::SpecificId, SemIR::SpecificId>>
  285. non_equivalent_specifics_;
  286. };
  287. } // namespace Carbon::Lower
  288. #endif // CARBON_TOOLCHAIN_LOWER_FILE_CONTEXT_H_