inst_fingerprinter.cpp 15 KB

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