fact_manager.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  1. // Copyright (c) 2019 Google LLC
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include "source/fuzz/fact_manager.h"
  15. #include <sstream>
  16. #include <unordered_map>
  17. #include <unordered_set>
  18. #include "source/fuzz/equivalence_relation.h"
  19. #include "source/fuzz/fuzzer_util.h"
  20. #include "source/fuzz/uniform_buffer_element_descriptor.h"
  21. #include "source/opt/ir_context.h"
  22. namespace spvtools {
  23. namespace fuzz {
  24. namespace {
  25. std::string ToString(const protobufs::Fact& fact) {
  26. assert(fact.fact_case() == protobufs::Fact::kConstantUniformFact &&
  27. "Right now this is the only fact we know how to stringify.");
  28. std::stringstream stream;
  29. stream << "("
  30. << fact.constant_uniform_fact()
  31. .uniform_buffer_element_descriptor()
  32. .descriptor_set()
  33. << ", "
  34. << fact.constant_uniform_fact()
  35. .uniform_buffer_element_descriptor()
  36. .binding()
  37. << ")[";
  38. bool first = true;
  39. for (auto index : fact.constant_uniform_fact()
  40. .uniform_buffer_element_descriptor()
  41. .index()) {
  42. if (first) {
  43. first = false;
  44. } else {
  45. stream << ", ";
  46. }
  47. stream << index;
  48. }
  49. stream << "] == [";
  50. first = true;
  51. for (auto constant_word : fact.constant_uniform_fact().constant_word()) {
  52. if (first) {
  53. first = false;
  54. } else {
  55. stream << ", ";
  56. }
  57. stream << constant_word;
  58. }
  59. stream << "]";
  60. return stream.str();
  61. }
  62. } // namespace
  63. //=======================
  64. // Constant uniform facts
  65. // The purpose of this class is to group the fields and data used to represent
  66. // facts about uniform constants.
  67. class FactManager::ConstantUniformFacts {
  68. public:
  69. // See method in FactManager which delegates to this method.
  70. bool AddFact(const protobufs::FactConstantUniform& fact,
  71. opt::IRContext* context);
  72. // See method in FactManager which delegates to this method.
  73. std::vector<uint32_t> GetConstantsAvailableFromUniformsForType(
  74. opt::IRContext* ir_context, uint32_t type_id) const;
  75. // See method in FactManager which delegates to this method.
  76. const std::vector<protobufs::UniformBufferElementDescriptor>
  77. GetUniformDescriptorsForConstant(opt::IRContext* ir_context,
  78. uint32_t constant_id) const;
  79. // See method in FactManager which delegates to this method.
  80. uint32_t GetConstantFromUniformDescriptor(
  81. opt::IRContext* context,
  82. const protobufs::UniformBufferElementDescriptor& uniform_descriptor)
  83. const;
  84. // See method in FactManager which delegates to this method.
  85. std::vector<uint32_t> GetTypesForWhichUniformValuesAreKnown() const;
  86. // See method in FactManager which delegates to this method.
  87. const std::vector<std::pair<protobufs::FactConstantUniform, uint32_t>>&
  88. GetConstantUniformFactsAndTypes() const;
  89. private:
  90. // Returns true if and only if the words associated with
  91. // |constant_instruction| exactly match the words for the constant associated
  92. // with |constant_uniform_fact|.
  93. bool DataMatches(
  94. const opt::Instruction& constant_instruction,
  95. const protobufs::FactConstantUniform& constant_uniform_fact) const;
  96. // Yields the constant words associated with |constant_uniform_fact|.
  97. std::vector<uint32_t> GetConstantWords(
  98. const protobufs::FactConstantUniform& constant_uniform_fact) const;
  99. // Yields the id of a constant of type |type_id| whose data matches the
  100. // constant data in |constant_uniform_fact|, or 0 if no such constant is
  101. // declared.
  102. uint32_t GetConstantId(
  103. opt::IRContext* context,
  104. const protobufs::FactConstantUniform& constant_uniform_fact,
  105. uint32_t type_id) const;
  106. // Checks that the width of a floating-point constant is supported, and that
  107. // the constant is finite.
  108. bool FloatingPointValueIsSuitable(const protobufs::FactConstantUniform& fact,
  109. uint32_t width) const;
  110. std::vector<std::pair<protobufs::FactConstantUniform, uint32_t>>
  111. facts_and_type_ids_;
  112. };
  113. uint32_t FactManager::ConstantUniformFacts::GetConstantId(
  114. opt::IRContext* context,
  115. const protobufs::FactConstantUniform& constant_uniform_fact,
  116. uint32_t type_id) const {
  117. auto type = context->get_type_mgr()->GetType(type_id);
  118. assert(type != nullptr && "Unknown type id.");
  119. auto constant = context->get_constant_mgr()->GetConstant(
  120. type, GetConstantWords(constant_uniform_fact));
  121. return context->get_constant_mgr()->FindDeclaredConstant(constant, type_id);
  122. }
  123. std::vector<uint32_t> FactManager::ConstantUniformFacts::GetConstantWords(
  124. const protobufs::FactConstantUniform& constant_uniform_fact) const {
  125. std::vector<uint32_t> result;
  126. for (auto constant_word : constant_uniform_fact.constant_word()) {
  127. result.push_back(constant_word);
  128. }
  129. return result;
  130. }
  131. bool FactManager::ConstantUniformFacts::DataMatches(
  132. const opt::Instruction& constant_instruction,
  133. const protobufs::FactConstantUniform& constant_uniform_fact) const {
  134. assert(constant_instruction.opcode() == SpvOpConstant);
  135. std::vector<uint32_t> data_in_constant;
  136. for (uint32_t i = 0; i < constant_instruction.NumInOperands(); i++) {
  137. data_in_constant.push_back(constant_instruction.GetSingleWordInOperand(i));
  138. }
  139. return data_in_constant == GetConstantWords(constant_uniform_fact);
  140. }
  141. std::vector<uint32_t>
  142. FactManager::ConstantUniformFacts::GetConstantsAvailableFromUniformsForType(
  143. opt::IRContext* ir_context, uint32_t type_id) const {
  144. std::vector<uint32_t> result;
  145. std::set<uint32_t> already_seen;
  146. for (auto& fact_and_type_id : facts_and_type_ids_) {
  147. if (fact_and_type_id.second != type_id) {
  148. continue;
  149. }
  150. if (auto constant_id =
  151. GetConstantId(ir_context, fact_and_type_id.first, type_id)) {
  152. if (already_seen.find(constant_id) == already_seen.end()) {
  153. result.push_back(constant_id);
  154. already_seen.insert(constant_id);
  155. }
  156. }
  157. }
  158. return result;
  159. }
  160. const std::vector<protobufs::UniformBufferElementDescriptor>
  161. FactManager::ConstantUniformFacts::GetUniformDescriptorsForConstant(
  162. opt::IRContext* ir_context, uint32_t constant_id) const {
  163. std::vector<protobufs::UniformBufferElementDescriptor> result;
  164. auto constant_inst = ir_context->get_def_use_mgr()->GetDef(constant_id);
  165. assert(constant_inst->opcode() == SpvOpConstant &&
  166. "The given id must be that of a constant");
  167. auto type_id = constant_inst->type_id();
  168. for (auto& fact_and_type_id : facts_and_type_ids_) {
  169. if (fact_and_type_id.second != type_id) {
  170. continue;
  171. }
  172. if (DataMatches(*constant_inst, fact_and_type_id.first)) {
  173. result.emplace_back(
  174. fact_and_type_id.first.uniform_buffer_element_descriptor());
  175. }
  176. }
  177. return result;
  178. }
  179. uint32_t FactManager::ConstantUniformFacts::GetConstantFromUniformDescriptor(
  180. opt::IRContext* context,
  181. const protobufs::UniformBufferElementDescriptor& uniform_descriptor) const {
  182. // Consider each fact.
  183. for (auto& fact_and_type : facts_and_type_ids_) {
  184. // Check whether the uniform descriptor associated with the fact matches
  185. // |uniform_descriptor|.
  186. if (UniformBufferElementDescriptorEquals()(
  187. &uniform_descriptor,
  188. &fact_and_type.first.uniform_buffer_element_descriptor())) {
  189. return GetConstantId(context, fact_and_type.first, fact_and_type.second);
  190. }
  191. }
  192. // No fact associated with the given uniform descriptor was found.
  193. return 0;
  194. }
  195. std::vector<uint32_t>
  196. FactManager::ConstantUniformFacts::GetTypesForWhichUniformValuesAreKnown()
  197. const {
  198. std::vector<uint32_t> result;
  199. for (auto& fact_and_type : facts_and_type_ids_) {
  200. if (std::find(result.begin(), result.end(), fact_and_type.second) ==
  201. result.end()) {
  202. result.push_back(fact_and_type.second);
  203. }
  204. }
  205. return result;
  206. }
  207. bool FactManager::ConstantUniformFacts::FloatingPointValueIsSuitable(
  208. const protobufs::FactConstantUniform& fact, uint32_t width) const {
  209. const uint32_t kFloatWidth = 32;
  210. const uint32_t kDoubleWidth = 64;
  211. if (width != kFloatWidth && width != kDoubleWidth) {
  212. // Only 32- and 64-bit floating-point types are handled.
  213. return false;
  214. }
  215. std::vector<uint32_t> words = GetConstantWords(fact);
  216. if (width == 32) {
  217. float value;
  218. memcpy(&value, words.data(), sizeof(float));
  219. if (!std::isfinite(value)) {
  220. return false;
  221. }
  222. } else {
  223. double value;
  224. memcpy(&value, words.data(), sizeof(double));
  225. if (!std::isfinite(value)) {
  226. return false;
  227. }
  228. }
  229. return true;
  230. }
  231. bool FactManager::ConstantUniformFacts::AddFact(
  232. const protobufs::FactConstantUniform& fact, opt::IRContext* context) {
  233. // Try to find a unique instruction that declares a variable such that the
  234. // variable is decorated with the descriptor set and binding associated with
  235. // the constant uniform fact.
  236. opt::Instruction* uniform_variable = FindUniformVariable(
  237. fact.uniform_buffer_element_descriptor(), context, true);
  238. if (!uniform_variable) {
  239. return false;
  240. }
  241. assert(SpvOpVariable == uniform_variable->opcode());
  242. assert(SpvStorageClassUniform == uniform_variable->GetSingleWordInOperand(0));
  243. auto should_be_uniform_pointer_type =
  244. context->get_type_mgr()->GetType(uniform_variable->type_id());
  245. if (!should_be_uniform_pointer_type->AsPointer()) {
  246. return false;
  247. }
  248. if (should_be_uniform_pointer_type->AsPointer()->storage_class() !=
  249. SpvStorageClassUniform) {
  250. return false;
  251. }
  252. auto should_be_uniform_pointer_instruction =
  253. context->get_def_use_mgr()->GetDef(uniform_variable->type_id());
  254. auto composite_type =
  255. should_be_uniform_pointer_instruction->GetSingleWordInOperand(1);
  256. auto final_element_type_id = fuzzerutil::WalkCompositeTypeIndices(
  257. context, composite_type,
  258. fact.uniform_buffer_element_descriptor().index());
  259. if (!final_element_type_id) {
  260. return false;
  261. }
  262. auto final_element_type =
  263. context->get_type_mgr()->GetType(final_element_type_id);
  264. assert(final_element_type &&
  265. "There should be a type corresponding to this id.");
  266. if (!(final_element_type->AsFloat() || final_element_type->AsInteger())) {
  267. return false;
  268. }
  269. auto width = final_element_type->AsFloat()
  270. ? final_element_type->AsFloat()->width()
  271. : final_element_type->AsInteger()->width();
  272. if (final_element_type->AsFloat() &&
  273. !FloatingPointValueIsSuitable(fact, width)) {
  274. return false;
  275. }
  276. auto required_words = (width + 32 - 1) / 32;
  277. if (static_cast<uint32_t>(fact.constant_word().size()) != required_words) {
  278. return false;
  279. }
  280. facts_and_type_ids_.emplace_back(
  281. std::pair<protobufs::FactConstantUniform, uint32_t>(
  282. fact, final_element_type_id));
  283. return true;
  284. }
  285. const std::vector<std::pair<protobufs::FactConstantUniform, uint32_t>>&
  286. FactManager::ConstantUniformFacts::GetConstantUniformFactsAndTypes() const {
  287. return facts_and_type_ids_;
  288. }
  289. // End of uniform constant facts
  290. //==============================
  291. //==============================
  292. // Data synonym facts
  293. // The purpose of this class is to group the fields and data used to represent
  294. // facts about data synonyms.
  295. class FactManager::DataSynonymFacts {
  296. public:
  297. // See method in FactManager which delegates to this method.
  298. void AddFact(const protobufs::FactDataSynonym& fact, opt::IRContext* context);
  299. // See method in FactManager which delegates to this method.
  300. std::vector<const protobufs::DataDescriptor*> GetSynonymsForDataDescriptor(
  301. const protobufs::DataDescriptor& data_descriptor,
  302. opt::IRContext* context) const;
  303. // See method in FactManager which delegates to this method.
  304. std::vector<uint32_t> GetIdsForWhichSynonymsAreKnown(
  305. opt::IRContext* context) const;
  306. // See method in FactManager which delegates to this method.
  307. bool IsSynonymous(const protobufs::DataDescriptor& data_descriptor1,
  308. const protobufs::DataDescriptor& data_descriptor2,
  309. opt::IRContext* context) const;
  310. private:
  311. // Adds |fact| to the set of managed facts, and recurses into sub-components
  312. // of the data descriptors referenced in |fact|, if they are composites, to
  313. // record that their components are pairwise-synonymous.
  314. void AddFactRecursive(const protobufs::FactDataSynonym& fact,
  315. opt::IRContext* context);
  316. // Inspects all known facts and adds corollary facts; e.g. if we know that
  317. // a.x == b.x and a.y == b.y, where a and b have vec2 type, we can record
  318. // that a == b holds.
  319. //
  320. // This method is expensive, and is thus called on demand: rather than
  321. // computing the closure of facts each time a data synonym fact is added, we
  322. // compute the closure only when a data synonym fact is *queried*.
  323. void ComputeClosureOfFacts(opt::IRContext* context) const;
  324. // Returns true if and only if |dd1| and |dd2| are valid data descriptors
  325. // whose associated data have the same type.
  326. bool DataDescriptorsAreWellFormedAndComparable(
  327. opt::IRContext* context, const protobufs::DataDescriptor& dd1,
  328. const protobufs::DataDescriptor& dd2) const;
  329. // The data descriptors that are known to be synonymous with one another are
  330. // captured by this equivalence relation.
  331. //
  332. // This member is mutable in order to allow the closure of facts captured by
  333. // the relation to be computed lazily when a question about data synonym
  334. // facts is asked.
  335. mutable EquivalenceRelation<protobufs::DataDescriptor, DataDescriptorHash,
  336. DataDescriptorEquals>
  337. synonymous_;
  338. // When a new synonym fact is added, it may be possible to deduce further
  339. // synonym facts by computing a closure of all known facts. However, there is
  340. // no point computing this closure until a question regarding synonym facts is
  341. // actually asked: if several facts are added in succession with no questions
  342. // asked in between, we can avoid computing fact closures multiple times.
  343. //
  344. // This boolean tracks whether a closure computation is required - i.e.,
  345. // whether a new fact has been added since the last time such a computation
  346. // was performed.
  347. //
  348. // It is mutable so faciliate having const methods, that provide answers to
  349. // questions about data synonym facts, triggering closure computation on
  350. // demand.
  351. mutable bool closure_computation_required = false;
  352. };
  353. void FactManager::DataSynonymFacts::AddFact(
  354. const protobufs::FactDataSynonym& fact, opt::IRContext* context) {
  355. // Add the fact, including all facts relating sub-components of the data
  356. // descriptors that are involved.
  357. AddFactRecursive(fact, context);
  358. }
  359. void FactManager::DataSynonymFacts::AddFactRecursive(
  360. const protobufs::FactDataSynonym& fact, opt::IRContext* context) {
  361. assert(DataDescriptorsAreWellFormedAndComparable(context, fact.data1(),
  362. fact.data2()));
  363. // Record that the data descriptors provided in the fact are equivalent.
  364. synonymous_.MakeEquivalent(fact.data1(), fact.data2());
  365. // As we have updated the equivalence relation, we might be able to deduce
  366. // more facts by performing a closure computation, so we record that such a
  367. // computation is required; it will be performed next time a method answering
  368. // a data synonym fact-related question is invoked.
  369. closure_computation_required = true;
  370. // We now check whether this is a synonym about composite objects. If it is,
  371. // we can recursively add synonym facts about their associated sub-components.
  372. // Get the type of the object referred to by the first data descriptor in the
  373. // synonym fact.
  374. uint32_t type_id = fuzzerutil::WalkCompositeTypeIndices(
  375. context,
  376. context->get_def_use_mgr()->GetDef(fact.data1().object())->type_id(),
  377. fact.data1().index());
  378. auto type = context->get_type_mgr()->GetType(type_id);
  379. auto type_instruction = context->get_def_use_mgr()->GetDef(type_id);
  380. assert(type != nullptr &&
  381. "Invalid data synonym fact: one side has an unknown type.");
  382. // Check whether the type is composite, recording the number of elements
  383. // associated with the composite if so.
  384. uint32_t num_composite_elements;
  385. if (type->AsArray()) {
  386. num_composite_elements =
  387. fuzzerutil::GetArraySize(*type_instruction, context);
  388. } else if (type->AsMatrix()) {
  389. num_composite_elements = type->AsMatrix()->element_count();
  390. } else if (type->AsStruct()) {
  391. num_composite_elements =
  392. fuzzerutil::GetNumberOfStructMembers(*type_instruction);
  393. } else if (type->AsVector()) {
  394. num_composite_elements = type->AsVector()->element_count();
  395. } else {
  396. // The type is not a composite, so return.
  397. return;
  398. }
  399. // If the fact has the form:
  400. // obj_1[a_1, ..., a_m] == obj_2[b_1, ..., b_n]
  401. // then for each composite index i, we add a fact of the form:
  402. // obj_1[a_1, ..., a_m, i] == obj_2[b_1, ..., b_n, i]
  403. for (uint32_t i = 0; i < num_composite_elements; i++) {
  404. std::vector<uint32_t> extended_indices1 =
  405. fuzzerutil::RepeatedFieldToVector(fact.data1().index());
  406. extended_indices1.push_back(i);
  407. std::vector<uint32_t> extended_indices2 =
  408. fuzzerutil::RepeatedFieldToVector(fact.data2().index());
  409. extended_indices2.push_back(i);
  410. protobufs::FactDataSynonym extended_data_synonym_fact;
  411. *extended_data_synonym_fact.mutable_data1() =
  412. MakeDataDescriptor(fact.data1().object(), std::move(extended_indices1));
  413. *extended_data_synonym_fact.mutable_data2() =
  414. MakeDataDescriptor(fact.data2().object(), std::move(extended_indices2));
  415. AddFactRecursive(extended_data_synonym_fact, context);
  416. }
  417. }
  418. void FactManager::DataSynonymFacts::ComputeClosureOfFacts(
  419. opt::IRContext* context) const {
  420. // Suppose that obj_1[a_1, ..., a_m] and obj_2[b_1, ..., b_n] are distinct
  421. // data descriptors that describe objects of the same composite type, and that
  422. // the composite type is comprised of k components.
  423. //
  424. // For example, if m is a mat4x4 and v a vec4, we might consider:
  425. // m[2]: describes the 2nd column of m, a vec4
  426. // v[]: describes all of v, a vec4
  427. //
  428. // Suppose that we know, for every 0 <= i < k, that the fact:
  429. // obj_1[a_1, ..., a_m, i] == obj_2[b_1, ..., b_n, i]
  430. // holds - i.e. that the children of the two data descriptors are synonymous.
  431. //
  432. // Then we can conclude that:
  433. // obj_1[a_1, ..., a_m] == obj_2[b_1, ..., b_n]
  434. // holds.
  435. //
  436. // For instance, if we have the facts:
  437. // m[2, 0] == v[0]
  438. // m[2, 1] == v[1]
  439. // m[2, 2] == v[2]
  440. // m[2, 3] == v[3]
  441. // then we can conclude that:
  442. // m[2] == v.
  443. //
  444. // This method repeatedly searches the equivalence relation of data
  445. // descriptors, deducing and adding such facts, until a pass over the
  446. // relation leads to no further facts being deduced.
  447. // The method relies on working with pairs of data descriptors, and in
  448. // particular being able to hash and compare such pairs.
  449. using DataDescriptorPair =
  450. std::pair<protobufs::DataDescriptor, protobufs::DataDescriptor>;
  451. struct DataDescriptorPairHash {
  452. std::size_t operator()(const DataDescriptorPair& pair) const {
  453. return DataDescriptorHash()(&pair.first) ^
  454. DataDescriptorHash()(&pair.second);
  455. }
  456. };
  457. struct DataDescriptorPairEquals {
  458. bool operator()(const DataDescriptorPair& first,
  459. const DataDescriptorPair& second) const {
  460. return DataDescriptorEquals()(&first.first, &second.first) &&
  461. DataDescriptorEquals()(&first.second, &second.second);
  462. }
  463. };
  464. // This map records, for a given pair of composite data descriptors of the
  465. // same type, all the indices at which the data descriptors are known to be
  466. // synonymous. A pair is a key to this map only if we have observed that
  467. // the pair are synonymous at *some* index, but not at *all* indices.
  468. // Once we find that a pair of data descriptors are equivalent at all indices
  469. // we record the fact that they are synonymous and remove them from the map.
  470. //
  471. // Using the m and v example from above, initially the pair (m[2], v) would
  472. // not be a key to the map. If we find that m[2, 2] == v[2] holds, we would
  473. // add an entry:
  474. // (m[2], v) -> [false, false, true, false]
  475. // to record that they are synonymous at index 2. If we then find that
  476. // m[2, 0] == v[0] holds, we would update this entry to:
  477. // (m[2], v) -> [true, false, true, false]
  478. // If we then find that m[2, 3] == v[3] holds, we would update this entry to:
  479. // (m[2], v) -> [true, false, true, true]
  480. // Finally, if we then find that m[2, 1] == v[1] holds, which would make the
  481. // boolean vector true at every index, we would add the fact:
  482. // m[2] == v
  483. // to the equivalence relation and remove (m[2], v) from the map.
  484. std::unordered_map<DataDescriptorPair, std::vector<bool>,
  485. DataDescriptorPairHash, DataDescriptorPairEquals>
  486. candidate_composite_synonyms;
  487. // We keep looking for new facts until we perform a complete pass over the
  488. // equivalence relation without finding any new facts.
  489. while (closure_computation_required) {
  490. // We have not found any new facts yet during this pass; we set this to
  491. // 'true' if we do find a new fact.
  492. closure_computation_required = false;
  493. // Consider each class in the equivalence relation.
  494. for (auto representative :
  495. synonymous_.GetEquivalenceClassRepresentatives()) {
  496. auto equivalence_class = synonymous_.GetEquivalenceClass(*representative);
  497. // Consider every data descriptor in the equivalence class.
  498. for (auto dd1_it = equivalence_class.begin();
  499. dd1_it != equivalence_class.end(); ++dd1_it) {
  500. // If this data descriptor has no indices then it does not have the form
  501. // obj_1[a_1, ..., a_m, i], so move on.
  502. auto dd1 = *dd1_it;
  503. if (dd1->index_size() == 0) {
  504. continue;
  505. }
  506. // Consider every other data descriptor later in the equivalence class
  507. // (due to symmetry, there is no need to compare with previous data
  508. // descriptors).
  509. auto dd2_it = dd1_it;
  510. for (++dd2_it; dd2_it != equivalence_class.end(); ++dd2_it) {
  511. auto dd2 = *dd2_it;
  512. // If this data descriptor has no indices then it does not have the
  513. // form obj_2[b_1, ..., b_n, i], so move on.
  514. if (dd2->index_size() == 0) {
  515. continue;
  516. }
  517. // At this point we know that:
  518. // - |dd1| has the form obj_1[a_1, ..., a_m, i]
  519. // - |dd2| has the form obj_2[b_1, ..., b_n, j]
  520. assert(dd1->index_size() > 0 && dd2->index_size() > 0 &&
  521. "Control should not reach here if either data descriptor has "
  522. "no indices.");
  523. // We are only interested if i == j.
  524. if (dd1->index(dd1->index_size() - 1) !=
  525. dd2->index(dd2->index_size() - 1)) {
  526. continue;
  527. }
  528. const uint32_t common_final_index = dd1->index(dd1->index_size() - 1);
  529. // Make data descriptors |dd1_prefix| and |dd2_prefix| for
  530. // obj_1[a_1, ..., a_m]
  531. // and
  532. // obj_2[b_1, ..., b_n]
  533. // These are the two data descriptors we might be getting closer to
  534. // deducing as being synonymous, due to knowing that they are
  535. // synonymous when extended by a particular index.
  536. protobufs::DataDescriptor dd1_prefix;
  537. dd1_prefix.set_object(dd1->object());
  538. for (uint32_t i = 0; i < static_cast<uint32_t>(dd1->index_size() - 1);
  539. i++) {
  540. dd1_prefix.add_index(dd1->index(i));
  541. }
  542. protobufs::DataDescriptor dd2_prefix;
  543. dd2_prefix.set_object(dd2->object());
  544. for (uint32_t i = 0; i < static_cast<uint32_t>(dd2->index_size() - 1);
  545. i++) {
  546. dd2_prefix.add_index(dd2->index(i));
  547. }
  548. assert(!DataDescriptorEquals()(&dd1_prefix, &dd2_prefix) &&
  549. "By construction these prefixes should be different.");
  550. // If we already know that these prefixes are synonymous, move on.
  551. if (synonymous_.Exists(dd1_prefix) &&
  552. synonymous_.Exists(dd2_prefix) &&
  553. synonymous_.IsEquivalent(dd1_prefix, dd2_prefix)) {
  554. continue;
  555. }
  556. // Get the type of obj_1
  557. auto dd1_root_type_id =
  558. context->get_def_use_mgr()->GetDef(dd1->object())->type_id();
  559. // Use this type, together with a_1, ..., a_m, to get the type of
  560. // obj_1[a_1, ..., a_m].
  561. auto dd1_prefix_type = fuzzerutil::WalkCompositeTypeIndices(
  562. context, dd1_root_type_id, dd1_prefix.index());
  563. // Similarly, get the type of obj_2 and use it to get the type of
  564. // obj_2[b_1, ..., b_n].
  565. auto dd2_root_type_id =
  566. context->get_def_use_mgr()->GetDef(dd2->object())->type_id();
  567. auto dd2_prefix_type = fuzzerutil::WalkCompositeTypeIndices(
  568. context, dd2_root_type_id, dd2_prefix.index());
  569. // If the types of dd1_prefix and dd2_prefix are not the same, they
  570. // cannot be synonymous.
  571. if (dd1_prefix_type != dd2_prefix_type) {
  572. continue;
  573. }
  574. // At this point, we know we have synonymous data descriptors of the
  575. // form:
  576. // obj_1[a_1, ..., a_m, i]
  577. // obj_2[b_1, ..., b_n, i]
  578. // with the same last_index i, such that:
  579. // obj_1[a_1, ..., a_m]
  580. // and
  581. // obj_2[b_1, ..., b_n]
  582. // have the same type.
  583. // Work out how many components there are in the (common) commposite
  584. // type associated with obj_1[a_1, ..., a_m] and obj_2[b_1, ..., b_n].
  585. // This depends on whether the composite type is array, matrix, struct
  586. // or vector.
  587. uint32_t num_components_in_composite;
  588. auto composite_type =
  589. context->get_type_mgr()->GetType(dd1_prefix_type);
  590. auto composite_type_instruction =
  591. context->get_def_use_mgr()->GetDef(dd1_prefix_type);
  592. if (composite_type->AsArray()) {
  593. num_components_in_composite =
  594. fuzzerutil::GetArraySize(*composite_type_instruction, context);
  595. if (num_components_in_composite == 0) {
  596. // This indicates that the array has an unknown size, in which
  597. // case we cannot be sure we have matched all of its elements with
  598. // synonymous elements of another array.
  599. continue;
  600. }
  601. } else if (composite_type->AsMatrix()) {
  602. num_components_in_composite =
  603. composite_type->AsMatrix()->element_count();
  604. } else if (composite_type->AsStruct()) {
  605. num_components_in_composite = fuzzerutil::GetNumberOfStructMembers(
  606. *composite_type_instruction);
  607. } else {
  608. assert(composite_type->AsVector());
  609. num_components_in_composite =
  610. composite_type->AsVector()->element_count();
  611. }
  612. // We are one step closer to being able to say that |dd1_prefix| and
  613. // |dd2_prefix| are synonymous.
  614. DataDescriptorPair candidate_composite_synonym(dd1_prefix,
  615. dd2_prefix);
  616. // We look up what we already know about this pair.
  617. auto existing_entry =
  618. candidate_composite_synonyms.find(candidate_composite_synonym);
  619. if (existing_entry == candidate_composite_synonyms.end()) {
  620. // If this is the first time we have seen the pair, we make a vector
  621. // of size |num_components_in_composite| that is 'true' at the
  622. // common final index associated with |dd1| and |dd2|, and 'false'
  623. // everywhere else, and register this vector as being associated
  624. // with the pair.
  625. std::vector<bool> entry;
  626. for (uint32_t i = 0; i < num_components_in_composite; i++) {
  627. entry.push_back(i == common_final_index);
  628. }
  629. candidate_composite_synonyms[candidate_composite_synonym] = entry;
  630. existing_entry =
  631. candidate_composite_synonyms.find(candidate_composite_synonym);
  632. } else {
  633. // We have seen this pair of data descriptors before, and we now
  634. // know that they are synonymous at one further index, so we
  635. // update the entry to record that.
  636. existing_entry->second[common_final_index] = true;
  637. }
  638. assert(existing_entry != candidate_composite_synonyms.end());
  639. // Check whether |dd1_prefix| and |dd2_prefix| are now known to match
  640. // at every sub-component.
  641. bool all_components_match = true;
  642. for (uint32_t i = 0; i < num_components_in_composite; i++) {
  643. if (!existing_entry->second[i]) {
  644. all_components_match = false;
  645. break;
  646. }
  647. }
  648. if (all_components_match) {
  649. // The two prefixes match on all sub-components, so we know that
  650. // they are synonymous. We add this fact *non-recursively*, as we
  651. // have deduced that |dd1_prefix| and |dd2_prefix| are synonymous
  652. // by observing that all their sub-components are already
  653. // synonymous.
  654. assert(DataDescriptorsAreWellFormedAndComparable(
  655. context, dd1_prefix, dd2_prefix));
  656. synonymous_.MakeEquivalent(dd1_prefix, dd2_prefix);
  657. // As we have added a new synonym fact, we might benefit from doing
  658. // another pass over the equivalence relation.
  659. closure_computation_required = true;
  660. // Now that we know this pair of data descriptors are synonymous,
  661. // there is no point recording how close they are to being
  662. // synonymous.
  663. candidate_composite_synonyms.erase(candidate_composite_synonym);
  664. }
  665. }
  666. }
  667. }
  668. }
  669. }
  670. bool FactManager::DataSynonymFacts::DataDescriptorsAreWellFormedAndComparable(
  671. opt::IRContext* context, const protobufs::DataDescriptor& dd1,
  672. const protobufs::DataDescriptor& dd2) const {
  673. auto end_type_1 = fuzzerutil::WalkCompositeTypeIndices(
  674. context, context->get_def_use_mgr()->GetDef(dd1.object())->type_id(),
  675. dd1.index());
  676. auto end_type_2 = fuzzerutil::WalkCompositeTypeIndices(
  677. context, context->get_def_use_mgr()->GetDef(dd2.object())->type_id(),
  678. dd2.index());
  679. return end_type_1 && end_type_1 == end_type_2;
  680. }
  681. std::vector<const protobufs::DataDescriptor*>
  682. FactManager::DataSynonymFacts::GetSynonymsForDataDescriptor(
  683. const protobufs::DataDescriptor& data_descriptor,
  684. opt::IRContext* context) const {
  685. ComputeClosureOfFacts(context);
  686. if (synonymous_.Exists(data_descriptor)) {
  687. return synonymous_.GetEquivalenceClass(data_descriptor);
  688. }
  689. return std::vector<const protobufs::DataDescriptor*>();
  690. }
  691. std::vector<uint32_t>
  692. FactManager::DataSynonymFacts ::GetIdsForWhichSynonymsAreKnown(
  693. opt::IRContext* context) const {
  694. ComputeClosureOfFacts(context);
  695. std::vector<uint32_t> result;
  696. for (auto& data_descriptor : synonymous_.GetAllKnownValues()) {
  697. if (data_descriptor->index().empty()) {
  698. result.push_back(data_descriptor->object());
  699. }
  700. }
  701. return result;
  702. }
  703. bool FactManager::DataSynonymFacts::IsSynonymous(
  704. const protobufs::DataDescriptor& data_descriptor1,
  705. const protobufs::DataDescriptor& data_descriptor2,
  706. opt::IRContext* context) const {
  707. const_cast<FactManager::DataSynonymFacts*>(this)->ComputeClosureOfFacts(
  708. context);
  709. return synonymous_.Exists(data_descriptor1) &&
  710. synonymous_.Exists(data_descriptor2) &&
  711. synonymous_.IsEquivalent(data_descriptor1, data_descriptor2);
  712. }
  713. // End of data synonym facts
  714. //==============================
  715. FactManager::FactManager()
  716. : uniform_constant_facts_(MakeUnique<ConstantUniformFacts>()),
  717. data_synonym_facts_(MakeUnique<DataSynonymFacts>()) {}
  718. FactManager::~FactManager() = default;
  719. void FactManager::AddFacts(const MessageConsumer& message_consumer,
  720. const protobufs::FactSequence& initial_facts,
  721. opt::IRContext* context) {
  722. for (auto& fact : initial_facts.fact()) {
  723. if (!AddFact(fact, context)) {
  724. message_consumer(
  725. SPV_MSG_WARNING, nullptr, {},
  726. ("Invalid fact " + ToString(fact) + " ignored.").c_str());
  727. }
  728. }
  729. }
  730. bool FactManager::AddFact(const fuzz::protobufs::Fact& fact,
  731. opt::IRContext* context) {
  732. switch (fact.fact_case()) {
  733. case protobufs::Fact::kConstantUniformFact:
  734. return uniform_constant_facts_->AddFact(fact.constant_uniform_fact(),
  735. context);
  736. case protobufs::Fact::kDataSynonymFact:
  737. data_synonym_facts_->AddFact(fact.data_synonym_fact(), context);
  738. return true;
  739. default:
  740. assert(false && "Unknown fact type.");
  741. return false;
  742. }
  743. }
  744. void FactManager::AddFactDataSynonym(const protobufs::DataDescriptor& data1,
  745. const protobufs::DataDescriptor& data2,
  746. opt::IRContext* context) {
  747. protobufs::FactDataSynonym fact;
  748. *fact.mutable_data1() = data1;
  749. *fact.mutable_data2() = data2;
  750. data_synonym_facts_->AddFact(fact, context);
  751. }
  752. std::vector<uint32_t> FactManager::GetConstantsAvailableFromUniformsForType(
  753. opt::IRContext* ir_context, uint32_t type_id) const {
  754. return uniform_constant_facts_->GetConstantsAvailableFromUniformsForType(
  755. ir_context, type_id);
  756. }
  757. const std::vector<protobufs::UniformBufferElementDescriptor>
  758. FactManager::GetUniformDescriptorsForConstant(opt::IRContext* ir_context,
  759. uint32_t constant_id) const {
  760. return uniform_constant_facts_->GetUniformDescriptorsForConstant(ir_context,
  761. constant_id);
  762. }
  763. uint32_t FactManager::GetConstantFromUniformDescriptor(
  764. opt::IRContext* context,
  765. const protobufs::UniformBufferElementDescriptor& uniform_descriptor) const {
  766. return uniform_constant_facts_->GetConstantFromUniformDescriptor(
  767. context, uniform_descriptor);
  768. }
  769. std::vector<uint32_t> FactManager::GetTypesForWhichUniformValuesAreKnown()
  770. const {
  771. return uniform_constant_facts_->GetTypesForWhichUniformValuesAreKnown();
  772. }
  773. const std::vector<std::pair<protobufs::FactConstantUniform, uint32_t>>&
  774. FactManager::GetConstantUniformFactsAndTypes() const {
  775. return uniform_constant_facts_->GetConstantUniformFactsAndTypes();
  776. }
  777. std::vector<uint32_t> FactManager::GetIdsForWhichSynonymsAreKnown(
  778. opt::IRContext* context) const {
  779. return data_synonym_facts_->GetIdsForWhichSynonymsAreKnown(context);
  780. }
  781. std::vector<const protobufs::DataDescriptor*>
  782. FactManager::GetSynonymsForDataDescriptor(
  783. const protobufs::DataDescriptor& data_descriptor,
  784. opt::IRContext* context) const {
  785. return data_synonym_facts_->GetSynonymsForDataDescriptor(data_descriptor,
  786. context);
  787. }
  788. std::vector<const protobufs::DataDescriptor*> FactManager::GetSynonymsForId(
  789. uint32_t id, opt::IRContext* context) const {
  790. return GetSynonymsForDataDescriptor(MakeDataDescriptor(id, {}), context);
  791. }
  792. bool FactManager::IsSynonymous(
  793. const protobufs::DataDescriptor& data_descriptor1,
  794. const protobufs::DataDescriptor& data_descriptor2,
  795. opt::IRContext* context) const {
  796. return data_synonym_facts_->IsSynonymous(data_descriptor1, data_descriptor2,
  797. context);
  798. }
  799. } // namespace fuzz
  800. } // namespace spvtools