semantics_node.h 16 KB

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