file.h 16 KB

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