file.h 16 KB

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