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 "llvm/ADT/SmallVector.h"
  7. #include "llvm/ADT/iterator_range.h"
  8. #include "llvm/Support/Allocator.h"
  9. #include "llvm/Support/FormatVariadic.h"
  10. #include "toolchain/base/value_store.h"
  11. #include "toolchain/base/yaml.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/type_info.h"
  14. #include "toolchain/sem_ir/value_stores.h"
  15. namespace Carbon::SemIR {
  16. struct BindNameInfo : public Printable<BindNameInfo> {
  17. auto Print(llvm::raw_ostream& out) const -> void {
  18. out << "{name: " << name_id << ", enclosing_scope: " << enclosing_scope_id
  19. << "}";
  20. }
  21. NameId name_id;
  22. NameScopeId enclosing_scope_id;
  23. };
  24. // A function.
  25. struct Function : public Printable<Function> {
  26. auto Print(llvm::raw_ostream& out) const -> void {
  27. out << "{name: " << name_id << ", "
  28. << "param_refs: " << param_refs_id;
  29. if (return_type_id.is_valid()) {
  30. out << ", return_type: " << return_type_id;
  31. }
  32. if (return_slot_id.is_valid()) {
  33. out << ", return_slot: " << return_slot_id;
  34. }
  35. if (!body_block_ids.empty()) {
  36. out << llvm::formatv(
  37. ", body: [{0}]",
  38. llvm::make_range(body_block_ids.begin(), body_block_ids.end()));
  39. }
  40. out << "}";
  41. }
  42. // Given a parameter reference instruction from `param_refs_id` or
  43. // `implicit_param_refs_id`, returns the corresponding `Param` instruction
  44. // and its ID.
  45. static auto GetParamFromParamRefId(const File& sem_ir, InstId param_ref_id)
  46. -> std::pair<InstId, Param>;
  47. // The function name.
  48. NameId name_id;
  49. // The first declaration of the function. This is a FunctionDecl.
  50. InstId decl_id = InstId::Invalid;
  51. // The definition, if the function has been defined or is currently being
  52. // defined. This is a FunctionDecl.
  53. InstId definition_id = InstId::Invalid;
  54. // A block containing a single reference instruction per implicit parameter.
  55. InstBlockId implicit_param_refs_id;
  56. // A block containing a single reference instruction per parameter.
  57. InstBlockId param_refs_id;
  58. // The return type. This will be invalid if the return type wasn't specified.
  59. TypeId return_type_id;
  60. // The storage for the return value, which is a reference expression whose
  61. // type is the return type of the function. Will be invalid if the function
  62. // doesn't have a return slot. If this is valid, a call to the function is
  63. // expected to have an additional final argument corresponding to the return
  64. // slot.
  65. InstId return_slot_id;
  66. // A list of the statically reachable code blocks in the body of the
  67. // function, in lexical order. The first block is the entry block. This will
  68. // be empty for declarations that don't have a visible definition.
  69. llvm::SmallVector<InstBlockId> body_block_ids = {};
  70. };
  71. // A class.
  72. struct Class : public Printable<Class> {
  73. enum InheritanceKind : int8_t {
  74. // `abstract class`
  75. Abstract,
  76. // `base class`
  77. Base,
  78. // `class`
  79. Final,
  80. };
  81. auto Print(llvm::raw_ostream& out) const -> void {
  82. out << "{name: " << name_id;
  83. out << "}";
  84. }
  85. // Determines whether this class has been fully defined. This is false until
  86. // we reach the `}` of the class definition.
  87. auto is_defined() const -> bool { return object_repr_id.is_valid(); }
  88. // The following members always have values, and do not change throughout the
  89. // lifetime of the class.
  90. // The class name.
  91. NameId name_id;
  92. // The class type, which is the type of `Self` in the class definition.
  93. TypeId self_type_id;
  94. // The first declaration of the class. This is a ClassDecl.
  95. InstId decl_id = InstId::Invalid;
  96. // The kind of inheritance that this class supports.
  97. // TODO: The rules here are not yet decided. See #3384.
  98. InheritanceKind inheritance_kind;
  99. // The following members are set at the `{` of the class definition.
  100. // The definition of the class. This is a ClassDecl.
  101. InstId definition_id = InstId::Invalid;
  102. // The class scope.
  103. NameScopeId scope_id = NameScopeId::Invalid;
  104. // The first block of the class body.
  105. // TODO: Handle control flow in the class body, such as if-expressions.
  106. InstBlockId body_block_id = InstBlockId::Invalid;
  107. // The following members are accumulated throughout the class definition.
  108. // The base class declaration. Invalid if the class has no base class. This is
  109. // a BaseDecl instruction.
  110. InstId base_id = InstId::Invalid;
  111. // The following members are set at the `}` of the class definition.
  112. // The object representation type to use for this class. This is valid once
  113. // the class is defined.
  114. TypeId object_repr_id = TypeId::Invalid;
  115. };
  116. // An interface.
  117. struct Interface : public Printable<Interface> {
  118. auto Print(llvm::raw_ostream& out) const -> void {
  119. out << "{name: " << name_id;
  120. out << "}";
  121. }
  122. // Determines whether this interface has been fully defined. This is false
  123. // until we reach the `}` of the interface definition.
  124. auto is_defined() const -> bool { return defined; }
  125. // The following members always have values, and do not change throughout the
  126. // lifetime of the interface.
  127. // The interface name.
  128. NameId name_id;
  129. // TODO: TypeId self_type_id;
  130. // The first declaration of the interface. This is a InterfaceDecl.
  131. InstId decl_id = InstId::Invalid;
  132. // The following members are set at the `{` of the interface definition.
  133. // The definition of the interface. This is a InterfaceDecl.
  134. InstId definition_id = InstId::Invalid;
  135. // The interface scope.
  136. NameScopeId scope_id = NameScopeId::Invalid;
  137. // The first block of the interface body.
  138. // TODO: Handle control flow in the interface body, such as if-expressions.
  139. InstBlockId body_block_id = InstBlockId::Invalid;
  140. // The following members are set at the `}` of the class definition.
  141. bool defined = true;
  142. };
  143. // Provides semantic analysis on a Parse::Tree.
  144. class File : public Printable<File> {
  145. public:
  146. // Produces a file for the builtins.
  147. explicit File(SharedValueStores& value_stores);
  148. // Starts a new file for Check::CheckParseTree. Builtins are required.
  149. explicit File(SharedValueStores& value_stores, std::string filename,
  150. const File* builtins);
  151. File(const File&) = delete;
  152. auto operator=(const File&) -> File& = delete;
  153. // Verifies that invariants of the semantics IR hold.
  154. auto Verify() const -> ErrorOr<Success>;
  155. // Prints the full IR. Allow omitting builtins so that unrelated changes are
  156. // less likely to alter test golden files.
  157. // TODO: In the future, the things to print may change, for example by adding
  158. // preludes. We may then want the ability to omit other things similar to
  159. // builtins.
  160. auto Print(llvm::raw_ostream& out, bool include_builtins = false) const
  161. -> void {
  162. Yaml::Print(out, OutputYaml(include_builtins));
  163. }
  164. auto OutputYaml(bool include_builtins) const -> Yaml::OutputMapping;
  165. // Returns array bound value from the bound instruction.
  166. auto GetArrayBoundValue(InstId bound_id) const -> uint64_t {
  167. return ints()
  168. .Get(insts().GetAs<IntLiteral>(bound_id).int_id)
  169. .getZExtValue();
  170. }
  171. // Marks a type as complete, and sets its value representation.
  172. auto CompleteType(TypeId object_type_id, ValueRepr value_repr) -> void {
  173. if (object_type_id.index < 0) {
  174. // We already know our builtin types are complete.
  175. return;
  176. }
  177. CARBON_CHECK(types().Get(object_type_id).value_repr.kind ==
  178. ValueRepr::Unknown)
  179. << "Type " << object_type_id << " completed more than once";
  180. types().Get(object_type_id).value_repr = value_repr;
  181. complete_types_.push_back(object_type_id);
  182. }
  183. // Gets the pointee type of the given type, which must be a pointer type.
  184. auto GetPointeeType(TypeId pointer_id) const -> TypeId {
  185. return types().GetAs<PointerType>(pointer_id).pointee_id;
  186. }
  187. // Produces a string version of a type.
  188. auto StringifyType(TypeId type_id) const -> std::string;
  189. // Same as `StringifyType`, but starting with an instruction representing a
  190. // type expression rather than a canonical type.
  191. auto StringifyTypeExpr(InstId outer_inst_id) const -> std::string;
  192. // Directly expose SharedValueStores members.
  193. auto identifiers() -> StringStoreWrapper<IdentifierId>& {
  194. return value_stores_->identifiers();
  195. }
  196. auto identifiers() const -> const StringStoreWrapper<IdentifierId>& {
  197. return value_stores_->identifiers();
  198. }
  199. auto ints() -> ValueStore<IntId>& { return value_stores_->ints(); }
  200. auto ints() const -> const ValueStore<IntId>& {
  201. return value_stores_->ints();
  202. }
  203. auto reals() -> ValueStore<RealId>& { return value_stores_->reals(); }
  204. auto reals() const -> const ValueStore<RealId>& {
  205. return value_stores_->reals();
  206. }
  207. auto string_literal_values() -> StringStoreWrapper<StringLiteralValueId>& {
  208. return value_stores_->string_literal_values();
  209. }
  210. auto string_literal_values() const
  211. -> const StringStoreWrapper<StringLiteralValueId>& {
  212. return value_stores_->string_literal_values();
  213. }
  214. auto bind_names() -> ValueStore<BindNameId>& { return bind_names_; }
  215. auto bind_names() const -> const ValueStore<BindNameId>& {
  216. return bind_names_;
  217. }
  218. auto functions() -> ValueStore<FunctionId>& { return functions_; }
  219. auto functions() const -> const ValueStore<FunctionId>& { return functions_; }
  220. auto classes() -> ValueStore<ClassId>& { return classes_; }
  221. auto classes() const -> const ValueStore<ClassId>& { return classes_; }
  222. auto interfaces() -> ValueStore<InterfaceId>& { return interfaces_; }
  223. auto interfaces() const -> const ValueStore<InterfaceId>& {
  224. return interfaces_;
  225. }
  226. auto cross_ref_irs() -> ValueStore<CrossRefIRId>& { return cross_ref_irs_; }
  227. auto cross_ref_irs() const -> const ValueStore<CrossRefIRId>& {
  228. return cross_ref_irs_;
  229. }
  230. auto names() const -> NameStoreWrapper {
  231. return NameStoreWrapper(&identifiers());
  232. }
  233. auto name_scopes() -> NameScopeStore& { return name_scopes_; }
  234. auto name_scopes() const -> const NameScopeStore& { return name_scopes_; }
  235. auto types() -> TypeStore& { return types_; }
  236. auto types() const -> const TypeStore& { return types_; }
  237. auto type_blocks() -> BlockValueStore<TypeBlockId>& { return type_blocks_; }
  238. auto type_blocks() const -> const BlockValueStore<TypeBlockId>& {
  239. return type_blocks_;
  240. }
  241. auto insts() -> InstStore& { return insts_; }
  242. auto insts() const -> const InstStore& { return insts_; }
  243. auto inst_blocks() -> InstBlockStore& { return inst_blocks_; }
  244. auto inst_blocks() const -> const InstBlockStore& { return inst_blocks_; }
  245. auto constants() -> ConstantStore& { return constants_; }
  246. auto constants() const -> const ConstantStore& { return constants_; }
  247. // A list of types that were completed in this file, in the order in which
  248. // they were completed. Earlier types in this list cannot contain instances of
  249. // later types.
  250. auto complete_types() const -> llvm::ArrayRef<TypeId> {
  251. return complete_types_;
  252. }
  253. auto top_inst_block_id() const -> InstBlockId { return top_inst_block_id_; }
  254. auto set_top_inst_block_id(InstBlockId block_id) -> void {
  255. top_inst_block_id_ = block_id;
  256. }
  257. // Returns true if there were errors creating the semantics IR.
  258. auto has_errors() const -> bool { return has_errors_; }
  259. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  260. auto filename() const -> llvm::StringRef { return filename_; }
  261. private:
  262. bool has_errors_ = false;
  263. // Shared, compile-scoped values.
  264. SharedValueStores* value_stores_;
  265. // Slab allocator, used to allocate instruction and type blocks.
  266. llvm::BumpPtrAllocator allocator_;
  267. // The associated filename.
  268. // TODO: If SemIR starts linking back to tokens, reuse its filename.
  269. std::string filename_;
  270. // Storage for bind names.
  271. ValueStore<BindNameId> bind_names_;
  272. // Storage for callable objects.
  273. ValueStore<FunctionId> functions_;
  274. // Storage for classes.
  275. ValueStore<ClassId> classes_;
  276. // Storage for interfaces.
  277. ValueStore<InterfaceId> interfaces_;
  278. // Related IRs. There will always be at least 2 entries, the builtin IR (used
  279. // for references of builtins) followed by the current IR (used for references
  280. // crossing instruction blocks).
  281. ValueStore<CrossRefIRId> cross_ref_irs_;
  282. // Storage for name scopes.
  283. NameScopeStore name_scopes_;
  284. // Type blocks within the IR. These reference entries in types_. Storage for
  285. // the data is provided by allocator_.
  286. BlockValueStore<TypeBlockId> type_blocks_;
  287. // All instructions. The first entries will always be cross-references to
  288. // builtins, at indices matching BuiltinKind ordering.
  289. InstStore insts_;
  290. // Instruction blocks within the IR. These reference entries in
  291. // insts_. Storage for the data is provided by allocator_.
  292. InstBlockStore inst_blocks_;
  293. // The top instruction block ID.
  294. InstBlockId top_inst_block_id_ = InstBlockId::Invalid;
  295. // Storage for instructions that represent computed global constants, such as
  296. // types.
  297. ConstantStore constants_;
  298. // Descriptions of types used in this file.
  299. TypeStore types_ = TypeStore(&insts_);
  300. // Types that were completed in this file.
  301. llvm::SmallVector<TypeId> complete_types_;
  302. };
  303. // The expression category of a sem_ir instruction. See /docs/design/values.md
  304. // for details.
  305. enum class ExprCategory : int8_t {
  306. // This instruction does not correspond to an expression, and as such has no
  307. // category.
  308. NotExpr,
  309. // The category of this instruction is not known due to an error.
  310. Error,
  311. // This instruction represents a value expression.
  312. Value,
  313. // This instruction represents a durable reference expression, that denotes an
  314. // object that outlives the current full expression context.
  315. DurableRef,
  316. // This instruction represents an ephemeral reference expression, that denotes
  317. // an
  318. // object that does not outlive the current full expression context.
  319. EphemeralRef,
  320. // This instruction represents an initializing expression, that describes how
  321. // to
  322. // initialize an object.
  323. Initializing,
  324. // This instruction represents a syntactic combination of expressions that are
  325. // permitted to have different expression categories. This is used for tuple
  326. // and struct literals, where the subexpressions for different elements can
  327. // have different categories.
  328. Mixed,
  329. Last = Mixed
  330. };
  331. // Returns the expression category for an instruction.
  332. auto GetExprCategory(const File& file, InstId inst_id) -> ExprCategory;
  333. // Returns information about the value representation to use for a type.
  334. inline auto GetValueRepr(const File& file, TypeId type_id) -> ValueRepr {
  335. return file.types().GetValueRepr(type_id);
  336. }
  337. // The initializing representation to use when returning by value.
  338. struct InitRepr {
  339. enum Kind : int8_t {
  340. // The type has no initializing representation. This is used for empty
  341. // types, where no initialization is necessary.
  342. None,
  343. // An initializing expression produces an object representation by value,
  344. // which is copied into the initialized object.
  345. ByCopy,
  346. // An initializing expression takes a location as input, which is
  347. // initialized as a side effect of evaluating the expression.
  348. InPlace,
  349. // TODO: Consider adding a kind where the expression takes an advisory
  350. // location and returns a value plus an indicator of whether the location
  351. // was actually initialized.
  352. };
  353. // The kind of initializing representation used by this type.
  354. Kind kind;
  355. // Returns whether a return slot is used when returning this type.
  356. auto has_return_slot() const -> bool { return kind == InPlace; }
  357. };
  358. // Returns information about the initializing representation to use for a type.
  359. auto GetInitRepr(const File& file, TypeId type_id) -> InitRepr;
  360. } // namespace Carbon::SemIR
  361. #endif // CARBON_TOOLCHAIN_SEM_IR_FILE_H_