inst_fingerprinter.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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. #include "toolchain/sem_ir/inst_fingerprinter.h"
  5. #include <variant>
  6. #include "common/ostream.h"
  7. #include "llvm/ADT/STLExtras.h"
  8. #include "llvm/ADT/SmallVector.h"
  9. #include "llvm/ADT/StableHashing.h"
  10. #include "toolchain/base/value_ids.h"
  11. #include "toolchain/sem_ir/entity_with_params_base.h"
  12. #include "toolchain/sem_ir/ids.h"
  13. #include "toolchain/sem_ir/typed_insts.h"
  14. namespace Carbon::SemIR {
  15. namespace {
  16. struct Worklist {
  17. // The file containing the instruction we're currently processing.
  18. const File* sem_ir = nullptr;
  19. // The instructions we need to compute fingerprints for.
  20. llvm::SmallVector<std::pair<const File*, std::variant<InstId, InstBlockId>>>
  21. todo;
  22. // The contents of the current instruction as accumulated so far. This is used
  23. // to build a Merkle tree containing a fingerprint for the current
  24. // instruction.
  25. llvm::SmallVector<llvm::stable_hash> contents = {};
  26. // Known cached instruction fingerprints. Each item in `todo` will be added to
  27. // the cache if not already present.
  28. Map<std::pair<const File*, InstId>, uint64_t>* fingerprints;
  29. // Finish fingerprinting and compute the fingerprint.
  30. auto Finish() -> uint64_t { return llvm::stable_hash_combine(contents); }
  31. // Add an invalid marker to the contents. This is used when the entity
  32. // contains a `None` ID. This uses an arbitrary fixed value that is assumed
  33. // to be unlikely to collide with a valid value.
  34. auto AddInvalid() -> void { contents.push_back(-1); }
  35. // Add a string to the contents.
  36. auto AddString(llvm::StringRef string) -> void {
  37. contents.push_back(llvm::stable_hash_name(string));
  38. }
  39. // Each of the following `Add` functions adds a typed argument to the contents
  40. // of the current instruction. If we don't yet have a fingerprint for the
  41. // argument, it instead adds that argument to the worklist instead.
  42. auto Add(InstKind kind) -> void {
  43. // TODO: Precompute or cache the hash of instruction IR names, or pick a
  44. // scheme that doesn't change when IR names change.
  45. AddString(kind.ir_name());
  46. }
  47. auto Add(IdentifierId ident_id) -> void {
  48. AddString(sem_ir->identifiers().Get(ident_id));
  49. }
  50. auto Add(StringLiteralValueId lit_id) -> void {
  51. AddString(sem_ir->string_literal_values().Get(lit_id));
  52. }
  53. auto Add(NameId name_id) -> void {
  54. AddString(sem_ir->names().GetIRBaseName(name_id));
  55. }
  56. auto Add(EntityNameId entity_name_id) -> void {
  57. if (!entity_name_id.has_value()) {
  58. AddInvalid();
  59. return;
  60. }
  61. const auto& entity_name = sem_ir->entity_names().Get(entity_name_id);
  62. if (entity_name.bind_index.has_value()) {
  63. Add(entity_name.bind_index);
  64. // Don't include the name. While it is part of the canonical identity of a
  65. // compile-time binding, renaming it (and its uses) is a compatible change
  66. // that we would like to not affect the fingerprint.
  67. } else {
  68. Add(entity_name.name_id);
  69. }
  70. // TODO: Should we include the parent index?
  71. }
  72. auto AddInFile(const File* file, InstId inner_id) -> void {
  73. if (!inner_id.has_value()) {
  74. AddInvalid();
  75. return;
  76. }
  77. if (auto lookup = fingerprints->Lookup(std::pair(file, inner_id))) {
  78. contents.push_back(lookup.value());
  79. } else {
  80. todo.push_back({file, inner_id});
  81. }
  82. }
  83. auto Add(InstId inner_id) -> void { AddInFile(sem_ir, inner_id); }
  84. auto Add(ConstantId constant_id) -> void {
  85. if (!constant_id.has_value()) {
  86. AddInvalid();
  87. return;
  88. }
  89. Add(sem_ir->constant_values().GetInstId(constant_id));
  90. }
  91. auto Add(TypeId type_id) -> void {
  92. if (!type_id.has_value()) {
  93. AddInvalid();
  94. return;
  95. }
  96. Add(sem_ir->types().GetInstId(type_id));
  97. }
  98. template <typename T>
  99. auto AddBlock(llvm::ArrayRef<T> block) -> void {
  100. contents.push_back(block.size());
  101. for (auto inner_id : block) {
  102. Add(inner_id);
  103. }
  104. }
  105. auto Add(InstBlockId inst_block_id) -> void {
  106. if (!inst_block_id.has_value()) {
  107. AddInvalid();
  108. return;
  109. }
  110. AddBlock(sem_ir->inst_blocks().Get(inst_block_id));
  111. }
  112. auto Add(TypeBlockId type_block_id) -> void {
  113. if (!type_block_id.has_value()) {
  114. AddInvalid();
  115. return;
  116. }
  117. AddBlock(sem_ir->type_blocks().Get(type_block_id));
  118. }
  119. auto Add(StructTypeField field) -> void {
  120. Add(field.name_id);
  121. Add(field.type_id);
  122. }
  123. auto Add(StructTypeFieldsId struct_type_fields_id) -> void {
  124. if (!struct_type_fields_id.has_value()) {
  125. AddInvalid();
  126. return;
  127. }
  128. AddBlock(sem_ir->struct_type_fields().Get(struct_type_fields_id));
  129. }
  130. auto Add(NameScopeId name_scope_id) -> void {
  131. if (!name_scope_id.has_value()) {
  132. AddInvalid();
  133. return;
  134. }
  135. const auto& scope = sem_ir->name_scopes().Get(name_scope_id);
  136. Add(scope.name_id());
  137. if (!sem_ir->name_scopes().IsPackage(name_scope_id) &&
  138. scope.parent_scope_id().has_value()) {
  139. Add(sem_ir->name_scopes().Get(scope.parent_scope_id()).inst_id());
  140. }
  141. }
  142. template <typename EntityT = EntityWithParamsBase>
  143. auto AddEntity(const std::type_identity_t<EntityT>& entity) -> void {
  144. Add(entity.name_id);
  145. if (entity.parent_scope_id.has_value()) {
  146. Add(sem_ir->name_scopes().Get(entity.parent_scope_id).inst_id());
  147. }
  148. }
  149. auto Add(FunctionId function_id) -> void {
  150. AddEntity(sem_ir->functions().Get(function_id));
  151. }
  152. auto Add(ClassId class_id) -> void {
  153. AddEntity(sem_ir->classes().Get(class_id));
  154. }
  155. auto Add(InterfaceId interface_id) -> void {
  156. AddEntity(sem_ir->interfaces().Get(interface_id));
  157. }
  158. auto Add(AssociatedConstantId assoc_const_id) -> void {
  159. AddEntity<AssociatedConstant>(
  160. sem_ir->associated_constants().Get(assoc_const_id));
  161. }
  162. auto Add(ImplId impl_id) -> void {
  163. const auto& impl = sem_ir->impls().Get(impl_id);
  164. Add(sem_ir->constant_values().Get(impl.self_id));
  165. Add(sem_ir->constant_values().Get(impl.constraint_id));
  166. Add(impl.parent_scope_id);
  167. }
  168. auto Add(DeclInstBlockId /*block_id*/) -> void {
  169. // Intentionally exclude decl blocks from fingerprinting. Changes to the
  170. // decl block don't change the identity of the declaration.
  171. }
  172. auto Add(LabelId /*block_id*/) -> void {
  173. CARBON_FATAL("Should never fingerprint a label");
  174. }
  175. auto Add(FacetTypeId facet_type_id) -> void {
  176. const auto& facet_type = sem_ir->facet_types().Get(facet_type_id);
  177. for (auto [interface_id, specific_id] : facet_type.impls_constraints) {
  178. Add(interface_id);
  179. Add(specific_id);
  180. }
  181. for (auto [lhs_id, rhs_id] : facet_type.rewrite_constraints) {
  182. Add(lhs_id);
  183. Add(rhs_id);
  184. }
  185. contents.push_back(facet_type.other_requirements);
  186. }
  187. auto Add(GenericId generic_id) -> void {
  188. if (!generic_id.has_value()) {
  189. AddInvalid();
  190. return;
  191. }
  192. Add(sem_ir->generics().Get(generic_id).decl_id);
  193. }
  194. auto Add(SpecificId specific_id) -> void {
  195. if (!specific_id.has_value()) {
  196. AddInvalid();
  197. return;
  198. }
  199. const auto& specific = sem_ir->specifics().Get(specific_id);
  200. Add(specific.generic_id);
  201. Add(specific.args_id);
  202. }
  203. auto Add(const llvm::APInt& value) -> void {
  204. contents.push_back(value.getBitWidth());
  205. for (auto word : llvm::seq((value.getBitWidth() + 63) / 64)) {
  206. // TODO: Is there a better way to copy the words from an APInt?
  207. contents.push_back(value.extractBitsAsZExtValue(64, 64 * word));
  208. }
  209. }
  210. auto Add(IntId int_id) -> void { Add(sem_ir->ints().Get(int_id)); }
  211. auto Add(FloatId float_id) -> void {
  212. Add(sem_ir->floats().Get(float_id).bitcastToAPInt());
  213. }
  214. auto Add(LibraryNameId lib_name_id) -> void {
  215. if (lib_name_id == LibraryNameId::Default) {
  216. AddString("");
  217. } else if (lib_name_id == LibraryNameId::Error) {
  218. AddString("<error>");
  219. } else if (lib_name_id.has_value()) {
  220. Add(lib_name_id.AsStringLiteralValueId());
  221. } else {
  222. AddInvalid();
  223. }
  224. }
  225. auto Add(ImportIRId ir_id) -> void {
  226. const auto* ir = sem_ir->import_irs().Get(ir_id).sem_ir;
  227. Add(ir->package_id());
  228. Add(ir->library_id());
  229. }
  230. auto Add(ImportIRInstId ir_inst_id) -> void {
  231. auto ir_inst = sem_ir->import_ir_insts().Get(ir_inst_id);
  232. AddInFile(sem_ir->import_irs().Get(ir_inst.ir_id).sem_ir, ir_inst.inst_id);
  233. }
  234. template <typename T>
  235. requires(std::same_as<T, BoolValue> ||
  236. std::same_as<T, CompileTimeBindIndex> ||
  237. std::same_as<T, ElementIndex> || std::same_as<T, FloatKind> ||
  238. std::same_as<T, IntKind> || std::same_as<T, RuntimeParamIndex>)
  239. auto Add(T arg) -> void {
  240. // Index-like ID: just include the value directly.
  241. contents.push_back(arg.index);
  242. }
  243. template <typename T>
  244. requires(std::same_as<T, AnyRawId> || std::same_as<T, ExprRegionId> ||
  245. std::same_as<T, LocId> || std::same_as<T, RealId>)
  246. auto Add(T /*arg*/) -> void {
  247. CARBON_FATAL("Unexpected instruction operand kind {0}", typeid(T).name());
  248. }
  249. // Add an instruction argument to the contents of the current instruction.
  250. template <typename... Types>
  251. auto AddWithKind(uint64_t arg, TypeEnum<Types...> kind) -> void {
  252. using AddFunction = void (*)(Worklist& worklist, uint64_t arg);
  253. using Kind = decltype(kind);
  254. // Build a lookup table to add an argument of the given kind.
  255. static constexpr std::array<AddFunction, Kind::NumTypes + 2> Table = [] {
  256. std::array<AddFunction, Kind::NumTypes + 2> table;
  257. table[Kind::None.ToIndex()] = [](Worklist& /*worklist*/,
  258. uint64_t /*arg*/) {};
  259. table[Kind::Invalid.ToIndex()] = [](Worklist& /*worklist*/,
  260. uint64_t /*arg*/) {
  261. CARBON_FATAL("Unexpected invalid argument kind");
  262. };
  263. ((table[Kind::template For<Types>.ToIndex()] =
  264. [](Worklist& worklist, uint64_t arg) {
  265. return worklist.Add(Inst::FromRaw<Types>(arg));
  266. }),
  267. ...);
  268. return table;
  269. }();
  270. Table[kind.ToIndex()](*this, arg);
  271. }
  272. // Ensure all the instructions on the todo list have fingerprints. To avoid a
  273. // re-lookup, returns the fingerprint of the first instruction on the todo
  274. // list, and requires the todo list to be non-empty.
  275. auto Run() -> uint64_t {
  276. CARBON_CHECK(!todo.empty());
  277. while (true) {
  278. const size_t init_size = todo.size();
  279. auto [next_sem_ir, next_inst_id_or_block] = todo.back();
  280. sem_ir = next_sem_ir;
  281. contents.clear();
  282. if (auto* inst_block_id =
  283. std::get_if<InstBlockId>(&next_inst_id_or_block)) {
  284. // Add all the instructions in the block so they all contribute to the
  285. // `contents`.
  286. Add(*inst_block_id);
  287. // If we didn't add any more work, then we have a fingerprint for the
  288. // instruction block, otherwise we wait until that work is completed. If
  289. // the block is the last thing in `todo`, we return the fingerprint.
  290. // Otherwise we would just discard it because we don't currently cache
  291. // the fingerprint for blocks, but we really only expect `InstBlockId`
  292. // to be at the bottom of the `todo` stack since they are not added to
  293. // `todo` during Run().
  294. if (todo.size() == init_size) {
  295. auto fingerprint = Finish();
  296. todo.pop_back();
  297. CARBON_CHECK(todo.empty(),
  298. "An InstBlockId was inserted into `todo` during Run()");
  299. return fingerprint;
  300. }
  301. // Move on to processing the instructions in the block; we will come
  302. // back to this branch once they are done.
  303. continue;
  304. }
  305. auto next_inst_id = std::get<InstId>(next_inst_id_or_block);
  306. // If we already have a fingerprint for this instruction, we have nothing
  307. // to do. Just pop it from `todo`.
  308. if (auto lookup =
  309. fingerprints->Lookup(std::pair(next_sem_ir, next_inst_id))) {
  310. todo.pop_back();
  311. if (todo.empty()) {
  312. return lookup.value();
  313. }
  314. continue;
  315. }
  316. // Keep this instruction in `todo` for now. If we add more work, we'll
  317. // finish that work and process this instruction again, and if not, we'll
  318. // pop the instruction at the end of the loop.
  319. auto inst = next_sem_ir->insts().Get(next_inst_id);
  320. auto [arg0_kind, arg1_kind] = inst.ArgKinds();
  321. // Add the instruction's fields to the contents.
  322. Add(inst.kind());
  323. // Don't include the type if it's `type` or `<error>`, because those types
  324. // are self-referential.
  325. if (inst.type_id() != TypeType::SingletonTypeId &&
  326. inst.type_id() != ErrorInst::SingletonTypeId) {
  327. Add(inst.type_id());
  328. }
  329. AddWithKind(inst.arg0(), arg0_kind);
  330. AddWithKind(inst.arg1(), arg1_kind);
  331. // If we didn't add any work, we have a fingerprint for this instruction;
  332. // pop it from the todo list. Otherwise, we leave it on the todo list so
  333. // we can compute its fingerprint once we've finished the work we added.
  334. if (todo.size() == init_size) {
  335. uint64_t fingerprint = Finish();
  336. fingerprints->Insert(std::pair(next_sem_ir, next_inst_id), fingerprint);
  337. todo.pop_back();
  338. if (todo.empty()) {
  339. return fingerprint;
  340. }
  341. }
  342. }
  343. }
  344. };
  345. } // namespace
  346. auto InstFingerprinter::GetOrCompute(const File* file, InstId inst_id)
  347. -> uint64_t {
  348. Worklist worklist = {.todo = {{file, inst_id}},
  349. .fingerprints = &fingerprints_};
  350. return worklist.Run();
  351. }
  352. auto InstFingerprinter::GetOrCompute(const File* file,
  353. InstBlockId inst_block_id) -> uint64_t {
  354. Worklist worklist = {.todo = {{file, inst_block_id}},
  355. .fingerprints = &fingerprints_};
  356. return worklist.Run();
  357. }
  358. } // namespace Carbon::SemIR