file.h 16 KB

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