file.h 14 KB

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