force_render_red.cpp 16 KB

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