file.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 clang_ast_unit() -> clang::ASTUnit* { return clang_ast_unit_; }
  197. auto clang_ast_unit() const -> const clang::ASTUnit* {
  198. return clang_ast_unit_;
  199. }
  200. // TODO: When the AST can be created before creating `File`, initialize the
  201. // pointer in the constructor and remove this function. This is part of
  202. // https://github.com/carbon-language/carbon-lang/issues/4666
  203. auto set_clang_ast_unit(clang::ASTUnit* clang_ast_unit) -> void;
  204. auto clang_mangle_context() -> clang::MangleContext* {
  205. return clang_mangle_context_.get();
  206. }
  207. auto clang_decls() -> ClangDeclStore& { return clang_decls_; }
  208. auto clang_decls() const -> const ClangDeclStore& { return clang_decls_; }
  209. auto names() const -> NameStoreWrapper {
  210. return NameStoreWrapper(&identifiers());
  211. }
  212. auto name_scopes() -> NameScopeStore& { return name_scopes_; }
  213. auto name_scopes() const -> const NameScopeStore& { return name_scopes_; }
  214. auto struct_type_fields() -> StructTypeFieldsStore& {
  215. return struct_type_fields_;
  216. }
  217. auto struct_type_fields() const -> const StructTypeFieldsStore& {
  218. return struct_type_fields_;
  219. }
  220. auto custom_layouts() -> CustomLayoutStore& { return custom_layouts_; }
  221. auto custom_layouts() const -> const CustomLayoutStore& {
  222. return custom_layouts_;
  223. }
  224. auto types() -> TypeStore& { return types_; }
  225. auto types() const -> const TypeStore& { return types_; }
  226. auto insts() -> InstStore& { return insts_; }
  227. auto insts() const -> const InstStore& { return insts_; }
  228. auto vtables() -> VtableStore& { return vtables_; }
  229. auto vtables() const -> const VtableStore& { return vtables_; }
  230. auto constant_values() -> ConstantValueStore& { return constant_values_; }
  231. auto constant_values() const -> const ConstantValueStore& {
  232. return constant_values_;
  233. }
  234. auto inst_blocks() -> InstBlockStore& { return inst_blocks_; }
  235. auto inst_blocks() const -> const InstBlockStore& { return inst_blocks_; }
  236. auto constants() -> ConstantStore& { return constants_; }
  237. auto constants() const -> const ConstantStore& { return constants_; }
  238. auto expr_regions() -> ExprRegionStore& { return expr_regions_; }
  239. auto expr_regions() const -> const ExprRegionStore& { return expr_regions_; }
  240. using ClangSourceLocStore =
  241. ValueStore<ClangSourceLocId, clang::SourceLocation>;
  242. auto clang_source_locs() -> ClangSourceLocStore& {
  243. return clang_source_locs_;
  244. }
  245. auto clang_source_locs() const -> const ClangSourceLocStore& {
  246. return clang_source_locs_;
  247. }
  248. auto top_inst_block_id() const -> InstBlockId { return top_inst_block_id_; }
  249. auto set_top_inst_block_id(InstBlockId block_id) -> void {
  250. top_inst_block_id_ = block_id;
  251. }
  252. auto global_ctor_id() const -> FunctionId { return global_ctor_id_; }
  253. auto set_global_ctor_id(FunctionId function_id) -> void {
  254. global_ctor_id_ = function_id;
  255. }
  256. // Returns true if there were errors creating the semantics IR.
  257. auto has_errors() const -> bool { return has_errors_; }
  258. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  259. auto filename() const -> llvm::StringRef { return filename_; }
  260. auto parse_tree() const -> const Parse::Tree& { return *parse_tree_; }
  261. private:
  262. const Parse::Tree* parse_tree_;
  263. // True if parts of the IR may be invalid.
  264. bool has_errors_ = false;
  265. // The file's ID.
  266. CheckIRId check_ir_id_;
  267. // The file's package.
  268. PackageNameId package_id_ = PackageNameId::None;
  269. // The file's library.
  270. LibraryNameId library_id_ = LibraryNameId::None;
  271. // Shared, compile-scoped values.
  272. SharedValueStores* value_stores_;
  273. // Slab allocator, used to allocate instruction and type blocks.
  274. llvm::BumpPtrAllocator allocator_;
  275. // The associated filename.
  276. // TODO: If SemIR starts linking back to tokens, reuse its filename.
  277. std::string filename_;
  278. // Storage for EntityNames.
  279. EntityNameStore entity_names_;
  280. // For imported C++ global variables, the Clang decl to use for mangling.
  281. CppGlobalVarStore cpp_global_vars_;
  282. // Storage for callable objects.
  283. FunctionStore functions_;
  284. // Storage for CppOverloadSet.
  285. CppOverloadSetStore cpp_overload_sets_;
  286. // Storage for classes.
  287. ClassStore classes_;
  288. // Storage for interfaces.
  289. InterfaceStore interfaces_;
  290. // Storage for named constraints.
  291. NamedConstraintStore named_constraints_;
  292. // Storage for associated constants.
  293. AssociatedConstantStore associated_constants_;
  294. // Storage for facet types.
  295. FacetTypeInfoStore facet_types_;
  296. // Storage for identified facet types.
  297. IdentifiedFacetTypeStore identified_facet_types_;
  298. // Storage for impls.
  299. ImplStore impls_;
  300. // Storage for specific interfaces, which are an individual unit of impl
  301. // lookup for a single interface.
  302. SpecificInterfaceStore specific_interfaces_;
  303. // Storage for generics.
  304. GenericStore generics_;
  305. // Storage for specifics.
  306. SpecificStore specifics_;
  307. // Related IRs. There are some fixed entries at the start; see ImportIRId.
  308. ImportIRStore import_irs_;
  309. // Related IR instructions. These are created for LocIds for instructions
  310. // that are import-related.
  311. ImportIRInstStore import_ir_insts_;
  312. // The Clang AST to use when looking up `Cpp` names. Null if there are no
  313. // `Cpp` imports.
  314. clang::ASTUnit* clang_ast_unit_ = nullptr;
  315. // The Clang mangle context for the target in the ASTContext. Initialized
  316. // together with `clang_ast_unit_`.
  317. std::unique_ptr<clang::MangleContext> clang_mangle_context_;
  318. // Clang AST declarations pointing to the AST and their mapped Carbon
  319. // instructions. When calling `Lookup()`, `inst_id` is ignored. `Add()` will
  320. // not add multiple entries with the same `decl` and different `inst_id`.
  321. ClangDeclStore clang_decls_;
  322. // All instructions. The first entries will always be the singleton
  323. // instructions.
  324. InstStore insts_;
  325. VtableStore vtables_;
  326. // Storage for name scopes.
  327. NameScopeStore name_scopes_ = NameScopeStore(this);
  328. // Constant values for instructions.
  329. ConstantValueStore constant_values_;
  330. // Instruction blocks within the IR. These reference entries in
  331. // insts_. Storage for the data is provided by allocator_.
  332. InstBlockStore inst_blocks_;
  333. // The top instruction block ID.
  334. InstBlockId top_inst_block_id_ = InstBlockId::None;
  335. // The global constructor function id.
  336. FunctionId global_ctor_id_ = FunctionId::None;
  337. // Storage for instructions that represent computed global constants, such as
  338. // types.
  339. ConstantStore constants_;
  340. // Storage for StructTypeField lists.
  341. StructTypeFieldsStore struct_type_fields_;
  342. // Storage for custom layouts.
  343. CustomLayoutStore custom_layouts_ = CustomLayoutStore(allocator_);
  344. // Descriptions of types used in this file.
  345. TypeStore types_ = TypeStore(this);
  346. // Single-entry/single-exit regions that are referenced as units, e.g. because
  347. // they represent expressions.
  348. ExprRegionStore expr_regions_;
  349. // C++ source locations for C++ interop.
  350. ClangSourceLocStore clang_source_locs_;
  351. };
  352. } // namespace Carbon::SemIR
  353. #endif // CARBON_TOOLCHAIN_SEM_IR_FILE_H_