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