semantics_ir.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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_IR_H_
  5. #define CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_
  6. #include "llvm/ADT/SmallVector.h"
  7. #include "llvm/ADT/StringMap.h"
  8. #include "llvm/ADT/iterator_range.h"
  9. #include "llvm/Support/FormatVariadic.h"
  10. #include "toolchain/parser/parse_tree.h"
  11. #include "toolchain/semantics/semantics_node.h"
  12. namespace Carbon {
  13. // A function.
  14. struct SemanticsFunction {
  15. auto Print(llvm::raw_ostream& out) const -> void {
  16. out << "{name: " << name_id << ", "
  17. << "param_refs: " << param_refs_id;
  18. if (return_type_id.is_valid()) {
  19. out << ", return_type: " << return_type_id;
  20. }
  21. if (!body_block_ids.empty()) {
  22. out << llvm::formatv(
  23. ", body: {{{0}}}",
  24. llvm::make_range(body_block_ids.begin(), body_block_ids.end()));
  25. }
  26. out << "}";
  27. }
  28. // The function name.
  29. SemanticsStringId name_id;
  30. // A block containing a single reference node per parameter.
  31. SemanticsNodeBlockId param_refs_id;
  32. // The return type. This will be invalid if the return type wasn't specified.
  33. SemanticsTypeId return_type_id;
  34. // A list of the statically reachable code blocks in the body of the
  35. // function, in lexical order. The first block is the entry block. This will
  36. // be empty for declarations that don't have a visible definition.
  37. llvm::SmallVector<SemanticsNodeBlockId> body_block_ids;
  38. };
  39. struct SemanticsRealLiteral {
  40. auto Print(llvm::raw_ostream& out) const -> void {
  41. out << "{mantissa: " << mantissa << ", exponent: " << exponent
  42. << ", is_decimal: " << is_decimal << "}";
  43. }
  44. llvm::APInt mantissa;
  45. llvm::APInt exponent;
  46. // If false, the value is mantissa * 2^exponent.
  47. // If true, the value is mantissa * 10^exponent.
  48. bool is_decimal;
  49. };
  50. // Provides semantic analysis on a ParseTree.
  51. class SemanticsIR {
  52. public:
  53. // Produces the builtins.
  54. static auto MakeBuiltinIR() -> SemanticsIR;
  55. // Adds the IR for the provided ParseTree.
  56. static auto MakeFromParseTree(const SemanticsIR& builtin_ir,
  57. const TokenizedBuffer& tokens,
  58. const ParseTree& parse_tree,
  59. DiagnosticConsumer& consumer,
  60. llvm::raw_ostream* vlog_stream) -> SemanticsIR;
  61. // Verifies that invariants of the semantics IR hold.
  62. auto Verify() const -> ErrorOr<Success>;
  63. // Prints the full IR. Allow omitting builtins so that unrelated changes are
  64. // less likely to alternate test golden files.
  65. // TODO: In the future, the things to print may change, for example by adding
  66. // preludes. We may then want the ability to omit other things similar to
  67. // builtins.
  68. auto Print(llvm::raw_ostream& out) const -> void {
  69. Print(out, /*include_builtins=*/false);
  70. }
  71. auto Print(llvm::raw_ostream& out, bool include_builtins) const -> void;
  72. // Returns the requested IR.
  73. auto GetCrossReferenceIR(SemanticsCrossReferenceIRId xref_id) const
  74. -> const SemanticsIR& {
  75. return *cross_reference_irs_[xref_id.index];
  76. }
  77. // Adds a callable, returning an ID to reference it.
  78. auto AddFunction(SemanticsFunction function) -> SemanticsFunctionId {
  79. SemanticsFunctionId id(functions_.size());
  80. functions_.push_back(function);
  81. return id;
  82. }
  83. // Returns the requested callable.
  84. auto GetFunction(SemanticsFunctionId function_id) const
  85. -> const SemanticsFunction& {
  86. return functions_[function_id.index];
  87. }
  88. // Returns the requested callable.
  89. auto GetFunction(SemanticsFunctionId function_id) -> SemanticsFunction& {
  90. return functions_[function_id.index];
  91. }
  92. // Adds an integer literal, returning an ID to reference it.
  93. auto AddIntegerLiteral(llvm::APInt integer_literal)
  94. -> SemanticsIntegerLiteralId {
  95. SemanticsIntegerLiteralId id(integer_literals_.size());
  96. integer_literals_.push_back(integer_literal);
  97. return id;
  98. }
  99. // Returns the requested integer literal.
  100. auto GetIntegerLiteral(SemanticsIntegerLiteralId int_id) const
  101. -> const llvm::APInt& {
  102. return integer_literals_[int_id.index];
  103. }
  104. // Adds a name scope, returning an ID to reference it.
  105. auto AddNameScope() -> SemanticsNameScopeId {
  106. SemanticsNameScopeId name_scopes_id(name_scopes_.size());
  107. name_scopes_.resize(name_scopes_id.index + 1);
  108. return name_scopes_id;
  109. }
  110. // Adds an entry to a name scope. Returns true on success, false on
  111. // duplicates.
  112. auto AddNameScopeEntry(SemanticsNameScopeId scope_id,
  113. SemanticsStringId name_id, SemanticsNodeId target_id)
  114. -> bool {
  115. return name_scopes_[scope_id.index].insert({name_id, target_id}).second;
  116. }
  117. // Returns the requested name scope.
  118. auto GetNameScope(SemanticsNameScopeId scope_id) const
  119. -> const llvm::DenseMap<SemanticsStringId, SemanticsNodeId>& {
  120. return name_scopes_[scope_id.index];
  121. }
  122. // Adds a node to a specified block, returning an ID to reference the node.
  123. auto AddNode(SemanticsNodeBlockId block_id, SemanticsNode node)
  124. -> SemanticsNodeId {
  125. SemanticsNodeId node_id(nodes_.size());
  126. nodes_.push_back(node);
  127. if (block_id != SemanticsNodeBlockId::Unreachable) {
  128. node_blocks_[block_id.index].push_back(node_id);
  129. }
  130. return node_id;
  131. }
  132. // Returns the requested node.
  133. auto GetNode(SemanticsNodeId node_id) const -> SemanticsNode {
  134. return nodes_[node_id.index];
  135. }
  136. // Adds an empty node block, returning an ID to reference it.
  137. auto AddNodeBlock() -> SemanticsNodeBlockId {
  138. SemanticsNodeBlockId id(node_blocks_.size());
  139. node_blocks_.push_back({});
  140. return id;
  141. }
  142. // Returns the requested node block.
  143. auto GetNodeBlock(SemanticsNodeBlockId block_id) const
  144. -> const llvm::SmallVector<SemanticsNodeId>& {
  145. CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable);
  146. return node_blocks_[block_id.index];
  147. }
  148. // Returns the requested node block.
  149. auto GetNodeBlock(SemanticsNodeBlockId block_id)
  150. -> llvm::SmallVector<SemanticsNodeId>& {
  151. CARBON_CHECK(block_id != SemanticsNodeBlockId::Unreachable);
  152. return node_blocks_[block_id.index];
  153. }
  154. // Adds a real literal, returning an ID to reference it.
  155. auto AddRealLiteral(SemanticsRealLiteral real_literal)
  156. -> SemanticsRealLiteralId {
  157. SemanticsRealLiteralId id(real_literals_.size());
  158. real_literals_.push_back(real_literal);
  159. return id;
  160. }
  161. // Returns the requested real literal.
  162. auto GetRealLiteral(SemanticsRealLiteralId int_id) const
  163. -> const SemanticsRealLiteral& {
  164. return real_literals_[int_id.index];
  165. }
  166. // Adds an string, returning an ID to reference it.
  167. auto AddString(llvm::StringRef str) -> SemanticsStringId {
  168. // If the string has already been stored, return the corresponding ID.
  169. if (auto existing_id = GetStringID(str)) {
  170. return *existing_id;
  171. }
  172. // Allocate the string and store it in the map.
  173. SemanticsStringId id(strings_.size());
  174. strings_.push_back(str);
  175. CARBON_CHECK(string_to_id_.insert({str, id}).second);
  176. return id;
  177. }
  178. // Returns the requested string.
  179. auto GetString(SemanticsStringId string_id) const -> llvm::StringRef {
  180. return strings_[string_id.index];
  181. }
  182. // Returns an ID for the string if it's previously been stored.
  183. auto GetStringID(llvm::StringRef str) -> std::optional<SemanticsStringId> {
  184. auto str_find = string_to_id_.find(str);
  185. if (str_find != string_to_id_.end()) {
  186. return str_find->second;
  187. }
  188. return std::nullopt;
  189. }
  190. // Adds a type, returning an ID to reference it.
  191. auto AddType(SemanticsNodeId node_id) -> SemanticsTypeId {
  192. SemanticsTypeId type_id(types_.size());
  193. types_.push_back(node_id);
  194. return type_id;
  195. }
  196. // Gets the node ID for a type. This doesn't handle TypeType or InvalidType in
  197. // order to avoid a check; callers that need that should use
  198. // GetTypeAllowBuiltinTypes.
  199. auto GetType(SemanticsTypeId type_id) const -> SemanticsNodeId {
  200. // Double-check it's not called with TypeType or InvalidType.
  201. CARBON_CHECK(type_id.index >= 0)
  202. << "Invalid argument for GetType: " << type_id;
  203. return types_[type_id.index];
  204. }
  205. auto GetTypeAllowBuiltinTypes(SemanticsTypeId type_id) const
  206. -> SemanticsNodeId {
  207. if (type_id == SemanticsTypeId::TypeType) {
  208. return SemanticsNodeId::BuiltinTypeType;
  209. } else if (type_id == SemanticsTypeId::Error) {
  210. return SemanticsNodeId::BuiltinError;
  211. } else {
  212. return GetType(type_id);
  213. }
  214. }
  215. // Adds an empty type block, returning an ID to reference it.
  216. auto AddTypeBlock() -> SemanticsTypeBlockId {
  217. SemanticsTypeBlockId id(type_blocks_.size());
  218. type_blocks_.push_back({});
  219. return id;
  220. }
  221. // Returns the requested type block.
  222. auto GetTypeBlock(SemanticsTypeBlockId block_id) const
  223. -> const llvm::SmallVector<SemanticsTypeId>& {
  224. return type_blocks_[block_id.index];
  225. }
  226. // Returns the requested type block.
  227. auto GetTypeBlock(SemanticsTypeBlockId block_id)
  228. -> llvm::SmallVector<SemanticsTypeId>& {
  229. return type_blocks_[block_id.index];
  230. }
  231. // Produces a string version of a type. If `in_type_context` is false, an
  232. // explicit conversion to type `type` will be added in cases where the type
  233. // expression would otherwise have a different type, such as a tuple or
  234. // struct type.
  235. auto StringifyType(SemanticsTypeId type_id,
  236. bool in_type_context = false) const -> std::string;
  237. auto functions_size() const -> int { return functions_.size(); }
  238. auto nodes_size() const -> int { return nodes_.size(); }
  239. auto node_blocks_size() const -> int { return node_blocks_.size(); }
  240. auto types() const -> const llvm::SmallVector<SemanticsNodeId>& {
  241. return types_;
  242. }
  243. // The node blocks, for direct mutation.
  244. auto node_blocks() -> llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>>& {
  245. return node_blocks_;
  246. }
  247. auto top_node_block_id() const -> SemanticsNodeBlockId {
  248. return top_node_block_id_;
  249. }
  250. // Returns true if there were errors creating the semantics IR.
  251. auto has_errors() const -> bool { return has_errors_; }
  252. private:
  253. explicit SemanticsIR(const SemanticsIR* builtin_ir)
  254. : cross_reference_irs_({builtin_ir == nullptr ? this : builtin_ir}) {
  255. // For SemanticsNodeBlockId::Empty.
  256. node_blocks_.resize(1);
  257. }
  258. bool has_errors_ = false;
  259. // Storage for callable objects.
  260. llvm::SmallVector<SemanticsFunction> functions_;
  261. // Related IRs. There will always be at least 2 entries, the builtin IR (used
  262. // for references of builtins) followed by the current IR (used for references
  263. // crossing node blocks).
  264. llvm::SmallVector<const SemanticsIR*> cross_reference_irs_;
  265. // Storage for integer literals.
  266. llvm::SmallVector<llvm::APInt> integer_literals_;
  267. // Storage for name scopes.
  268. llvm::SmallVector<llvm::DenseMap<SemanticsStringId, SemanticsNodeId>>
  269. name_scopes_;
  270. // Storage for real literals.
  271. llvm::SmallVector<SemanticsRealLiteral> real_literals_;
  272. // Storage for strings. strings_ provides a list of allocated strings, while
  273. // string_to_id_ provides a mapping to identify strings.
  274. llvm::StringMap<SemanticsStringId> string_to_id_;
  275. llvm::SmallVector<llvm::StringRef> strings_;
  276. // Nodes which correspond to in-use types. Stored separately for easy access
  277. // by lowering.
  278. llvm::SmallVector<SemanticsNodeId> types_;
  279. // Storage for blocks within the IR. These reference entries in types_.
  280. llvm::SmallVector<llvm::SmallVector<SemanticsTypeId>> type_blocks_;
  281. // All nodes. The first entries will always be cross-references to builtins,
  282. // at indices matching SemanticsBuiltinKind ordering.
  283. llvm::SmallVector<SemanticsNode> nodes_;
  284. // Storage for blocks within the IR. These reference entries in nodes_.
  285. llvm::SmallVector<llvm::SmallVector<SemanticsNodeId>> node_blocks_;
  286. // The top node block ID.
  287. SemanticsNodeBlockId top_node_block_id_ = SemanticsNodeBlockId::Invalid;
  288. };
  289. // The expression category of a semantics node. See /docs/design/values.md for
  290. // details.
  291. enum class SemanticsExpressionCategory {
  292. // This node does not correspond to an expression, and as such has no
  293. // category.
  294. NotExpression,
  295. // This node represents a value expression.
  296. Value,
  297. // This node represents a durable reference expression, that denotes an
  298. // object that outlives the current full expression context.
  299. DurableReference,
  300. // This node represents an ephemeral reference expression, that denotes an
  301. // object that does not outlive the current full expression context.
  302. EphemeralReference,
  303. // This node represents an initializing expression, that describes how to
  304. // initialize an object.
  305. Initializing,
  306. };
  307. // Returns the expression category for a node.
  308. auto GetSemanticsExpressionCategory(const SemanticsIR& semantics_ir,
  309. SemanticsNodeId node_id)
  310. -> SemanticsExpressionCategory;
  311. } // namespace Carbon
  312. #endif // CARBON_TOOLCHAIN_SEMANTICS_SEMANTICS_IR_H_