force_render_red.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  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/force_render_red.h"
  15. #include "source/fuzz/fact_manager.h"
  16. #include "source/fuzz/protobufs/spirvfuzz_protobufs.h"
  17. #include "source/fuzz/transformation_replace_constant_with_uniform.h"
  18. #include "source/fuzz/uniform_buffer_element_descriptor.h"
  19. #include "source/opt/build_module.h"
  20. #include "source/opt/ir_context.h"
  21. #include "source/opt/types.h"
  22. #include "source/util/make_unique.h"
  23. #include "tools/util/cli_consumer.h"
  24. #include <algorithm>
  25. #include <utility>
  26. namespace spvtools {
  27. namespace fuzz {
  28. namespace {
  29. // Helper method to find the fragment shader entry point, complaining if there
  30. // is no shader or if there is no fragment entry point.
  31. opt::Function* FindFragmentShaderEntryPoint(opt::IRContext* ir_context,
  32. MessageConsumer message_consumer) {
  33. // Check that this is a fragment shader
  34. bool found_capability_shader = false;
  35. for (auto& capability : ir_context->capabilities()) {
  36. assert(capability.opcode() == SpvOpCapability);
  37. if (capability.GetSingleWordInOperand(0) == SpvCapabilityShader) {
  38. found_capability_shader = true;
  39. break;
  40. }
  41. }
  42. if (!found_capability_shader) {
  43. message_consumer(
  44. SPV_MSG_ERROR, nullptr, {},
  45. "Forcing of red rendering requires the Shader capability.");
  46. return nullptr;
  47. }
  48. opt::Instruction* fragment_entry_point = nullptr;
  49. for (auto& entry_point : ir_context->module()->entry_points()) {
  50. if (entry_point.GetSingleWordInOperand(0) == SpvExecutionModelFragment) {
  51. fragment_entry_point = &entry_point;
  52. break;
  53. }
  54. }
  55. if (fragment_entry_point == nullptr) {
  56. message_consumer(SPV_MSG_ERROR, nullptr, {},
  57. "Forcing of red rendering requires an entry point with "
  58. "the Fragment execution model.");
  59. return nullptr;
  60. }
  61. for (auto& function : *ir_context->module()) {
  62. if (function.result_id() ==
  63. fragment_entry_point->GetSingleWordInOperand(1)) {
  64. return &function;
  65. }
  66. }
  67. assert(
  68. false &&
  69. "A valid module must have a function associate with each entry point.");
  70. return nullptr;
  71. }
  72. // Helper method to check that there is a single vec4 output variable and get a
  73. // pointer to it.
  74. opt::Instruction* FindVec4OutputVariable(opt::IRContext* ir_context,
  75. MessageConsumer message_consumer) {
  76. opt::Instruction* output_variable = nullptr;
  77. for (auto& inst : ir_context->types_values()) {
  78. if (inst.opcode() == SpvOpVariable &&
  79. inst.GetSingleWordInOperand(0) == SpvStorageClassOutput) {
  80. if (output_variable != nullptr) {
  81. message_consumer(SPV_MSG_ERROR, nullptr, {},
  82. "Only one output variable can be handled at present; "
  83. "found multiple.");
  84. return nullptr;
  85. }
  86. output_variable = &inst;
  87. // Do not break, as we want to check for multiple output variables.
  88. }
  89. }
  90. if (output_variable == nullptr) {
  91. message_consumer(SPV_MSG_ERROR, nullptr, {},
  92. "No output variable to which to write red was found.");
  93. return nullptr;
  94. }
  95. auto output_variable_base_type = ir_context->get_type_mgr()
  96. ->GetType(output_variable->type_id())
  97. ->AsPointer()
  98. ->pointee_type()
  99. ->AsVector();
  100. if (!output_variable_base_type ||
  101. output_variable_base_type->element_count() != 4 ||
  102. !output_variable_base_type->element_type()->AsFloat()) {
  103. message_consumer(SPV_MSG_ERROR, nullptr, {},
  104. "The output variable must have type vec4.");
  105. return nullptr;
  106. }
  107. return output_variable;
  108. }
  109. // Helper to get the ids of float constants 0.0 and 1.0, creating them if
  110. // necessary.
  111. std::pair<uint32_t, uint32_t> FindOrCreateFloatZeroAndOne(
  112. opt::IRContext* ir_context, opt::analysis::Float* float_type) {
  113. float one = 1.0;
  114. uint32_t one_as_uint;
  115. memcpy(&one_as_uint, &one, sizeof(float));
  116. std::vector<uint32_t> zero_bytes = {0};
  117. std::vector<uint32_t> one_bytes = {one_as_uint};
  118. auto constant_zero = ir_context->get_constant_mgr()->RegisterConstant(
  119. MakeUnique<opt::analysis::FloatConstant>(float_type, zero_bytes));
  120. auto constant_one = ir_context->get_constant_mgr()->RegisterConstant(
  121. MakeUnique<opt::analysis::FloatConstant>(float_type, one_bytes));
  122. auto constant_zero_id = ir_context->get_constant_mgr()
  123. ->GetDefiningInstruction(constant_zero)
  124. ->result_id();
  125. auto constant_one_id = ir_context->get_constant_mgr()
  126. ->GetDefiningInstruction(constant_one)
  127. ->result_id();
  128. return std::pair<uint32_t, uint32_t>(constant_zero_id, constant_one_id);
  129. }
  130. std::unique_ptr<TransformationReplaceConstantWithUniform>
  131. MakeConstantUniformReplacement(opt::IRContext* ir_context,
  132. const FactManager& fact_manager,
  133. uint32_t constant_id,
  134. uint32_t greater_than_instruction,
  135. uint32_t in_operand_index) {
  136. return MakeUnique<TransformationReplaceConstantWithUniform>(
  137. transformation::MakeIdUseDescriptor(constant_id, SpvOpFOrdGreaterThan,
  138. in_operand_index,
  139. greater_than_instruction, 0),
  140. fact_manager.GetUniformDescriptorsForConstant(ir_context, constant_id)[0],
  141. ir_context->TakeNextId(), ir_context->TakeNextId());
  142. }
  143. } // namespace
  144. bool ForceRenderRed(
  145. const spv_target_env& target_env, const std::vector<uint32_t>& binary_in,
  146. const spvtools::fuzz::protobufs::FactSequence& initial_facts,
  147. std::vector<uint32_t>* binary_out) {
  148. auto message_consumer = spvtools::utils::CLIMessageConsumer;
  149. spvtools::SpirvTools tools(target_env);
  150. if (!tools.IsValid()) {
  151. message_consumer(SPV_MSG_ERROR, nullptr, {},
  152. "Failed to create SPIRV-Tools interface; stopping.");
  153. return false;
  154. }
  155. // Initial binary should be valid.
  156. if (!tools.Validate(&binary_in[0], binary_in.size())) {
  157. message_consumer(SPV_MSG_ERROR, nullptr, {},
  158. "Initial binary is invalid; stopping.");
  159. return false;
  160. }
  161. // Build the module from the input binary.
  162. std::unique_ptr<opt::IRContext> ir_context = BuildModule(
  163. target_env, message_consumer, binary_in.data(), binary_in.size());
  164. assert(ir_context);
  165. // Set up a fact manager with any given initial facts.
  166. FactManager fact_manager;
  167. for (auto& fact : initial_facts.fact()) {
  168. fact_manager.AddFact(fact, ir_context.get());
  169. }
  170. auto entry_point_function =
  171. FindFragmentShaderEntryPoint(ir_context.get(), message_consumer);
  172. auto output_variable =
  173. FindVec4OutputVariable(ir_context.get(), message_consumer);
  174. if (entry_point_function == nullptr || output_variable == nullptr) {
  175. return false;
  176. }
  177. opt::analysis::Float temp_float_type(32);
  178. opt::analysis::Float* float_type = ir_context->get_type_mgr()
  179. ->GetRegisteredType(&temp_float_type)
  180. ->AsFloat();
  181. std::pair<uint32_t, uint32_t> zero_one_float_ids =
  182. FindOrCreateFloatZeroAndOne(ir_context.get(), float_type);
  183. // Make the new exit block
  184. auto new_exit_block_id = ir_context->TakeNextId();
  185. {
  186. auto label = MakeUnique<opt::Instruction>(ir_context.get(), SpvOpLabel, 0,
  187. new_exit_block_id,
  188. opt::Instruction::OperandList());
  189. auto new_exit_block = MakeUnique<opt::BasicBlock>(std::move(label));
  190. new_exit_block->AddInstruction(MakeUnique<opt::Instruction>(
  191. ir_context.get(), SpvOpReturn, 0, 0, opt::Instruction::OperandList()));
  192. entry_point_function->AddBasicBlock(std::move(new_exit_block));
  193. }
  194. // Make the new entry block
  195. {
  196. auto label = MakeUnique<opt::Instruction>(ir_context.get(), SpvOpLabel, 0,
  197. ir_context->TakeNextId(),
  198. opt::Instruction::OperandList());
  199. auto new_entry_block = MakeUnique<opt::BasicBlock>(std::move(label));
  200. // Make an instruction to construct vec4(1.0, 0.0, 0.0, 1.0), representing
  201. // the colour red.
  202. opt::Operand zero_float = {SPV_OPERAND_TYPE_ID, {zero_one_float_ids.first}};
  203. opt::Operand one_float = {SPV_OPERAND_TYPE_ID, {zero_one_float_ids.second}};
  204. opt::Instruction::OperandList op_composite_construct_operands = {
  205. one_float, zero_float, zero_float, one_float};
  206. auto temp_vec4 = opt::analysis::Vector(float_type, 4);
  207. auto vec4_id = ir_context->get_type_mgr()->GetId(&temp_vec4);
  208. auto red = MakeUnique<opt::Instruction>(
  209. ir_context.get(), SpvOpCompositeConstruct, vec4_id,
  210. ir_context->TakeNextId(), op_composite_construct_operands);
  211. auto red_id = red->result_id();
  212. new_entry_block->AddInstruction(std::move(red));
  213. // Make an instruction to store red into the output color.
  214. opt::Operand variable_to_store_into = {SPV_OPERAND_TYPE_ID,
  215. {output_variable->result_id()}};
  216. opt::Operand value_to_be_stored = {SPV_OPERAND_TYPE_ID, {red_id}};
  217. opt::Instruction::OperandList op_store_operands = {variable_to_store_into,
  218. value_to_be_stored};
  219. new_entry_block->AddInstruction(MakeUnique<opt::Instruction>(
  220. ir_context.get(), SpvOpStore, 0, 0, op_store_operands));
  221. // We are going to attempt to construct 'false' as an expression of the form
  222. // 'literal1 > literal2'. If we succeed, we will later replace each literal
  223. // with a uniform of the same value - we can only do that replacement once
  224. // we have added the entry block to the module.
  225. std::unique_ptr<TransformationReplaceConstantWithUniform>
  226. first_greater_then_operand_replacement = nullptr;
  227. std::unique_ptr<TransformationReplaceConstantWithUniform>
  228. second_greater_then_operand_replacement = nullptr;
  229. uint32_t id_guaranteed_to_be_false = 0;
  230. opt::analysis::Bool temp_bool_type;
  231. opt::analysis::Bool* registered_bool_type =
  232. ir_context->get_type_mgr()
  233. ->GetRegisteredType(&temp_bool_type)
  234. ->AsBool();
  235. auto float_type_id = ir_context->get_type_mgr()->GetId(float_type);
  236. auto types_for_which_uniforms_are_known =
  237. fact_manager.GetTypesForWhichUniformValuesAreKnown();
  238. // Check whether we have any float uniforms.
  239. if (std::find(types_for_which_uniforms_are_known.begin(),
  240. types_for_which_uniforms_are_known.end(),
  241. float_type_id) != types_for_which_uniforms_are_known.end()) {
  242. // We have at least one float uniform; let's see whether we have at least
  243. // two.
  244. auto available_constants =
  245. fact_manager.GetConstantsAvailableFromUniformsForType(
  246. ir_context.get(), float_type_id);
  247. if (available_constants.size() > 1) {
  248. // Grab the float constants associated with the first two known float
  249. // uniforms.
  250. auto first_constant =
  251. ir_context->get_constant_mgr()
  252. ->GetConstantFromInst(ir_context->get_def_use_mgr()->GetDef(
  253. available_constants[0]))
  254. ->AsFloatConstant();
  255. auto second_constant =
  256. ir_context->get_constant_mgr()
  257. ->GetConstantFromInst(ir_context->get_def_use_mgr()->GetDef(
  258. available_constants[1]))
  259. ->AsFloatConstant();
  260. // Now work out which of the two constants is larger than the other.
  261. uint32_t larger_constant_index = 0;
  262. uint32_t smaller_constant_index = 0;
  263. if (first_constant->GetFloat() > second_constant->GetFloat()) {
  264. larger_constant_index = 0;
  265. smaller_constant_index = 1;
  266. } else if (first_constant->GetFloat() < second_constant->GetFloat()) {
  267. larger_constant_index = 1;
  268. smaller_constant_index = 0;
  269. }
  270. // Only proceed with these constants if they have turned out to be
  271. // distinct.
  272. if (larger_constant_index != smaller_constant_index) {
  273. // We are in a position to create 'false' as 'literal1 > literal2', so
  274. // reserve an id for this computation; this id will end up being
  275. // guaranteed to be 'false'.
  276. id_guaranteed_to_be_false = ir_context->TakeNextId();
  277. auto smaller_constant = available_constants[smaller_constant_index];
  278. auto larger_constant = available_constants[larger_constant_index];
  279. opt::Instruction::OperandList greater_than_operands = {
  280. {SPV_OPERAND_TYPE_ID, {smaller_constant}},
  281. {SPV_OPERAND_TYPE_ID, {larger_constant}}};
  282. new_entry_block->AddInstruction(MakeUnique<opt::Instruction>(
  283. ir_context.get(), SpvOpFOrdGreaterThan,
  284. ir_context->get_type_mgr()->GetId(registered_bool_type),
  285. id_guaranteed_to_be_false, greater_than_operands));
  286. first_greater_then_operand_replacement =
  287. MakeConstantUniformReplacement(ir_context.get(), fact_manager,
  288. smaller_constant,
  289. id_guaranteed_to_be_false, 0);
  290. second_greater_then_operand_replacement =
  291. MakeConstantUniformReplacement(ir_context.get(), fact_manager,
  292. larger_constant,
  293. id_guaranteed_to_be_false, 1);
  294. }
  295. }
  296. }
  297. if (id_guaranteed_to_be_false == 0) {
  298. auto constant_false = ir_context->get_constant_mgr()->RegisterConstant(
  299. MakeUnique<opt::analysis::BoolConstant>(registered_bool_type, false));
  300. id_guaranteed_to_be_false = ir_context->get_constant_mgr()
  301. ->GetDefiningInstruction(constant_false)
  302. ->result_id();
  303. }
  304. opt::Operand false_condition = {SPV_OPERAND_TYPE_ID,
  305. {id_guaranteed_to_be_false}};
  306. opt::Operand then_block = {SPV_OPERAND_TYPE_ID,
  307. {entry_point_function->entry()->id()}};
  308. opt::Operand else_block = {SPV_OPERAND_TYPE_ID, {new_exit_block_id}};
  309. opt::Instruction::OperandList op_branch_conditional_operands = {
  310. false_condition, then_block, else_block};
  311. new_entry_block->AddInstruction(
  312. MakeUnique<opt::Instruction>(ir_context.get(), SpvOpBranchConditional,
  313. 0, 0, op_branch_conditional_operands));
  314. entry_point_function->InsertBasicBlockBefore(
  315. std::move(new_entry_block), entry_point_function->entry().get());
  316. for (auto& replacement : {first_greater_then_operand_replacement.get(),
  317. second_greater_then_operand_replacement.get()}) {
  318. if (replacement) {
  319. assert(replacement->IsApplicable(ir_context.get(), fact_manager));
  320. replacement->Apply(ir_context.get(), &fact_manager);
  321. }
  322. }
  323. }
  324. // Write out the module as a binary.
  325. ir_context->module()->ToBinary(binary_out, false);
  326. return true;
  327. }
  328. } // namespace fuzz
  329. } // namespace spvtools