semantics_node.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  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_SEMANTICS_SEMANTICS_NODE_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_
  6. #include <cstdint>
  7. #include "common/check.h"
  8. #include "common/ostream.h"
  9. #include "toolchain/parser/parse_tree.h"
  10. #include "toolchain/semantics/semantics_builtin_kind.h"
  11. #include "toolchain/semantics/semantics_node_kind.h"
  12. namespace Carbon {
  13. // The ID of a node.
  14. struct SemanticsNodeId : public IndexBase {
  15. // An explicitly invalid node ID.
  16. static const SemanticsNodeId Invalid;
  17. // Builtin node IDs.
  18. #define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \
  19. static const SemanticsNodeId Builtin##Name;
  20. #include "toolchain/semantics/semantics_builtin_kind.def"
  21. using IndexBase::IndexBase;
  22. auto Print(llvm::raw_ostream& out) const -> void {
  23. out << "node";
  24. if (!is_valid()) {
  25. IndexBase::Print(out);
  26. } else if (index < SemanticsBuiltinKind::ValidCount) {
  27. out << SemanticsBuiltinKind::FromInt(index);
  28. } else {
  29. // Use the `+` as a small reminder that this is a delta, rather than an
  30. // absolute index.
  31. out << "+" << index - SemanticsBuiltinKind::ValidCount;
  32. }
  33. }
  34. };
  35. constexpr SemanticsNodeId SemanticsNodeId::Invalid =
  36. SemanticsNodeId(SemanticsNodeId::InvalidIndex);
  37. // Uses the cross-reference node ID for a builtin. This relies on SemanticsIR
  38. // guarantees for builtin cross-reference placement.
  39. #define CARBON_SEMANTICS_BUILTIN_KIND_NAME(Name) \
  40. constexpr SemanticsNodeId SemanticsNodeId::Builtin##Name = \
  41. SemanticsNodeId(SemanticsBuiltinKind::Name.AsInt());
  42. #include "toolchain/semantics/semantics_builtin_kind.def"
  43. // The ID of a function.
  44. struct SemanticsFunctionId : public IndexBase {
  45. using IndexBase::IndexBase;
  46. auto Print(llvm::raw_ostream& out) const -> void {
  47. out << "function";
  48. IndexBase::Print(out);
  49. }
  50. };
  51. // The ID of a cross-referenced IR.
  52. struct SemanticsCrossReferenceIRId : public IndexBase {
  53. using IndexBase::IndexBase;
  54. auto Print(llvm::raw_ostream& out) const -> void {
  55. out << "ir";
  56. IndexBase::Print(out);
  57. }
  58. };
  59. // A boolean value.
  60. struct SemanticsBoolValue : public IndexBase {
  61. using IndexBase::IndexBase;
  62. auto Print(llvm::raw_ostream& out) const -> void {
  63. switch (index) {
  64. case 0:
  65. out << "false";
  66. break;
  67. case 1:
  68. out << "true";
  69. break;
  70. default:
  71. CARBON_FATAL() << "Invalid bool value " << index;
  72. }
  73. }
  74. };
  75. // The ID of an integer literal.
  76. struct SemanticsIntegerLiteralId : public IndexBase {
  77. using IndexBase::IndexBase;
  78. auto Print(llvm::raw_ostream& out) const -> void {
  79. out << "int";
  80. IndexBase::Print(out);
  81. }
  82. };
  83. // The ID of a node block.
  84. struct SemanticsNodeBlockId : public IndexBase {
  85. // All SemanticsIR instances must provide the 0th node block as empty.
  86. static const SemanticsNodeBlockId Empty;
  87. // An explicitly invalid ID.
  88. static const SemanticsNodeBlockId Invalid;
  89. using IndexBase::IndexBase;
  90. auto Print(llvm::raw_ostream& out) const -> void {
  91. out << "block";
  92. IndexBase::Print(out);
  93. }
  94. };
  95. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Empty =
  96. SemanticsNodeBlockId(0);
  97. constexpr SemanticsNodeBlockId SemanticsNodeBlockId::Invalid =
  98. SemanticsNodeBlockId(SemanticsNodeBlockId::InvalidIndex);
  99. // The ID of a real literal.
  100. struct SemanticsRealLiteralId : public IndexBase {
  101. using IndexBase::IndexBase;
  102. auto Print(llvm::raw_ostream& out) const -> void {
  103. out << "real";
  104. IndexBase::Print(out);
  105. }
  106. };
  107. // The ID of a string.
  108. struct SemanticsStringId : public IndexBase {
  109. using IndexBase::IndexBase;
  110. auto Print(llvm::raw_ostream& out) const -> void {
  111. out << "str";
  112. IndexBase::Print(out);
  113. }
  114. };
  115. // The ID of a node block.
  116. struct SemanticsTypeId : public IndexBase {
  117. // The builtin TypeType.
  118. static const SemanticsTypeId TypeType;
  119. // The builtin InvalidType.
  120. static const SemanticsTypeId InvalidType;
  121. // An explicitly invalid ID.
  122. static const SemanticsTypeId Invalid;
  123. using IndexBase::IndexBase;
  124. auto Print(llvm::raw_ostream& out) const -> void {
  125. out << "type";
  126. if (index == TypeType.index) {
  127. out << "TypeType";
  128. } else if (index == InvalidType.index) {
  129. out << "InvalidType";
  130. } else {
  131. IndexBase::Print(out);
  132. }
  133. }
  134. };
  135. constexpr SemanticsTypeId SemanticsTypeId::TypeType =
  136. SemanticsTypeId(SemanticsTypeId::InvalidIndex - 2);
  137. constexpr SemanticsTypeId SemanticsTypeId::InvalidType =
  138. SemanticsTypeId(SemanticsTypeId::InvalidIndex - 1);
  139. constexpr SemanticsTypeId SemanticsTypeId::Invalid =
  140. SemanticsTypeId(SemanticsTypeId::InvalidIndex);
  141. // An index for member access.
  142. struct SemanticsMemberIndex : public IndexBase {
  143. using IndexBase::IndexBase;
  144. auto Print(llvm::raw_ostream& out) const -> void {
  145. out << "member";
  146. IndexBase::Print(out);
  147. }
  148. };
  149. // The standard structure for SemanticsNode. This is trying to provide a minimal
  150. // amount of information for a node:
  151. //
  152. // - parse_node for error placement.
  153. // - kind for run-time logic when the input Kind is unknown.
  154. // - type_id for quick type checking.
  155. // - Up to two Kind-specific members.
  156. //
  157. // For each Kind in SemanticsNodeKind, a typical flow looks like:
  158. //
  159. // - Create a `SemanticsNode` using `SemanticsNode::Kind::Make()`
  160. // - Access cross-Kind members using `node.type_id()` and similar.
  161. // - Access Kind-specific members using `node.GetAsKind()`, which depending on
  162. // the number of members will return one of NoArgs, a single value, or a
  163. // `std::pair` of values.
  164. // - Using the wrong `node.GetAsKind()` is a programming error, and should
  165. // CHECK-fail in debug modes (opt may too, but it's not an API guarantee).
  166. //
  167. // Internally, each Kind uses the `Factory*` types to provide a boilerplate
  168. // `Make` and `Get` methods.
  169. class SemanticsNode {
  170. public:
  171. struct NoArgs {};
  172. // Factory base classes are private, then used for public classes. This class
  173. // has two public and two private sections to prevent accidents.
  174. private:
  175. // Factory templates need to use the raw enum instead of the class wrapper.
  176. using KindTemplateEnum = Internal::SemanticsNodeKindRawEnum;
  177. // Provides Make and Get to support 0, 1, or 2 arguments for a SemanticsNode.
  178. // These are protected so that child factories can opt in to what pieces they
  179. // want to use.
  180. template <KindTemplateEnum Kind, typename... ArgTypes>
  181. class FactoryBase {
  182. protected:
  183. static auto Make(ParseTree::Node parse_node, SemanticsTypeId type_id,
  184. ArgTypes... arg_ids) -> SemanticsNode {
  185. return SemanticsNode(parse_node, SemanticsNodeKind::Create(Kind), type_id,
  186. arg_ids.index...);
  187. }
  188. static auto Get(SemanticsNode node) {
  189. struct Unused {};
  190. return GetImpl<ArgTypes..., Unused>(node);
  191. }
  192. private:
  193. // GetImpl handles the different return types based on ArgTypes.
  194. template <typename Arg0Type, typename Arg1Type, typename>
  195. static auto GetImpl(SemanticsNode node) -> std::pair<Arg0Type, Arg1Type> {
  196. CARBON_CHECK(node.kind() == Kind);
  197. return {Arg0Type(node.arg0_), Arg1Type(node.arg1_)};
  198. }
  199. template <typename Arg0Type, typename>
  200. static auto GetImpl(SemanticsNode node) -> Arg0Type {
  201. CARBON_CHECK(node.kind() == Kind);
  202. return Arg0Type(node.arg0_);
  203. }
  204. template <typename>
  205. static auto GetImpl(SemanticsNode node) -> NoArgs {
  206. CARBON_CHECK(node.kind() == Kind);
  207. return NoArgs();
  208. }
  209. };
  210. // Provide Get along with a Make that requires a type.
  211. template <KindTemplateEnum Kind, typename... ArgTypes>
  212. class Factory : public FactoryBase<Kind, ArgTypes...> {
  213. public:
  214. using FactoryBase<Kind, ArgTypes...>::Make;
  215. using FactoryBase<Kind, ArgTypes...>::Get;
  216. };
  217. // Provides Get along with a Make that assumes a non-changing type.
  218. template <KindTemplateEnum Kind, typename... ArgTypes>
  219. class FactoryNoType : public FactoryBase<Kind, ArgTypes...> {
  220. public:
  221. static auto Make(ParseTree::Node parse_node, ArgTypes... args) {
  222. return FactoryBase<Kind, ArgTypes...>::Make(
  223. parse_node, SemanticsTypeId::Invalid, args...);
  224. }
  225. using FactoryBase<Kind, ArgTypes...>::Get;
  226. };
  227. public:
  228. // Invalid is in the SemanticsNodeKind enum, but should never be used.
  229. class Invalid {
  230. public:
  231. static auto Get(SemanticsNode /*node*/) -> SemanticsNode::NoArgs {
  232. CARBON_FATAL() << "Invalid access";
  233. }
  234. };
  235. using Assign = SemanticsNode::Factory<SemanticsNodeKind::Assign,
  236. SemanticsNodeId /*lhs_id*/,
  237. SemanticsNodeId /*rhs_id*/>;
  238. using BinaryOperatorAdd =
  239. SemanticsNode::Factory<SemanticsNodeKind::BinaryOperatorAdd,
  240. SemanticsNodeId /*lhs_id*/,
  241. SemanticsNodeId /*rhs_id*/>;
  242. using BindName = SemanticsNode::Factory<SemanticsNodeKind::BindName,
  243. SemanticsStringId /*name_id*/,
  244. SemanticsNodeId /*node_id*/>;
  245. using BlockArg = Factory<SemanticsNodeKind::BlockArg>;
  246. using BoolLiteral =
  247. Factory<SemanticsNodeKind::BoolLiteral, SemanticsBoolValue /*value*/>;
  248. using Branch = FactoryNoType<SemanticsNodeKind::Branch,
  249. SemanticsNodeBlockId /*target_id*/>;
  250. using BranchIf = FactoryNoType<SemanticsNodeKind::BranchIf,
  251. SemanticsNodeBlockId /*target_id*/,
  252. SemanticsNodeId /*cond_id*/>;
  253. using BranchWithArg = FactoryNoType<SemanticsNodeKind::BranchWithArg,
  254. SemanticsNodeBlockId /*target_id*/,
  255. SemanticsNodeId /*arg*/>;
  256. class Builtin {
  257. public:
  258. static auto Make(SemanticsBuiltinKind builtin_kind, SemanticsTypeId type_id)
  259. -> SemanticsNode {
  260. // Builtins won't have a ParseTree node associated, so we provide the
  261. // default invalid one.
  262. // This can't use the standard Make function because of the `AsInt()` cast
  263. // instead of `.index`.
  264. return SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Builtin,
  265. type_id, builtin_kind.AsInt());
  266. }
  267. static auto Get(SemanticsNode node) -> SemanticsBuiltinKind {
  268. return SemanticsBuiltinKind::FromInt(node.arg0_);
  269. }
  270. };
  271. using Call =
  272. Factory<SemanticsNodeKind::Call, SemanticsNodeBlockId /*refs_id*/,
  273. SemanticsFunctionId /*function_id*/>;
  274. using CodeBlock = FactoryNoType<SemanticsNodeKind::CodeBlock,
  275. SemanticsNodeBlockId /*node_block_id*/>;
  276. class CrossReference
  277. : public FactoryBase<SemanticsNodeKind::CrossReference,
  278. SemanticsCrossReferenceIRId /*ir_id*/,
  279. SemanticsNodeId /*node_id*/> {
  280. public:
  281. static auto Make(SemanticsTypeId type_id, SemanticsCrossReferenceIRId ir_id,
  282. SemanticsNodeId node_id) -> SemanticsNode {
  283. // A node's parse tree node must refer to a node in the current parse
  284. // tree. This cannot use the cross-referenced node's parse tree node
  285. // because it will be in a different parse tree.
  286. return FactoryBase::Make(ParseTree::Node::Invalid, type_id, ir_id,
  287. node_id);
  288. }
  289. using FactoryBase::Get;
  290. };
  291. using FunctionDeclaration =
  292. FactoryNoType<SemanticsNodeKind::FunctionDeclaration,
  293. SemanticsFunctionId /*function_id*/>;
  294. using IntegerLiteral = Factory<SemanticsNodeKind::IntegerLiteral,
  295. SemanticsIntegerLiteralId /*integer_id*/>;
  296. using RealLiteral = Factory<SemanticsNodeKind::RealLiteral,
  297. SemanticsRealLiteralId /*real_id*/>;
  298. using Return = FactoryNoType<SemanticsNodeKind::Return>;
  299. using ReturnExpression =
  300. Factory<SemanticsNodeKind::ReturnExpression, SemanticsNodeId /*expr_id*/>;
  301. using StringLiteral = Factory<SemanticsNodeKind::StringLiteral,
  302. SemanticsStringId /*string_id*/>;
  303. using StructMemberAccess = Factory<SemanticsNodeKind::StructMemberAccess,
  304. SemanticsNodeId /*struct_id*/,
  305. SemanticsMemberIndex /*ref_index*/>;
  306. using StructType =
  307. Factory<SemanticsNodeKind::StructType, SemanticsNodeBlockId /*refs_id*/>;
  308. using StructTypeField = Factory<SemanticsNodeKind::StructTypeField,
  309. SemanticsStringId /*name_id*/>;
  310. using StructValue =
  311. Factory<SemanticsNodeKind::StructValue, SemanticsNodeBlockId /*refs_id*/>;
  312. using StubReference =
  313. Factory<SemanticsNodeKind::StubReference, SemanticsNodeId /*node_id*/>;
  314. using VarStorage = Factory<SemanticsNodeKind::VarStorage>;
  315. SemanticsNode()
  316. : SemanticsNode(ParseTree::Node::Invalid, SemanticsNodeKind::Invalid,
  317. SemanticsTypeId::Invalid) {}
  318. // Provide `node.GetAsKind()` as an instance method for all kinds, essentially
  319. // an alias for`SemanticsNode::Kind::Get(node)`.
  320. #define CARBON_SEMANTICS_NODE_KIND(Name) \
  321. auto GetAs##Name() const { return Name::Get(*this); }
  322. #include "toolchain/semantics/semantics_node_kind.def"
  323. auto parse_node() const -> ParseTree::Node { return parse_node_; }
  324. auto kind() const -> SemanticsNodeKind { return kind_; }
  325. auto type_id() const -> SemanticsTypeId { return type_id_; }
  326. auto Print(llvm::raw_ostream& out) const -> void;
  327. private:
  328. // Builtins have peculiar construction, so they are a friend rather than using
  329. // a factory base class.
  330. friend struct SemanticsNodeForBuiltin;
  331. explicit SemanticsNode(ParseTree::Node parse_node, SemanticsNodeKind kind,
  332. SemanticsTypeId type_id,
  333. int32_t arg0 = SemanticsNodeId::InvalidIndex,
  334. int32_t arg1 = SemanticsNodeId::InvalidIndex)
  335. : parse_node_(parse_node),
  336. kind_(kind),
  337. type_id_(type_id),
  338. arg0_(arg0),
  339. arg1_(arg1) {}
  340. ParseTree::Node parse_node_;
  341. SemanticsNodeKind kind_;
  342. SemanticsTypeId type_id_;
  343. // Use GetAsKind to access arg0 and arg1.
  344. int32_t arg0_;
  345. int32_t arg1_;
  346. };
  347. // TODO: This is currently 20 bytes because we sometimes have 2 arguments for a
  348. // pair of SemanticsNodes. However, SemanticsNodeKind is 1 byte; if args
  349. // were 3.5 bytes, we could potentially shrink SemanticsNode by 4 bytes. This
  350. // may be worth investigating further.
  351. static_assert(sizeof(SemanticsNode) == 20, "Unexpected SemanticsNode size");
  352. // Provides base support for use of Id types as DenseMap/DenseSet keys.
  353. // Instantiated below.
  354. template <typename Id>
  355. struct SemanticsIdMapInfo {
  356. static inline auto getEmptyKey() -> Id {
  357. return Id(llvm::DenseMapInfo<int32_t>::getEmptyKey());
  358. }
  359. static inline auto getTombstoneKey() -> Id {
  360. return Id(llvm::DenseMapInfo<int32_t>::getTombstoneKey());
  361. }
  362. static auto getHashValue(const Id& val) -> unsigned {
  363. return llvm::DenseMapInfo<int32_t>::getHashValue(val.index);
  364. }
  365. static auto isEqual(const Id& lhs, const Id& rhs) -> bool {
  366. return lhs == rhs;
  367. }
  368. };
  369. } // namespace Carbon
  370. // Support use of Id types as DenseMap/DenseSet keys.
  371. template <>
  372. struct llvm::DenseMapInfo<Carbon::SemanticsNodeId>
  373. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsNodeId> {};
  374. template <>
  375. struct llvm::DenseMapInfo<Carbon::SemanticsStringId>
  376. : public Carbon::SemanticsIdMapInfo<Carbon::SemanticsStringId> {};
  377. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_NODE_H_