file.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  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/StringMap.h"
  8. #include "llvm/ADT/iterator_range.h"
  9. #include "llvm/Support/Allocator.h"
  10. #include "llvm/Support/FormatVariadic.h"
  11. #include "toolchain/sem_ir/node.h"
  12. namespace Carbon::SemIR {
  13. // A function.
  14. struct Function : public Printable<Function> {
  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 (return_slot_id.is_valid()) {
  22. out << ", return_slot: " << return_slot_id;
  23. }
  24. if (!body_block_ids.empty()) {
  25. out << llvm::formatv(
  26. ", body: [{0}]",
  27. llvm::make_range(body_block_ids.begin(), body_block_ids.end()));
  28. }
  29. out << "}";
  30. }
  31. // The function name.
  32. StringId name_id;
  33. // A block containing a single reference node per parameter.
  34. NodeBlockId param_refs_id;
  35. // The return type. This will be invalid if the return type wasn't specified.
  36. TypeId return_type_id;
  37. // The storage for the return value, which is a reference expression whose
  38. // type is the return type of the function. Will be invalid if the function
  39. // doesn't have a return slot. If this is valid, a call to the function is
  40. // expected to have an additional final argument corresponding to the return
  41. // slot.
  42. NodeId return_slot_id;
  43. // A list of the statically reachable code blocks in the body of the
  44. // function, in lexical order. The first block is the entry block. This will
  45. // be empty for declarations that don't have a visible definition.
  46. llvm::SmallVector<NodeBlockId> body_block_ids;
  47. };
  48. struct RealLiteral : public Printable<RealLiteral> {
  49. auto Print(llvm::raw_ostream& out) const -> void {
  50. out << "{mantissa: ";
  51. mantissa.print(out, /*isSigned=*/false);
  52. out << ", exponent: " << exponent << ", is_decimal: " << is_decimal << "}";
  53. }
  54. llvm::APInt mantissa;
  55. llvm::APInt exponent;
  56. // If false, the value is mantissa * 2^exponent.
  57. // If true, the value is mantissa * 10^exponent.
  58. bool is_decimal;
  59. };
  60. // Provides semantic analysis on a Parse::Tree.
  61. class File : public Printable<File> {
  62. public:
  63. // Produces a file for the builtins.
  64. explicit File();
  65. // Starts a new file for Check::CheckParseTree. Builtins are required.
  66. explicit File(std::string filename, const File* builtins);
  67. // Verifies that invariants of the semantics IR hold.
  68. auto Verify() const -> ErrorOr<Success>;
  69. // Prints the full IR. Allow omitting builtins so that unrelated changes are
  70. // less likely to alternate test golden files.
  71. // TODO: In the future, the things to print may change, for example by adding
  72. // preludes. We may then want the ability to omit other things similar to
  73. // builtins.
  74. auto Print(llvm::raw_ostream& out, bool include_builtins) const -> void;
  75. auto Print(llvm::raw_ostream& out) const -> void {
  76. Print(out, /*include_builtins=*/false);
  77. }
  78. // Returns array bound value from the bound node.
  79. auto GetArrayBoundValue(NodeId bound_id) const -> uint64_t {
  80. return GetIntegerLiteral(GetNode(bound_id).GetAsIntegerLiteral())
  81. .getZExtValue();
  82. }
  83. // Returns the requested IR.
  84. auto GetCrossReferenceIR(CrossReferenceIRId xref_id) const -> const File& {
  85. return *cross_reference_irs_[xref_id.index];
  86. }
  87. // Adds a callable, returning an ID to reference it.
  88. auto AddFunction(Function function) -> FunctionId {
  89. FunctionId id(functions_.size());
  90. functions_.push_back(function);
  91. return id;
  92. }
  93. // Returns the requested callable.
  94. auto GetFunction(FunctionId function_id) const -> const Function& {
  95. return functions_[function_id.index];
  96. }
  97. // Returns the requested callable.
  98. auto GetFunction(FunctionId function_id) -> Function& {
  99. return functions_[function_id.index];
  100. }
  101. // Adds an integer literal, returning an ID to reference it.
  102. auto AddIntegerLiteral(llvm::APInt integer_literal) -> IntegerLiteralId {
  103. IntegerLiteralId id(integer_literals_.size());
  104. integer_literals_.push_back(integer_literal);
  105. return id;
  106. }
  107. // Returns the requested integer literal.
  108. auto GetIntegerLiteral(IntegerLiteralId int_id) const -> const llvm::APInt& {
  109. return integer_literals_[int_id.index];
  110. }
  111. // Adds a name scope, returning an ID to reference it.
  112. auto AddNameScope() -> NameScopeId {
  113. NameScopeId name_scopes_id(name_scopes_.size());
  114. name_scopes_.resize(name_scopes_id.index + 1);
  115. return name_scopes_id;
  116. }
  117. // Adds an entry to a name scope. Returns true on success, false on
  118. // duplicates.
  119. auto AddNameScopeEntry(NameScopeId scope_id, StringId name_id,
  120. NodeId target_id) -> bool {
  121. return name_scopes_[scope_id.index].insert({name_id, target_id}).second;
  122. }
  123. // Returns the requested name scope.
  124. auto GetNameScope(NameScopeId scope_id) const
  125. -> const llvm::DenseMap<StringId, NodeId>& {
  126. return name_scopes_[scope_id.index];
  127. }
  128. // Adds a node to the node list, returning an ID to reference the node. Note
  129. // that this doesn't add the node to any node block. Check::Context::AddNode
  130. // or NodeBlockStack::AddNode should usually be used instead, to add the node
  131. // to the current block.
  132. auto AddNodeInNoBlock(Node node) -> NodeId {
  133. NodeId node_id(nodes_.size());
  134. nodes_.push_back(node);
  135. return node_id;
  136. }
  137. // Overwrites a given node with a new value.
  138. auto ReplaceNode(NodeId node_id, Node node) -> void {
  139. nodes_[node_id.index] = node;
  140. }
  141. // Returns the requested node.
  142. auto GetNode(NodeId node_id) const -> Node { return nodes_[node_id.index]; }
  143. // Reserves and returns a node block ID. The contents of the node block
  144. // should be specified by calling SetNodeBlock, or by pushing the ID onto the
  145. // NodeBlockStack.
  146. auto AddNodeBlockId() -> NodeBlockId {
  147. NodeBlockId id(node_blocks_.size());
  148. node_blocks_.push_back({});
  149. return id;
  150. }
  151. // Sets the contents of an empty node block to the given content.
  152. auto SetNodeBlock(NodeBlockId block_id, llvm::ArrayRef<NodeId> content)
  153. -> void {
  154. CARBON_CHECK(block_id != NodeBlockId::Unreachable);
  155. CARBON_CHECK(node_blocks_[block_id.index].empty())
  156. << "node block content set more than once";
  157. node_blocks_[block_id.index] = AllocateCopy(content);
  158. }
  159. // Adds a node block with the given content, returning an ID to reference it.
  160. auto AddNodeBlock(llvm::ArrayRef<NodeId> content) -> NodeBlockId {
  161. NodeBlockId id(node_blocks_.size());
  162. node_blocks_.push_back(AllocateCopy(content));
  163. return id;
  164. }
  165. // Adds a node block of the given size.
  166. auto AddUninitializedNodeBlock(size_t size) -> NodeBlockId {
  167. NodeBlockId id(node_blocks_.size());
  168. node_blocks_.push_back(AllocateUninitialized<NodeId>(size));
  169. return id;
  170. }
  171. // Returns the requested node block.
  172. auto GetNodeBlock(NodeBlockId block_id) const -> llvm::ArrayRef<NodeId> {
  173. CARBON_CHECK(block_id != NodeBlockId::Unreachable);
  174. return node_blocks_[block_id.index];
  175. }
  176. // Returns the requested node block.
  177. auto GetNodeBlock(NodeBlockId block_id) -> llvm::MutableArrayRef<NodeId> {
  178. CARBON_CHECK(block_id != NodeBlockId::Unreachable);
  179. return node_blocks_[block_id.index];
  180. }
  181. // Adds a real literal, returning an ID to reference it.
  182. auto AddRealLiteral(RealLiteral real_literal) -> RealLiteralId {
  183. RealLiteralId id(real_literals_.size());
  184. real_literals_.push_back(real_literal);
  185. return id;
  186. }
  187. // Returns the requested real literal.
  188. auto GetRealLiteral(RealLiteralId int_id) const -> const RealLiteral& {
  189. return real_literals_[int_id.index];
  190. }
  191. // Adds an string, returning an ID to reference it.
  192. auto AddString(llvm::StringRef str) -> StringId {
  193. // Look up the string, or add it if it's new.
  194. StringId next_id(strings_.size());
  195. auto [it, added] = string_to_id_.insert({str, next_id});
  196. if (added) {
  197. // Update the reverse mapping from IDs to strings.
  198. CARBON_CHECK(it->second == next_id);
  199. strings_.push_back(it->first());
  200. }
  201. return it->second;
  202. }
  203. // Returns the requested string.
  204. auto GetString(StringId string_id) const -> llvm::StringRef {
  205. return strings_[string_id.index];
  206. }
  207. // Adds a type, returning an ID to reference it.
  208. auto AddType(NodeId node_id) -> TypeId {
  209. TypeId type_id(types_.size());
  210. types_.push_back(node_id);
  211. return type_id;
  212. }
  213. // Gets the node ID for a type. This doesn't handle TypeType or InvalidType in
  214. // order to avoid a check; callers that need that should use
  215. // GetTypeAllowBuiltinTypes.
  216. auto GetType(TypeId type_id) const -> NodeId {
  217. // Double-check it's not called with TypeType or InvalidType.
  218. CARBON_CHECK(type_id.index >= 0)
  219. << "Invalid argument for GetType: " << type_id;
  220. return types_[type_id.index];
  221. }
  222. auto GetTypeAllowBuiltinTypes(TypeId type_id) const -> NodeId {
  223. if (type_id == TypeId::TypeType) {
  224. return NodeId::BuiltinTypeType;
  225. } else if (type_id == TypeId::Error) {
  226. return NodeId::BuiltinError;
  227. } else {
  228. return GetType(type_id);
  229. }
  230. }
  231. // Adds a type block with the given content, returning an ID to reference it.
  232. auto AddTypeBlock(llvm::ArrayRef<TypeId> content) -> TypeBlockId {
  233. TypeBlockId id(type_blocks_.size());
  234. type_blocks_.push_back(AllocateCopy(content));
  235. return id;
  236. }
  237. // Returns the requested type block.
  238. auto GetTypeBlock(TypeBlockId block_id) const -> llvm::ArrayRef<TypeId> {
  239. return type_blocks_[block_id.index];
  240. }
  241. // Returns the requested type block.
  242. auto GetTypeBlock(TypeBlockId block_id) -> llvm::MutableArrayRef<TypeId> {
  243. return type_blocks_[block_id.index];
  244. }
  245. // Produces a string version of a type. If `in_type_context` is false, an
  246. // explicit conversion to type `type` will be added in cases where the type
  247. // expression would otherwise have a different type, such as a tuple or
  248. // struct type.
  249. auto StringifyType(TypeId type_id, bool in_type_context = false) const
  250. -> std::string;
  251. auto functions_size() const -> int { return functions_.size(); }
  252. auto nodes_size() const -> int { return nodes_.size(); }
  253. auto node_blocks_size() const -> int { return node_blocks_.size(); }
  254. auto types() const -> llvm::ArrayRef<NodeId> { return types_; }
  255. auto top_node_block_id() const -> NodeBlockId { return top_node_block_id_; }
  256. auto set_top_node_block_id(NodeBlockId block_id) -> void {
  257. top_node_block_id_ = block_id;
  258. }
  259. // Returns true if there were errors creating the semantics IR.
  260. auto has_errors() const -> bool { return has_errors_; }
  261. auto set_has_errors(bool has_errors) -> void { has_errors_ = has_errors; }
  262. auto filename() const -> llvm::StringRef { return filename_; }
  263. private:
  264. // Allocates an uninitialized array using our slab allocator.
  265. template <typename T>
  266. auto AllocateUninitialized(std::size_t size) -> llvm::MutableArrayRef<T> {
  267. // We're not going to run a destructor, so ensure that's OK.
  268. static_assert(std::is_trivially_destructible_v<T>);
  269. T* storage =
  270. static_cast<T*>(allocator_.Allocate(size * sizeof(T), alignof(T)));
  271. return llvm::MutableArrayRef<T>(storage, size);
  272. }
  273. // Allocates a copy of the given data using our slab allocator.
  274. template <typename T>
  275. auto AllocateCopy(llvm::ArrayRef<T> data) -> llvm::MutableArrayRef<T> {
  276. auto result = AllocateUninitialized<T>(data.size());
  277. std::uninitialized_copy(data.begin(), data.end(), result.begin());
  278. return result;
  279. }
  280. bool has_errors_ = false;
  281. // Slab allocator, used to allocate node and type blocks.
  282. llvm::BumpPtrAllocator allocator_;
  283. // The associated filename.
  284. // TODO: If SemIR starts linking back to tokens, reuse its filename.
  285. std::string filename_;
  286. // Storage for callable objects.
  287. llvm::SmallVector<Function> functions_;
  288. // Related IRs. There will always be at least 2 entries, the builtin IR (used
  289. // for references of builtins) followed by the current IR (used for references
  290. // crossing node blocks).
  291. llvm::SmallVector<const File*> cross_reference_irs_;
  292. // Storage for integer literals.
  293. llvm::SmallVector<llvm::APInt> integer_literals_;
  294. // Storage for name scopes.
  295. llvm::SmallVector<llvm::DenseMap<StringId, NodeId>> name_scopes_;
  296. // Storage for real literals.
  297. llvm::SmallVector<RealLiteral> real_literals_;
  298. // Storage for strings. strings_ provides a list of allocated strings, while
  299. // string_to_id_ provides a mapping to identify strings.
  300. llvm::StringMap<StringId> string_to_id_;
  301. llvm::SmallVector<llvm::StringRef> strings_;
  302. // Nodes which correspond to in-use types. Stored separately for easy access
  303. // by lowering.
  304. llvm::SmallVector<NodeId> types_;
  305. // Type blocks within the IR. These reference entries in types_. Storage for
  306. // the data is provided by allocator_.
  307. llvm::SmallVector<llvm::MutableArrayRef<TypeId>> type_blocks_;
  308. // All nodes. The first entries will always be cross-references to builtins,
  309. // at indices matching BuiltinKind ordering.
  310. llvm::SmallVector<Node> nodes_;
  311. // Node blocks within the IR. These reference entries in nodes_. Storage for
  312. // the data is provided by allocator_.
  313. llvm::SmallVector<llvm::MutableArrayRef<NodeId>> node_blocks_;
  314. // The top node block ID.
  315. NodeBlockId top_node_block_id_ = NodeBlockId::Invalid;
  316. };
  317. // The expression category of a semantics node. See /docs/design/values.md for
  318. // details.
  319. enum class ExpressionCategory : int8_t {
  320. // This node does not correspond to an expression, and as such has no
  321. // category.
  322. NotExpression,
  323. // This node represents a value expression.
  324. Value,
  325. // This node represents a durable reference expression, that denotes an
  326. // object that outlives the current full expression context.
  327. DurableReference,
  328. // This node represents an ephemeral reference expression, that denotes an
  329. // object that does not outlive the current full expression context.
  330. EphemeralReference,
  331. // This node represents an initializing expression, that describes how to
  332. // initialize an object.
  333. Initializing,
  334. // This node represents a syntactic combination of expressions that are
  335. // permitted to have different expression categories. This is used for tuple
  336. // and struct literals, where the subexpressions for different elements can
  337. // have different categories.
  338. Mixed,
  339. Last = Mixed
  340. };
  341. // Returns the expression category for a node.
  342. auto GetExpressionCategory(const File& file, NodeId node_id)
  343. -> ExpressionCategory;
  344. // The value representation to use when passing by value.
  345. struct ValueRepresentation {
  346. enum Kind : int8_t {
  347. // The type has no value representation. This is used for empty types, such
  348. // as `()`, where there is no value.
  349. None,
  350. // The value representation is a copy of the value. On call boundaries, the
  351. // value itself will be passed. `type` is the value type.
  352. // TODO: `type` should be `const`-qualified, but is currently not.
  353. Copy,
  354. // The value representation is a pointer to an object. When used as a
  355. // parameter, the argument is a reference expression. `type` is the pointee
  356. // type.
  357. // TODO: `type` should be `const`-qualified, but is currently not.
  358. Pointer,
  359. // The value representation has been customized, and has the same behavior
  360. // as the value representation of some other type.
  361. // TODO: This is not implemented or used yet.
  362. Custom,
  363. };
  364. // The kind of value representation used by this type.
  365. Kind kind;
  366. // The type used to model the value representation.
  367. TypeId type;
  368. };
  369. // Returns information about the value representation to use for a type.
  370. auto GetValueRepresentation(const File& file, TypeId type_id)
  371. -> ValueRepresentation;
  372. // The initializing representation to use when returning by value.
  373. struct InitializingRepresentation {
  374. enum Kind : int8_t {
  375. // The type has no initializing representation. This is used for empty
  376. // types, where no initialization is necessary.
  377. None,
  378. // An initializing expression produces a value, which is copied into the
  379. // initialized object.
  380. ByCopy,
  381. // An initializing expression takes a location as input, which is
  382. // initialized as a side effect of evaluating the expression.
  383. InPlace,
  384. // TODO: Consider adding a kind where the expression takes an advisory
  385. // location and returns a value plus an indicator of whether the location
  386. // was actually initialized.
  387. };
  388. // The kind of initializing representation used by this type.
  389. Kind kind;
  390. // Returns whether a return slot is used when returning this type.
  391. auto has_return_slot() const -> bool { return kind == InPlace; }
  392. };
  393. // Returns information about the initializing representation to use for a type.
  394. auto GetInitializingRepresentation(const File& file, TypeId type_id)
  395. -> InitializingRepresentation;
  396. } // namespace Carbon::SemIR
  397. #endif // CARBON_TOOLCHAIN_SEM_IR_FILE_H_