file.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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_SEM_IR_FILE_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_FILE_H_
  6. #include "clang/Frontend/ASTUnit.h"
  7. #include "common/error.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "llvm/ADT/iterator_range.h"
  10. #include "llvm/Support/Allocator.h"
  11. #include "llvm/Support/FormatVariadic.h"
  12. #include "toolchain/base/canonical_value_store.h"
  13. #include "toolchain/base/int.h"
  14. #include "toolchain/base/relational_value_store.h"
  15. #include "toolchain/base/shared_value_stores.h"
  16. #include "toolchain/base/value_store.h"
  17. #include "toolchain/base/yaml.h"
  18. #include "toolchain/parse/tree.h"
  19. #include "toolchain/sem_ir/associated_constant.h"
  20. #include "toolchain/sem_ir/class.h"
  21. #include "toolchain/sem_ir/constant.h"
  22. #include "toolchain/sem_ir/cpp_global_var.h"
  23. #include "toolchain/sem_ir/cpp_overload_set.h"
  24. #include "toolchain/sem_ir/entity_name.h"
  25. #include "toolchain/sem_ir/facet_type_info.h"
  26. #include "toolchain/sem_ir/function.h"
  27. #include "toolchain/sem_ir/generic.h"
  28. #include "toolchain/sem_ir/ids.h"
  29. #include "toolchain/sem_ir/impl.h"
  30. #include "toolchain/sem_ir/import_cpp.h"
  31. #include "toolchain/sem_ir/import_ir.h"
  32. #include "toolchain/sem_ir/inst.h"
  33. #include "toolchain/sem_ir/interface.h"
  34. #include "toolchain/sem_ir/name.h"
  35. #include "toolchain/sem_ir/name_scope.h"
  36. #include "toolchain/sem_ir/named_constraint.h"
  37. #include "toolchain/sem_ir/singleton_insts.h"
  38. #include "toolchain/sem_ir/specific_interface.h"
  39. #include "toolchain/sem_ir/struct_type_field.h"
  40. #include "toolchain/sem_ir/type.h"
  41. #include "toolchain/sem_ir/type_info.h"
  42. #include "toolchain/sem_ir/vtable.h"
  43. namespace Carbon::SemIR {
  44. // An expression that may contain control flow, represented as a
  45. // single-entry/single-exit region. `block_ids` are the blocks that are part of
  46. // evaluation of the expression, and `result_id` represents the result of
  47. // evaluating the expression. `block_ids` consists of all blocks that are
  48. // dominated by `block_ids.front()` and post-dominated by `block_ids.back()`,
  49. // and should be in lexical order. `result_id` will be in `block_ids.back()` or
  50. // some block that dominates it.
  51. //
  52. // `block_ids` cannot be empty. If it has a single element, then the region
  53. // should be used via a `SpliceBlock` inst. Otherwise, the region should be used
  54. // by branching to the entry block, and the last inst in the exit block will
  55. // likewise be a branch.
  56. struct ExprRegion {
  57. llvm::SmallVector<InstBlockId> block_ids;
  58. InstId result_id;
  59. };
  60. using ExprRegionStore = ValueStore<ExprRegionId, ExprRegion>;
  61. using CustomLayoutStore = BlockValueStore<CustomLayoutId, uint64_t>;
  62. // The semantic IR for a single file.
  63. class File : public Printable<File> {
  64. public:
  65. using IdentifiedFacetTypeStore =
  66. RelationalValueStore<FacetTypeInfoStore, IdentifiedFacetTypeId,
  67. IdentifiedFacetType>;
  68. // Starts a new file for Check::CheckParseTree.
  69. explicit File(const Parse::Tree* parse_tree, CheckIRId check_ir_id,
  70. const std::optional<Parse::Tree::PackagingDecl>& packaging_decl,
  71. SharedValueStores& value_stores, std::string filename);
  72. File(const File&) = delete;
  73. ~File();
  74. auto operator=(const File&) -> File& = delete;
  75. // Verifies that invariants of the semantics IR hold.
  76. auto Verify() const -> ErrorOr<Success>;
  77. // Prints the full IR. Allow omitting singletons so that changes to the list
  78. // of singletons won't churn golden test file content.
  79. auto Print(llvm::raw_ostream& out, bool include_singletons = false) const
  80. -> void {
  81. Yaml::Print(out, OutputYaml(include_singletons));
  82. }
  83. auto OutputYaml(bool include_singletons) const -> Yaml::OutputMapping;
  84. // Collects memory usage of members.
  85. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  86. -> void;
  87. // Returns array bound value from the bound instruction.
  88. // TODO: Move this function elsewhere.
  89. auto GetArrayBoundValue(InstId bound_id) const -> std::optional<uint64_t> {
  90. if (auto bound = insts().TryGetAs<IntValue>(
  91. constant_values().GetConstantInstId(bound_id))) {
  92. return ints().Get(bound->int_id).getZExtValue();
  93. }
  94. return std::nullopt;
  95. }
  96. // Gets the pointee type of the given type, which must be a pointer type.
  97. // TODO: Move this function elsewhere.
  98. auto GetPointeeType(TypeId pointer_id) const -> TypeId {
  99. return types().GetTypeIdForTypeInstId(
  100. types().GetAs<PointerType>(pointer_id).pointee_id);
  101. }
  102. // Returns true if this file is an `impl`.
  103. auto is_impl() -> bool {
  104. return import_irs().Get(ImportIRId::ApiForImpl).sem_ir != nullptr;
  105. }
  106. auto check_ir_id() const -> CheckIRId { return check_ir_id_; }
  107. auto package_id() const -> PackageNameId { return package_id_; }
  108. auto library_id() const -> LibraryNameId { return library_id_; }
  109. // Directly expose SharedValueStores members.
  110. auto identifiers() -> SharedValueStores::IdentifierStore& {
  111. return value_stores_->identifiers();
  112. }
  113. auto identifiers() const -> const SharedValueStores::IdentifierStore& {
  114. return value_stores_->identifiers();
  115. }
  116. auto ints() -> SharedValueStores::IntStore& { return value_stores_->ints(); }
  117. auto ints() const -> const SharedValueStores::IntStore& {
  118. return value_stores_->ints();
  119. }
  120. auto reals() -> SharedValueStores::RealStore& {
  121. return value_stores_->reals();
  122. }
  123. auto reals() const -> const SharedValueStores::RealStore& {
  124. return value_stores_->reals();
  125. }
  126. auto floats() -> SharedValueStores::FloatStore& {
  127. return value_stores_->floats();
  128. }
  129. auto floats() const -> const SharedValueStores::FloatStore& {
  130. return value_stores_->floats();
  131. }
  132. auto string_literal_values() -> SharedValueStores::StringLiteralStore& {
  133. return value_stores_->string_literal_values();
  134. }
  135. auto string_literal_values() const
  136. -> const SharedValueStores::StringLiteralStore& {
  137. return value_stores_->string_literal_values();
  138. }
  139. auto entity_names() -> EntityNameStore& { return entity_names_; }
  140. auto entity_names() const -> const EntityNameStore& { return entity_names_; }
  141. auto cpp_global_vars() -> CppGlobalVarStore& { return cpp_global_vars_; }
  142. auto cpp_global_vars() const -> const CppGlobalVarStore& {
  143. return cpp_global_vars_;
  144. }
  145. auto functions() -> FunctionStore& { return functions_; }
  146. auto functions() const -> const FunctionStore& { return functions_; }
  147. auto cpp_overload_sets() -> CppOverloadSetStore& {
  148. return cpp_overload_sets_;
  149. }
  150. auto cpp_overload_sets() const -> const CppOverloadSetStore& {
  151. return cpp_overload_sets_;
  152. }
  153. auto classes() -> ClassStore& { return classes_; }
  154. auto classes() const -> const ClassStore& { return classes_; }
  155. auto interfaces() -> InterfaceStore& { return interfaces_; }
  156. auto interfaces() const -> const InterfaceStore& { return interfaces_; }
  157. auto named_constraints() -> NamedConstraintStore& {
  158. return named_constraints_;
  159. }
  160. auto named_constraints() const -> const NamedConstraintStore& {
  161. return named_constraints_;
  162. }
  163. auto associated_constants() -> AssociatedConstantStore& {
  164. return associated_constants_;
  165. }
  166. auto associated_constants() const -> const AssociatedConstantStore& {
  167. return associated_constants_;
  168. }
  169. // TODO: Rename these to `facet_type_infos`.
  170. auto facet_types() -> FacetTypeInfoStore& { return facet_types_; }
  171. auto facet_types() const -> const FacetTypeInfoStore& { return facet_types_; }
  172. auto identified_facet_types() -> IdentifiedFacetTypeStore& {
  173. return identified_facet_types_;
  174. }
  175. auto identified_facet_types() const -> const IdentifiedFacetTypeStore& {
  176. return identified_facet_types_;
  177. }
  178. auto impls() -> ImplStore& { return impls_; }
  179. auto impls() const -> const ImplStore& { return impls_; }
  180. auto specific_interfaces() -> SpecificInterfaceStore& {
  181. return specific_interfaces_;
  182. }
  183. auto specific_interfaces() const -> const SpecificInterfaceStore& {
  184. return specific_interfaces_;
  185. }
  186. auto generics() -> GenericStore& { return generics_; }
  187. auto generics() const -> const GenericStore& { return generics_; }
  188. auto specifics() -> SpecificStore& { return specifics_; }
  189. auto specifics() const -> const SpecificStore& { return specifics_; }
  190. auto import_irs() -> ImportIRStore& { return import_irs_; }
  191. auto import_irs() const -> const ImportIRStore& { return import_irs_; }
  192. auto import_ir_insts() -> ImportIRInstStore& { return import_ir_insts_; }
  193. auto import_ir_insts() const -> const ImportIRInstStore& {
  194. return import_ir_insts_;
  195. }
  196. auto import_cpps() -> ImportCppStore& { return import_cpps_; }
  197. auto import_cpps() const -> const ImportCppStore& { return import_cpps_; }
  198. auto clang_ast_unit() -> clang::ASTUnit* { return clang_ast_unit_; }
  199. auto clang_ast_unit() const -> const clang::ASTUnit* {
  200. return clang_ast_unit_;
  201. }
  202. // TODO: When the AST can be created before creating `File`, initialize the
  203. // pointer in the constructor and remove this function. This is part of
  204. // https://github.com/carbon-language/carbon-lang/issues/4666
  205. auto set_clang_ast_unit(clang::ASTUnit* clang_ast_unit) -> void;
  206. auto clang_mangle_context() -> clang::MangleContext* {
  207. return clang_mangle_context_.get();
  208. }
  209. auto clang_decls() -> ClangDeclStore& { return clang_decls_; }
  210. auto clang_decls() const -> const ClangDeclStore& { return clang_decls_; }
  211. auto names() const -> NameStoreWrapper {
  212. return NameStoreWrapper(&identifiers());
  213. }
  214. auto name_scopes() -> NameScopeStore& { return name_scopes_; }
  215. auto name_scopes() const -> const NameScopeStore& { return name_scopes_; }
  216. auto struct_type_fields() -> StructTypeFieldsStore& {
  217. return struct_type_fields_;
  218. }
  219. auto struct_type_fields() const -> const StructTypeFieldsStore& {
  220. return struct_type_fields_;
  221. }
  222. auto custom_layouts() -> CustomLayoutStore& { return custom_layouts_; }
  223. auto custom_layouts() const -> const CustomLayoutStore& {
  224. return custom_layouts_;
  225. }
  226. auto types() -> TypeStore& { return types_; }
  227. auto types() const -> const TypeStore& { return types_; }
  228. auto insts() -> InstStore& { return insts_; }
  229. auto insts() const -> const InstStore& { return insts_; }
  230. auto vtables() -> VtableStore& { return vtables_; }
  231. auto vtables() const -> const VtableStore& { return vtables_; }
  232. auto constant_values() -> ConstantValueStore& { return constant_values_; }
  233. auto constant_values() const -> const ConstantValueStore& {
  234. return constant_values_;
  235. }
  236. auto inst_blocks() -> InstBlockStore& { return inst_blocks_; }
  237. auto inst_blocks() const -> const InstBlockStore& { return inst_blocks_; }
  238. auto constants() -> ConstantStore& { return constants_; }
  239. auto constants() const -> const ConstantStore& { return constants_; }
  240. auto expr_regions() -> ExprRegionStore& { return expr_regions_; }
  241. auto expr_regions() const -> const ExprRegionStore& { return expr_regions_; }
  242. using ClangSourceLocStore =
  243. ValueStore<ClangSourceLocId, clang::SourceLocation>;
  244. auto clang_source_locs() -> ClangSourceLocStore& {
  245. return clang_source_locs_;
  246. }
  247. auto clang_source_locs() const -> const ClangSourceLocStore& {
  248. return clang_source_locs_;
  249. }
  250. auto top_inst_block_id() const -> InstBlockId { return top_inst_block_id_; }
  251. auto set_top_inst_block_id(InstBlockId block_id) -> void {
  252. top_inst_block_id_ = block_id;
  253. }
  254. auto global_ctor_id() const -> FunctionId { return global_ctor_id_; }
  255. auto set_global_ctor_id(FunctionId function_id) -> void {
  256. global_ctor_id_ = function_id;
  257. }
  258. // Returns true if there were errors creating the semantics IR.
  259. auto has_errors() const -> bool { return has_errors_; }
  260. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  261. auto filename() const -> llvm::StringRef { return filename_; }
  262. auto parse_tree() const -> const Parse::Tree& { return *parse_tree_; }
  263. private:
  264. const Parse::Tree* parse_tree_;
  265. // True if parts of the IR may be invalid.
  266. bool has_errors_ = false;
  267. // The file's ID.
  268. CheckIRId check_ir_id_;
  269. // The file's package.
  270. PackageNameId package_id_ = PackageNameId::None;
  271. // The file's library.
  272. LibraryNameId library_id_ = LibraryNameId::None;
  273. // Shared, compile-scoped values.
  274. SharedValueStores* value_stores_;
  275. // Slab allocator, used to allocate instruction and type blocks.
  276. llvm::BumpPtrAllocator allocator_;
  277. // The associated filename.
  278. // TODO: If SemIR starts linking back to tokens, reuse its filename.
  279. std::string filename_;
  280. // Storage for EntityNames.
  281. EntityNameStore entity_names_;
  282. // For imported C++ global variables, the Clang decl to use for mangling.
  283. CppGlobalVarStore cpp_global_vars_;
  284. // Storage for callable objects.
  285. FunctionStore functions_;
  286. // Storage for CppOverloadSet.
  287. CppOverloadSetStore cpp_overload_sets_;
  288. // Storage for classes.
  289. ClassStore classes_;
  290. // Storage for interfaces.
  291. InterfaceStore interfaces_;
  292. // Storage for named constraints.
  293. NamedConstraintStore named_constraints_;
  294. // Storage for associated constants.
  295. AssociatedConstantStore associated_constants_;
  296. // Storage for facet types.
  297. FacetTypeInfoStore facet_types_;
  298. // Storage for identified facet types.
  299. IdentifiedFacetTypeStore identified_facet_types_;
  300. // Storage for impls.
  301. ImplStore impls_;
  302. // Storage for specific interfaces, which are an individual unit of impl
  303. // lookup for a single interface.
  304. SpecificInterfaceStore specific_interfaces_;
  305. // Storage for generics.
  306. GenericStore generics_;
  307. // Storage for specifics.
  308. SpecificStore specifics_;
  309. // Related IRs. There are some fixed entries at the start; see ImportIRId.
  310. ImportIRStore import_irs_;
  311. // Related IR instructions. These are created for LocIds for instructions
  312. // that are import-related.
  313. ImportIRInstStore import_ir_insts_;
  314. // List of Cpp imports.
  315. ImportCppStore import_cpps_;
  316. // The Clang AST to use when looking up `Cpp` names. Null if there are no
  317. // `Cpp` imports.
  318. clang::ASTUnit* clang_ast_unit_ = nullptr;
  319. // The Clang mangle context for the target in the ASTContext. Initialized
  320. // together with `clang_ast_unit_`.
  321. std::unique_ptr<clang::MangleContext> clang_mangle_context_;
  322. // Clang AST declarations pointing to the AST and their mapped Carbon
  323. // instructions. When calling `Lookup()`, `inst_id` is ignored. `Add()` will
  324. // not add multiple entries with the same `decl` and different `inst_id`.
  325. ClangDeclStore clang_decls_;
  326. // All instructions. The first entries will always be the singleton
  327. // instructions.
  328. InstStore insts_;
  329. VtableStore vtables_;
  330. // Storage for name scopes.
  331. NameScopeStore name_scopes_ = NameScopeStore(this);
  332. // Constant values for instructions.
  333. ConstantValueStore constant_values_;
  334. // Instruction blocks within the IR. These reference entries in
  335. // insts_. Storage for the data is provided by allocator_.
  336. InstBlockStore inst_blocks_;
  337. // The top instruction block ID.
  338. InstBlockId top_inst_block_id_ = InstBlockId::None;
  339. // The global constructor function id.
  340. FunctionId global_ctor_id_ = FunctionId::None;
  341. // Storage for instructions that represent computed global constants, such as
  342. // types.
  343. ConstantStore constants_;
  344. // Storage for StructTypeField lists.
  345. StructTypeFieldsStore struct_type_fields_;
  346. // Storage for custom layouts.
  347. CustomLayoutStore custom_layouts_ = CustomLayoutStore(allocator_);
  348. // Descriptions of types used in this file.
  349. TypeStore types_ = TypeStore(this);
  350. // Single-entry/single-exit regions that are referenced as units, e.g. because
  351. // they represent expressions.
  352. ExprRegionStore expr_regions_;
  353. // C++ source locations for C++ interop.
  354. ClangSourceLocStore clang_source_locs_;
  355. };
  356. } // namespace Carbon::SemIR
  357. #endif // CARBON_TOOLCHAIN_SEM_IR_FILE_H_