constant.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  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_CONSTANT_H_
  5. #define CARBON_TOOLCHAIN_SEM_IR_CONSTANT_H_
  6. #include "common/map.h"
  7. #include "toolchain/base/yaml.h"
  8. #include "toolchain/sem_ir/ids.h"
  9. #include "toolchain/sem_ir/inst.h"
  10. namespace Carbon::SemIR {
  11. // The kinds of symbolic bindings that a constant might depend on. These are
  12. // ordered from least to most dependent, so that the dependence of an operation
  13. // can typically be computed by taking the maximum of the dependences of its
  14. // operands.
  15. enum class ConstantDependence : uint8_t {
  16. // This constant's value is known concretely, and does not depend on any
  17. // symbolic binding.
  18. None,
  19. // The only symbolic binding that this constant depends on is `.Self`.
  20. PeriodSelf,
  21. // The only symbolic bindings that this constant depends on are checked
  22. // generic bindings.
  23. Checked,
  24. // This symbolic binding depends on a template-dependent value, such as a
  25. // template parameter.
  26. Template,
  27. };
  28. // Information about a symbolic constant value. These are indexed by
  29. // `ConstantId`s for which `is_symbolic` is true.
  30. //
  31. // A constant value is defined by the canonical ID of a fully-evaluated inst,
  32. // called a "constant inst", which may depend on the canonical IDs of other
  33. // constant insts. "Canonical" here means that it is chosen such that equal
  34. // constants will have equal canonical IDs. This is typically achieved by
  35. // deduplication in `ConstantStore`, but certain kinds of constant insts are
  36. // canonicalized in other ways.
  37. //
  38. // That constant inst ID fully defines the constant value in itself, but for
  39. // symbolic constant values we sometimes need efficient access to metadata about
  40. // the mapping between the constant and corresponding constants in specifics of
  41. // its enclosing generic. As a result, the ID of a concrete constant directly
  42. // encodes the ID of the constant inst, but the ID of a symbolic constant is an
  43. // index into a table of `SymbolicConstant` entries containing that metadata, as
  44. // well as the constant inst ID.
  45. //
  46. // The price of this optimization is that the constant value's ID depends on the
  47. // enclosing generic, which isn't semantically relevant unless we're
  48. // specifically operating on the generic -> specific mapping. As a result, every
  49. // symbolic constant is represented by two `SymbolicConstant`s, with separate
  50. // IDs: one with that additional metadata, and one without it. The form with
  51. // additional metadata is called an "attached constant", and the form without it
  52. // is an "unattached constant". Note that constants in separate generics may be
  53. // represented by the same unattached constant. In general, only one of these
  54. // IDs is correct to use in a given situation; `ConstantValueStore` can be used
  55. // to map between them if necessary.
  56. //
  57. // Equivalently, you can think of an unattached constant as being implicitly
  58. // parameterized by the `bind_symbolic_name` constant insts that it depends on,
  59. // whereas an attached constant explicitly binds them to parameters of the
  60. // enclosing generic. It's the difference between "`Vector(T)` where `T` is some
  61. // value of type `type`" and "`Vector(T)` where `T` is the `T:! type` parameter
  62. // of this particular enclosing generic".
  63. //
  64. // TODO: consider instead keeping this metadata in a separate hash map keyed by
  65. // a `GenericId`/`ConstantId` pair, so that each constant has a single
  66. // `ConstantId`, rather than separate attached and unattached IDs.
  67. struct SymbolicConstant : Printable<SymbolicConstant> {
  68. // The canonical ID of the inst that defines this constant.
  69. InstId inst_id;
  70. // The generic that this constant is attached to, or `None` if this is an
  71. // unattached constant.
  72. GenericId generic_id;
  73. // The index of this constant within the generic's eval block, if this is an
  74. // attached constant. For a given specific of that generic, this is also the
  75. // index of this constant's value in the value block of that specific. If
  76. // this constant is unattached, `index` will be `None`.
  77. GenericInstIndex index;
  78. // The kind of dependence this symbolic constant exhibits. Should never be
  79. // `None`.
  80. ConstantDependence dependence;
  81. auto Print(llvm::raw_ostream& out) const -> void {
  82. out << "{inst: " << inst_id << ", kind: ";
  83. switch (dependence) {
  84. case ConstantDependence::None:
  85. out << "<error: concrete>";
  86. break;
  87. case ConstantDependence::PeriodSelf:
  88. out << "self";
  89. break;
  90. case ConstantDependence::Checked:
  91. out << "checked";
  92. break;
  93. case ConstantDependence::Template:
  94. out << "template";
  95. break;
  96. }
  97. out << ", attached: ";
  98. if (generic_id.has_value()) {
  99. out << "{generic: " << generic_id << ", index: " << index << "}";
  100. } else {
  101. out << "null";
  102. }
  103. out << "}";
  104. }
  105. };
  106. // Provides a ValueStore wrapper for tracking the constant values of
  107. // instructions.
  108. class ConstantValueStore {
  109. struct UnusableType {};
  110. public:
  111. inline static const auto Unusable = UnusableType();
  112. // Constructs an unusable ConstantValueStore, only good as a placeholder (eg:
  113. // in C++ interop, where there's no foreign SemIR to reference)
  114. explicit ConstantValueStore(UnusableType /* tag */)
  115. : default_(ConstantId::None),
  116. values_(CheckIRId::None),
  117. symbolic_constants_(CheckIRId::None),
  118. insts_(nullptr) {}
  119. explicit ConstantValueStore(ConstantId default_value, const InstStore* insts)
  120. : default_(default_value),
  121. values_(insts->GetIdTag()),
  122. symbolic_constants_(insts->GetIdTag().GetContainerTag()),
  123. insts_(insts) {}
  124. // Returns the constant value of the requested instruction, which is default_
  125. // if unallocated. Always returns an unattached constant.
  126. auto Get(InstId inst_id) const -> ConstantId {
  127. auto const_id = GetAttached(inst_id);
  128. return const_id.has_value() ? GetUnattachedConstant(const_id) : const_id;
  129. }
  130. // Returns the constant value of the requested instruction, which is default_
  131. // if unallocated. This may be an attached constant.
  132. auto GetAttached(InstId inst_id) const -> ConstantId {
  133. CARBON_CHECK(insts_,
  134. "Used ConstantValueStores must have an associated InstStore.");
  135. return values_.GetWithDefault(inst_id, default_);
  136. }
  137. auto IsAttached(ConstantId const_id) const -> bool {
  138. return const_id != GetUnattachedConstant(const_id);
  139. }
  140. // Sets the constant value of the given instruction, or sets that it is known
  141. // to not be a constant.
  142. auto Set(InstId inst_id, ConstantId const_id) -> void {
  143. CARBON_CHECK(insts_,
  144. "Used ConstantValueStores must have an associated InstStore.");
  145. auto index = insts_->GetRawIndex(inst_id);
  146. if (static_cast<size_t>(index) >= values_.size()) {
  147. values_.Resize(index + 1, default_);
  148. }
  149. values_.Get(inst_id) = const_id;
  150. }
  151. // Gets the ID of the underlying constant inst for the given constant. Returns
  152. // `None` if the constant ID is non-constant. Requires `const_id.has_value()`.
  153. auto GetInstId(ConstantId const_id) const -> InstId {
  154. if (const_id.is_concrete()) {
  155. return const_id.concrete_inst_id();
  156. }
  157. if (const_id.is_symbolic()) {
  158. return GetSymbolicConstant(const_id).inst_id;
  159. }
  160. return InstId::None;
  161. }
  162. // Gets the ID of the underlying constant inst for the given constant. Returns
  163. // `None` if the constant ID is non-constant or `None`.
  164. auto GetInstIdIfValid(ConstantId const_id) const -> InstId {
  165. return const_id.has_value() ? GetInstId(const_id) : InstId::None;
  166. }
  167. // Returns whether the underlying constant inst for the given constant is the
  168. // specified type.
  169. template <typename InstT>
  170. auto InstIs(ConstantId const_id) const -> bool {
  171. return insts_->Is<InstT>(GetInstId(const_id));
  172. }
  173. // Returns the requested instruction from the underlying constant inst.
  174. auto GetInst(ConstantId const_id) const -> Inst {
  175. return insts_->Get(GetInstId(const_id));
  176. }
  177. // Returns the requested instruction from the underlying constant inst, which
  178. // is known to have the specified type.
  179. template <typename InstT>
  180. auto GetInstAs(ConstantId const_id) const -> InstT {
  181. return insts_->GetAs<InstT>(GetInstId(const_id));
  182. }
  183. // Returns the requested instruction from the underlying constant inst as the
  184. // specified type, if it is of the that type.
  185. template <typename InstT>
  186. auto TryGetInstAs(ConstantId const_id) const -> std::optional<InstT> {
  187. return insts_->TryGetAs<InstT>(GetInstId(const_id));
  188. }
  189. // Given an instruction, returns the unique constant instruction that is
  190. // equivalent to it. Returns `None` for a non-constant instruction.
  191. auto GetConstantInstId(InstId inst_id) const -> InstId {
  192. return GetInstId(GetAttached(inst_id));
  193. }
  194. // Given a type instruction, returns the unique constant instruction that is
  195. // equivalent to it. Returns `None` for a non-constant instruction.
  196. auto GetConstantTypeInstId(TypeInstId inst_id) const -> TypeInstId {
  197. // If the source instruction has type `type`, its constant value will too,
  198. // since the constant value of `type` is itself.
  199. return TypeInstId::UnsafeMake(GetInstId(GetAttached(inst_id)));
  200. }
  201. // Given a symbolic constant, returns the unattached form of that constant.
  202. // For any other constant ID, returns the ID unchanged.
  203. auto GetUnattachedConstant(ConstantId const_id) const -> ConstantId {
  204. if (const_id.is_symbolic()) {
  205. return values_.Get(GetSymbolicConstant(const_id).inst_id);
  206. }
  207. return const_id;
  208. }
  209. auto AddSymbolicConstant(SymbolicConstant constant) -> ConstantId {
  210. return ConstantId::ForSymbolicConstantId(symbolic_constants_.Add(constant));
  211. }
  212. auto GetSymbolicConstant(ConstantId const_id) -> SymbolicConstant& {
  213. return symbolic_constants_.Get(const_id.symbolic_id());
  214. }
  215. auto GetSymbolicConstant(ConstantId const_id) const
  216. -> const SymbolicConstant& {
  217. return symbolic_constants_.Get(const_id.symbolic_id());
  218. }
  219. // Get the dependence of the given constant.
  220. auto GetDependence(ConstantId const_id) const -> ConstantDependence {
  221. return const_id.is_symbolic() ? GetSymbolicConstant(const_id).dependence
  222. : ConstantDependence::None;
  223. }
  224. // Returns true for symbolic constants other than those that are only symbolic
  225. // because they depend on `.Self`.
  226. auto DependsOnGenericParameter(ConstantId const_id) const -> bool {
  227. return GetDependence(const_id) > ConstantDependence::PeriodSelf;
  228. }
  229. // Collects memory usage of members.
  230. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  231. -> void {
  232. mem_usage.Collect(MemUsage::ConcatLabel(label, "values_"), values_);
  233. mem_usage.Collect(MemUsage::ConcatLabel(label, "symbolic_constants_"),
  234. symbolic_constants_);
  235. }
  236. // Makes an iterable range over pairs of the instruction id and constant value
  237. // id for each value in the store.
  238. auto enumerate() const -> auto { return values_.enumerate(); }
  239. // Outputs assigned constant values, and all symbolic constants.
  240. auto OutputYaml(bool include_singletons) const -> Yaml::OutputMapping {
  241. return Yaml::OutputMapping([&, include_singletons](
  242. Yaml::OutputMapping::Map map) {
  243. map.Add("values", Yaml::OutputMapping([&](Yaml::OutputMapping::Map map) {
  244. for (auto [id, value] : values_.enumerate()) {
  245. if (!include_singletons && IsSingletonInstId(id)) {
  246. continue;
  247. }
  248. if (!value.has_value() || value.is_constant()) {
  249. map.Add(PrintToString(id), Yaml::OutputScalar(value));
  250. }
  251. }
  252. }));
  253. map.Add("symbolic_constants", symbolic_constants_.OutputYaml());
  254. });
  255. }
  256. // The tag used in ConstantIds for concrete constants.
  257. using ConcreteIdTagType = IdTag<SemIR::ConstantId, Tag<SemIR::CheckIRId>>;
  258. auto GetConcreteIdTag() const -> ConcreteIdTagType {
  259. return values_.GetIdTag().ToEquivalentIdType<SemIR::ConstantId>();
  260. }
  261. // The tag used for TypeId, which are concrete constants internally.
  262. using TypeIdTagType = IdTag<SemIR::TypeId, Tag<SemIR::CheckIRId>>;
  263. auto GetTypeIdTag() const -> TypeIdTagType {
  264. return values_.GetIdTag().ToEquivalentIdType<SemIR::TypeId>();
  265. }
  266. // The tag used in ConstantIds for symbolic constants.
  267. using SymbolicIdTagType =
  268. IdTag<ConstantId::SymbolicId, Tag<SemIR::CheckIRId>>;
  269. auto GetSymbolicIdTag() const -> SymbolicIdTagType {
  270. return symbolic_constants_.GetIdTag();
  271. }
  272. // The size of the value store for concrete constant values.
  273. auto ConcreteStoreSize() const -> size_t { return values_.size(); }
  274. private:
  275. const ConstantId default_;
  276. // A mapping from `InstId::index` to the corresponding constant value. This is
  277. // expected to be sparse, and may be smaller than the list of instructions if
  278. // there are trailing non-constant instructions.
  279. //
  280. // Set inline size to 0 because these will typically be too large for the
  281. // stack, while this does make File smaller.
  282. ValueStore<InstId, ConstantId, Tag<CheckIRId>> values_;
  283. // A mapping from a symbolic constant ID index to information about the
  284. // symbolic constant. For a concrete constant, the only information that we
  285. // track is the instruction ID, which is stored directly within the
  286. // `ConstantId`. For a symbolic constant, we also track information about
  287. // where the constant was used, which is stored here.
  288. ValueStore<ConstantId::SymbolicId, SymbolicConstant, Tag<CheckIRId>>
  289. symbolic_constants_;
  290. const InstStore* insts_;
  291. };
  292. // Given a constant ID, returns an instruction that has that constant value.
  293. // For an unattached constant, the returned instruction is the instruction that
  294. // defines the constant; for an attached constant, this is the instruction in
  295. // the eval block that computes the constant value in each specific.
  296. //
  297. // Returns InstId::None if the ConstantId is None or NotConstant.
  298. auto GetInstWithConstantValue(const File& file, ConstantId const_id) -> InstId;
  299. // Provides storage for instructions representing deduplicated global constants.
  300. class ConstantStore {
  301. public:
  302. explicit ConstantStore(File* sem_ir) : sem_ir_(sem_ir) {}
  303. // Adds a new constant instruction, or gets the existing constant with this
  304. // value. Returns the ID of the constant.
  305. //
  306. // This updates `sem_ir->insts()` and `sem_ir->constant_values()` if the
  307. // constant is new.
  308. auto GetOrAdd(Inst inst, ConstantDependence dependence) -> ConstantId;
  309. // Collects memory usage of members.
  310. auto CollectMemUsage(MemUsage& mem_usage, llvm::StringRef label) const
  311. -> void {
  312. mem_usage.Collect(MemUsage::ConcatLabel(label, "map_"), map_);
  313. mem_usage.Collect(MemUsage::ConcatLabel(label, "constants_"), constants_);
  314. }
  315. // Returns a copy of the constant IDs as a vector, in an arbitrary but
  316. // stable order. This should not be used anywhere performance-sensitive.
  317. auto array_ref() const -> llvm::ArrayRef<InstId> { return constants_; }
  318. auto size() const -> int { return constants_.size(); }
  319. private:
  320. File* const sem_ir_;
  321. Map<Inst, ConstantId> map_;
  322. llvm::SmallVector<InstId, 0> constants_;
  323. };
  324. } // namespace Carbon::SemIR
  325. #endif // CARBON_TOOLCHAIN_SEM_IR_CONSTANT_H_