instruction.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072
  1. // Copyright (c) 2016 Google Inc.
  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/opt/instruction.h"
  15. #include <initializer_list>
  16. #include "OpenCLDebugInfo100.h"
  17. #include "source/disassemble.h"
  18. #include "source/opt/fold.h"
  19. #include "source/opt/ir_context.h"
  20. #include "source/opt/reflect.h"
  21. namespace spvtools {
  22. namespace opt {
  23. namespace {
  24. // Indices used to get particular operands out of instructions using InOperand.
  25. const uint32_t kTypeImageDimIndex = 1;
  26. const uint32_t kLoadBaseIndex = 0;
  27. const uint32_t kPointerTypeStorageClassIndex = 0;
  28. const uint32_t kVariableStorageClassIndex = 0;
  29. const uint32_t kTypeImageSampledIndex = 5;
  30. // Constants for OpenCL.DebugInfo.100 / NonSemantic.Shader.DebugInfo.100
  31. // extension instructions.
  32. const uint32_t kExtInstSetIdInIdx = 0;
  33. const uint32_t kExtInstInstructionInIdx = 1;
  34. const uint32_t kDebugScopeNumWords = 7;
  35. const uint32_t kDebugScopeNumWordsWithoutInlinedAt = 6;
  36. const uint32_t kDebugNoScopeNumWords = 5;
  37. // Number of operands of an OpBranchConditional instruction
  38. // with weights.
  39. const uint32_t kOpBranchConditionalWithWeightsNumOperands = 5;
  40. } // namespace
  41. Instruction::Instruction(IRContext* c)
  42. : utils::IntrusiveNodeBase<Instruction>(),
  43. context_(c),
  44. opcode_(SpvOpNop),
  45. has_type_id_(false),
  46. has_result_id_(false),
  47. unique_id_(c->TakeNextUniqueId()),
  48. dbg_scope_(kNoDebugScope, kNoInlinedAt) {}
  49. Instruction::Instruction(IRContext* c, SpvOp op)
  50. : utils::IntrusiveNodeBase<Instruction>(),
  51. context_(c),
  52. opcode_(op),
  53. has_type_id_(false),
  54. has_result_id_(false),
  55. unique_id_(c->TakeNextUniqueId()),
  56. dbg_scope_(kNoDebugScope, kNoInlinedAt) {}
  57. Instruction::Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
  58. std::vector<Instruction>&& dbg_line)
  59. : utils::IntrusiveNodeBase<Instruction>(),
  60. context_(c),
  61. opcode_(static_cast<SpvOp>(inst.opcode)),
  62. has_type_id_(inst.type_id != 0),
  63. has_result_id_(inst.result_id != 0),
  64. unique_id_(c->TakeNextUniqueId()),
  65. dbg_line_insts_(std::move(dbg_line)),
  66. dbg_scope_(kNoDebugScope, kNoInlinedAt) {
  67. for (uint32_t i = 0; i < inst.num_operands; ++i) {
  68. const auto& current_payload = inst.operands[i];
  69. operands_.emplace_back(
  70. current_payload.type, inst.words + current_payload.offset,
  71. inst.words + current_payload.offset + current_payload.num_words);
  72. }
  73. assert((!IsLineInst() || dbg_line.empty()) &&
  74. "Op(No)Line attaching to Op(No)Line found");
  75. }
  76. Instruction::Instruction(IRContext* c, const spv_parsed_instruction_t& inst,
  77. const DebugScope& dbg_scope)
  78. : utils::IntrusiveNodeBase<Instruction>(),
  79. context_(c),
  80. opcode_(static_cast<SpvOp>(inst.opcode)),
  81. has_type_id_(inst.type_id != 0),
  82. has_result_id_(inst.result_id != 0),
  83. unique_id_(c->TakeNextUniqueId()),
  84. dbg_scope_(dbg_scope) {
  85. for (uint32_t i = 0; i < inst.num_operands; ++i) {
  86. const auto& current_payload = inst.operands[i];
  87. operands_.emplace_back(
  88. current_payload.type, inst.words + current_payload.offset,
  89. inst.words + current_payload.offset + current_payload.num_words);
  90. }
  91. }
  92. Instruction::Instruction(IRContext* c, SpvOp op, uint32_t ty_id,
  93. uint32_t res_id, const OperandList& in_operands)
  94. : utils::IntrusiveNodeBase<Instruction>(),
  95. context_(c),
  96. opcode_(op),
  97. has_type_id_(ty_id != 0),
  98. has_result_id_(res_id != 0),
  99. unique_id_(c->TakeNextUniqueId()),
  100. operands_(),
  101. dbg_scope_(kNoDebugScope, kNoInlinedAt) {
  102. if (has_type_id_) {
  103. operands_.emplace_back(spv_operand_type_t::SPV_OPERAND_TYPE_TYPE_ID,
  104. std::initializer_list<uint32_t>{ty_id});
  105. }
  106. if (has_result_id_) {
  107. operands_.emplace_back(spv_operand_type_t::SPV_OPERAND_TYPE_RESULT_ID,
  108. std::initializer_list<uint32_t>{res_id});
  109. }
  110. operands_.insert(operands_.end(), in_operands.begin(), in_operands.end());
  111. }
  112. Instruction::Instruction(Instruction&& that)
  113. : utils::IntrusiveNodeBase<Instruction>(),
  114. context_(that.context_),
  115. opcode_(that.opcode_),
  116. has_type_id_(that.has_type_id_),
  117. has_result_id_(that.has_result_id_),
  118. unique_id_(that.unique_id_),
  119. operands_(std::move(that.operands_)),
  120. dbg_line_insts_(std::move(that.dbg_line_insts_)),
  121. dbg_scope_(that.dbg_scope_) {
  122. for (auto& i : dbg_line_insts_) {
  123. i.dbg_scope_ = that.dbg_scope_;
  124. }
  125. }
  126. Instruction& Instruction::operator=(Instruction&& that) {
  127. context_ = that.context_;
  128. opcode_ = that.opcode_;
  129. has_type_id_ = that.has_type_id_;
  130. has_result_id_ = that.has_result_id_;
  131. unique_id_ = that.unique_id_;
  132. operands_ = std::move(that.operands_);
  133. dbg_line_insts_ = std::move(that.dbg_line_insts_);
  134. dbg_scope_ = that.dbg_scope_;
  135. return *this;
  136. }
  137. Instruction* Instruction::Clone(IRContext* c) const {
  138. Instruction* clone = new Instruction(c);
  139. clone->opcode_ = opcode_;
  140. clone->has_type_id_ = has_type_id_;
  141. clone->has_result_id_ = has_result_id_;
  142. clone->unique_id_ = c->TakeNextUniqueId();
  143. clone->operands_ = operands_;
  144. clone->dbg_line_insts_ = dbg_line_insts_;
  145. for (auto& i : clone->dbg_line_insts_) {
  146. i.unique_id_ = c->TakeNextUniqueId();
  147. if (i.IsDebugLineInst()) i.SetResultId(c->TakeNextId());
  148. }
  149. clone->dbg_scope_ = dbg_scope_;
  150. return clone;
  151. }
  152. uint32_t Instruction::GetSingleWordOperand(uint32_t index) const {
  153. const auto& words = GetOperand(index).words;
  154. assert(words.size() == 1 && "expected the operand only taking one word");
  155. return words.front();
  156. }
  157. uint32_t Instruction::NumInOperandWords() const {
  158. uint32_t size = 0;
  159. for (uint32_t i = TypeResultIdCount(); i < operands_.size(); ++i)
  160. size += static_cast<uint32_t>(operands_[i].words.size());
  161. return size;
  162. }
  163. bool Instruction::HasBranchWeights() const {
  164. if (opcode_ == SpvOpBranchConditional &&
  165. NumOperands() == kOpBranchConditionalWithWeightsNumOperands) {
  166. return true;
  167. }
  168. return false;
  169. }
  170. void Instruction::ToBinaryWithoutAttachedDebugInsts(
  171. std::vector<uint32_t>* binary) const {
  172. const uint32_t num_words = 1 + NumOperandWords();
  173. binary->push_back((num_words << 16) | static_cast<uint16_t>(opcode_));
  174. for (const auto& operand : operands_) {
  175. binary->insert(binary->end(), operand.words.begin(), operand.words.end());
  176. }
  177. }
  178. void Instruction::ReplaceOperands(const OperandList& new_operands) {
  179. operands_.clear();
  180. operands_.insert(operands_.begin(), new_operands.begin(), new_operands.end());
  181. }
  182. bool Instruction::IsReadOnlyLoad() const {
  183. if (IsLoad()) {
  184. Instruction* address_def = GetBaseAddress();
  185. if (!address_def) {
  186. return false;
  187. }
  188. if (address_def->opcode() == SpvOpVariable) {
  189. if (address_def->IsReadOnlyPointer()) {
  190. return true;
  191. }
  192. }
  193. if (address_def->opcode() == SpvOpLoad) {
  194. const analysis::Type* address_type =
  195. context()->get_type_mgr()->GetType(address_def->type_id());
  196. if (address_type->AsSampledImage() != nullptr) {
  197. const auto* image_type =
  198. address_type->AsSampledImage()->image_type()->AsImage();
  199. if (image_type->sampled() == 1) {
  200. return true;
  201. }
  202. }
  203. }
  204. }
  205. return false;
  206. }
  207. Instruction* Instruction::GetBaseAddress() const {
  208. uint32_t base = GetSingleWordInOperand(kLoadBaseIndex);
  209. Instruction* base_inst = context()->get_def_use_mgr()->GetDef(base);
  210. bool done = false;
  211. while (!done) {
  212. switch (base_inst->opcode()) {
  213. case SpvOpAccessChain:
  214. case SpvOpInBoundsAccessChain:
  215. case SpvOpPtrAccessChain:
  216. case SpvOpInBoundsPtrAccessChain:
  217. case SpvOpImageTexelPointer:
  218. case SpvOpCopyObject:
  219. // All of these instructions have the base pointer use a base pointer
  220. // in in-operand 0.
  221. base = base_inst->GetSingleWordInOperand(0);
  222. base_inst = context()->get_def_use_mgr()->GetDef(base);
  223. break;
  224. default:
  225. done = true;
  226. break;
  227. }
  228. }
  229. return base_inst;
  230. }
  231. bool Instruction::IsReadOnlyPointer() const {
  232. if (context()->get_feature_mgr()->HasCapability(SpvCapabilityShader))
  233. return IsReadOnlyPointerShaders();
  234. else
  235. return IsReadOnlyPointerKernel();
  236. }
  237. bool Instruction::IsVulkanStorageImage() const {
  238. if (opcode() != SpvOpTypePointer) {
  239. return false;
  240. }
  241. uint32_t storage_class =
  242. GetSingleWordInOperand(kPointerTypeStorageClassIndex);
  243. if (storage_class != SpvStorageClassUniformConstant) {
  244. return false;
  245. }
  246. Instruction* base_type =
  247. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  248. // Unpack the optional layer of arraying.
  249. if (base_type->opcode() == SpvOpTypeArray ||
  250. base_type->opcode() == SpvOpTypeRuntimeArray) {
  251. base_type = context()->get_def_use_mgr()->GetDef(
  252. base_type->GetSingleWordInOperand(0));
  253. }
  254. if (base_type->opcode() != SpvOpTypeImage) {
  255. return false;
  256. }
  257. if (base_type->GetSingleWordInOperand(kTypeImageDimIndex) == SpvDimBuffer) {
  258. return false;
  259. }
  260. // Check if the image is sampled. If we do not know for sure that it is,
  261. // then assume it is a storage image.
  262. return base_type->GetSingleWordInOperand(kTypeImageSampledIndex) != 1;
  263. }
  264. bool Instruction::IsVulkanSampledImage() const {
  265. if (opcode() != SpvOpTypePointer) {
  266. return false;
  267. }
  268. uint32_t storage_class =
  269. GetSingleWordInOperand(kPointerTypeStorageClassIndex);
  270. if (storage_class != SpvStorageClassUniformConstant) {
  271. return false;
  272. }
  273. Instruction* base_type =
  274. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  275. // Unpack the optional layer of arraying.
  276. if (base_type->opcode() == SpvOpTypeArray ||
  277. base_type->opcode() == SpvOpTypeRuntimeArray) {
  278. base_type = context()->get_def_use_mgr()->GetDef(
  279. base_type->GetSingleWordInOperand(0));
  280. }
  281. if (base_type->opcode() != SpvOpTypeImage) {
  282. return false;
  283. }
  284. if (base_type->GetSingleWordInOperand(kTypeImageDimIndex) == SpvDimBuffer) {
  285. return false;
  286. }
  287. // Check if the image is sampled. If we know for sure that it is,
  288. // then return true.
  289. return base_type->GetSingleWordInOperand(kTypeImageSampledIndex) == 1;
  290. }
  291. bool Instruction::IsVulkanStorageTexelBuffer() const {
  292. if (opcode() != SpvOpTypePointer) {
  293. return false;
  294. }
  295. uint32_t storage_class =
  296. GetSingleWordInOperand(kPointerTypeStorageClassIndex);
  297. if (storage_class != SpvStorageClassUniformConstant) {
  298. return false;
  299. }
  300. Instruction* base_type =
  301. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  302. // Unpack the optional layer of arraying.
  303. if (base_type->opcode() == SpvOpTypeArray ||
  304. base_type->opcode() == SpvOpTypeRuntimeArray) {
  305. base_type = context()->get_def_use_mgr()->GetDef(
  306. base_type->GetSingleWordInOperand(0));
  307. }
  308. if (base_type->opcode() != SpvOpTypeImage) {
  309. return false;
  310. }
  311. if (base_type->GetSingleWordInOperand(kTypeImageDimIndex) != SpvDimBuffer) {
  312. return false;
  313. }
  314. // Check if the image is sampled. If we do not know for sure that it is,
  315. // then assume it is a storage texel buffer.
  316. return base_type->GetSingleWordInOperand(kTypeImageSampledIndex) != 1;
  317. }
  318. bool Instruction::IsVulkanStorageBuffer() const {
  319. // Is there a difference between a "Storage buffer" and a "dynamic storage
  320. // buffer" in SPIR-V and do we care about the difference?
  321. if (opcode() != SpvOpTypePointer) {
  322. return false;
  323. }
  324. Instruction* base_type =
  325. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  326. // Unpack the optional layer of arraying.
  327. if (base_type->opcode() == SpvOpTypeArray ||
  328. base_type->opcode() == SpvOpTypeRuntimeArray) {
  329. base_type = context()->get_def_use_mgr()->GetDef(
  330. base_type->GetSingleWordInOperand(0));
  331. }
  332. if (base_type->opcode() != SpvOpTypeStruct) {
  333. return false;
  334. }
  335. uint32_t storage_class =
  336. GetSingleWordInOperand(kPointerTypeStorageClassIndex);
  337. if (storage_class == SpvStorageClassUniform) {
  338. bool is_buffer_block = false;
  339. context()->get_decoration_mgr()->ForEachDecoration(
  340. base_type->result_id(), SpvDecorationBufferBlock,
  341. [&is_buffer_block](const Instruction&) { is_buffer_block = true; });
  342. return is_buffer_block;
  343. } else if (storage_class == SpvStorageClassStorageBuffer) {
  344. bool is_block = false;
  345. context()->get_decoration_mgr()->ForEachDecoration(
  346. base_type->result_id(), SpvDecorationBlock,
  347. [&is_block](const Instruction&) { is_block = true; });
  348. return is_block;
  349. }
  350. return false;
  351. }
  352. bool Instruction::IsVulkanStorageBufferVariable() const {
  353. if (opcode() != SpvOpVariable) {
  354. return false;
  355. }
  356. uint32_t storage_class = GetSingleWordInOperand(kVariableStorageClassIndex);
  357. if (storage_class == SpvStorageClassStorageBuffer ||
  358. storage_class == SpvStorageClassUniform) {
  359. Instruction* var_type = context()->get_def_use_mgr()->GetDef(type_id());
  360. return var_type != nullptr && var_type->IsVulkanStorageBuffer();
  361. }
  362. return false;
  363. }
  364. bool Instruction::IsVulkanUniformBuffer() const {
  365. if (opcode() != SpvOpTypePointer) {
  366. return false;
  367. }
  368. uint32_t storage_class =
  369. GetSingleWordInOperand(kPointerTypeStorageClassIndex);
  370. if (storage_class != SpvStorageClassUniform) {
  371. return false;
  372. }
  373. Instruction* base_type =
  374. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(1));
  375. // Unpack the optional layer of arraying.
  376. if (base_type->opcode() == SpvOpTypeArray ||
  377. base_type->opcode() == SpvOpTypeRuntimeArray) {
  378. base_type = context()->get_def_use_mgr()->GetDef(
  379. base_type->GetSingleWordInOperand(0));
  380. }
  381. if (base_type->opcode() != SpvOpTypeStruct) {
  382. return false;
  383. }
  384. bool is_block = false;
  385. context()->get_decoration_mgr()->ForEachDecoration(
  386. base_type->result_id(), SpvDecorationBlock,
  387. [&is_block](const Instruction&) { is_block = true; });
  388. return is_block;
  389. }
  390. bool Instruction::IsReadOnlyPointerShaders() const {
  391. if (type_id() == 0) {
  392. return false;
  393. }
  394. Instruction* type_def = context()->get_def_use_mgr()->GetDef(type_id());
  395. if (type_def->opcode() != SpvOpTypePointer) {
  396. return false;
  397. }
  398. uint32_t storage_class =
  399. type_def->GetSingleWordInOperand(kPointerTypeStorageClassIndex);
  400. switch (storage_class) {
  401. case SpvStorageClassUniformConstant:
  402. if (!type_def->IsVulkanStorageImage() &&
  403. !type_def->IsVulkanStorageTexelBuffer()) {
  404. return true;
  405. }
  406. break;
  407. case SpvStorageClassUniform:
  408. if (!type_def->IsVulkanStorageBuffer()) {
  409. return true;
  410. }
  411. break;
  412. case SpvStorageClassPushConstant:
  413. case SpvStorageClassInput:
  414. return true;
  415. default:
  416. break;
  417. }
  418. bool is_nonwritable = false;
  419. context()->get_decoration_mgr()->ForEachDecoration(
  420. result_id(), SpvDecorationNonWritable,
  421. [&is_nonwritable](const Instruction&) { is_nonwritable = true; });
  422. return is_nonwritable;
  423. }
  424. bool Instruction::IsReadOnlyPointerKernel() const {
  425. if (type_id() == 0) {
  426. return false;
  427. }
  428. Instruction* type_def = context()->get_def_use_mgr()->GetDef(type_id());
  429. if (type_def->opcode() != SpvOpTypePointer) {
  430. return false;
  431. }
  432. uint32_t storage_class =
  433. type_def->GetSingleWordInOperand(kPointerTypeStorageClassIndex);
  434. return storage_class == SpvStorageClassUniformConstant;
  435. }
  436. uint32_t Instruction::GetTypeComponent(uint32_t element) const {
  437. uint32_t subtype = 0;
  438. switch (opcode()) {
  439. case SpvOpTypeStruct:
  440. subtype = GetSingleWordInOperand(element);
  441. break;
  442. case SpvOpTypeArray:
  443. case SpvOpTypeRuntimeArray:
  444. case SpvOpTypeVector:
  445. case SpvOpTypeMatrix:
  446. // These types all have uniform subtypes.
  447. subtype = GetSingleWordInOperand(0u);
  448. break;
  449. default:
  450. break;
  451. }
  452. return subtype;
  453. }
  454. void Instruction::UpdateLexicalScope(uint32_t scope) {
  455. dbg_scope_.SetLexicalScope(scope);
  456. for (auto& i : dbg_line_insts_) {
  457. i.dbg_scope_.SetLexicalScope(scope);
  458. }
  459. if (!IsLineInst() &&
  460. context()->AreAnalysesValid(IRContext::kAnalysisDebugInfo)) {
  461. context()->get_debug_info_mgr()->AnalyzeDebugInst(this);
  462. }
  463. }
  464. void Instruction::UpdateDebugInlinedAt(uint32_t new_inlined_at) {
  465. dbg_scope_.SetInlinedAt(new_inlined_at);
  466. for (auto& i : dbg_line_insts_) {
  467. i.dbg_scope_.SetInlinedAt(new_inlined_at);
  468. }
  469. if (!IsLineInst() &&
  470. context()->AreAnalysesValid(IRContext::kAnalysisDebugInfo)) {
  471. context()->get_debug_info_mgr()->AnalyzeDebugInst(this);
  472. }
  473. }
  474. void Instruction::ClearDbgLineInsts() {
  475. if (context()->AreAnalysesValid(IRContext::kAnalysisDefUse)) {
  476. auto def_use_mgr = context()->get_def_use_mgr();
  477. for (auto& l_inst : dbg_line_insts_) def_use_mgr->ClearInst(&l_inst);
  478. }
  479. clear_dbg_line_insts();
  480. }
  481. void Instruction::UpdateDebugInfoFrom(const Instruction* from) {
  482. if (from == nullptr) return;
  483. ClearDbgLineInsts();
  484. if (!from->dbg_line_insts().empty())
  485. AddDebugLine(&from->dbg_line_insts().back());
  486. SetDebugScope(from->GetDebugScope());
  487. if (!IsLineInst() &&
  488. context()->AreAnalysesValid(IRContext::kAnalysisDebugInfo)) {
  489. context()->get_debug_info_mgr()->AnalyzeDebugInst(this);
  490. }
  491. }
  492. void Instruction::AddDebugLine(const Instruction* inst) {
  493. dbg_line_insts_.push_back(*inst);
  494. dbg_line_insts_.back().unique_id_ = context()->TakeNextUniqueId();
  495. if (inst->IsDebugLineInst())
  496. dbg_line_insts_.back().SetResultId(context_->TakeNextId());
  497. if (context()->AreAnalysesValid(IRContext::kAnalysisDefUse))
  498. context()->get_def_use_mgr()->AnalyzeInstDefUse(&dbg_line_insts_.back());
  499. }
  500. bool Instruction::IsDebugLineInst() const {
  501. NonSemanticShaderDebugInfo100Instructions ext_opt = GetShader100DebugOpcode();
  502. return ((ext_opt == NonSemanticShaderDebugInfo100DebugLine) ||
  503. (ext_opt == NonSemanticShaderDebugInfo100DebugNoLine));
  504. }
  505. bool Instruction::IsLineInst() const { return IsLine() || IsNoLine(); }
  506. bool Instruction::IsLine() const {
  507. if (opcode() == SpvOpLine) return true;
  508. NonSemanticShaderDebugInfo100Instructions ext_opt = GetShader100DebugOpcode();
  509. return ext_opt == NonSemanticShaderDebugInfo100DebugLine;
  510. }
  511. bool Instruction::IsNoLine() const {
  512. if (opcode() == SpvOpNoLine) return true;
  513. NonSemanticShaderDebugInfo100Instructions ext_opt = GetShader100DebugOpcode();
  514. return ext_opt == NonSemanticShaderDebugInfo100DebugNoLine;
  515. }
  516. Instruction* Instruction::InsertBefore(std::unique_ptr<Instruction>&& inst) {
  517. inst.get()->InsertBefore(this);
  518. return inst.release();
  519. }
  520. Instruction* Instruction::InsertBefore(
  521. std::vector<std::unique_ptr<Instruction>>&& list) {
  522. Instruction* first_node = list.front().get();
  523. for (auto& inst : list) {
  524. inst.release()->InsertBefore(this);
  525. }
  526. list.clear();
  527. return first_node;
  528. }
  529. bool Instruction::IsValidBasePointer() const {
  530. uint32_t tid = type_id();
  531. if (tid == 0) {
  532. return false;
  533. }
  534. Instruction* type = context()->get_def_use_mgr()->GetDef(tid);
  535. if (type->opcode() != SpvOpTypePointer) {
  536. return false;
  537. }
  538. auto feature_mgr = context()->get_feature_mgr();
  539. if (feature_mgr->HasCapability(SpvCapabilityAddresses)) {
  540. // TODO: The rules here could be more restrictive.
  541. return true;
  542. }
  543. if (opcode() == SpvOpVariable || opcode() == SpvOpFunctionParameter) {
  544. return true;
  545. }
  546. // With variable pointers, there are more valid base pointer objects.
  547. // Variable pointers implicitly declares Variable pointers storage buffer.
  548. SpvStorageClass storage_class =
  549. static_cast<SpvStorageClass>(type->GetSingleWordInOperand(0));
  550. if ((feature_mgr->HasCapability(SpvCapabilityVariablePointersStorageBuffer) &&
  551. storage_class == SpvStorageClassStorageBuffer) ||
  552. (feature_mgr->HasCapability(SpvCapabilityVariablePointers) &&
  553. storage_class == SpvStorageClassWorkgroup)) {
  554. switch (opcode()) {
  555. case SpvOpPhi:
  556. case SpvOpSelect:
  557. case SpvOpFunctionCall:
  558. case SpvOpConstantNull:
  559. return true;
  560. default:
  561. break;
  562. }
  563. }
  564. uint32_t pointee_type_id = type->GetSingleWordInOperand(1);
  565. Instruction* pointee_type_inst =
  566. context()->get_def_use_mgr()->GetDef(pointee_type_id);
  567. if (pointee_type_inst->IsOpaqueType()) {
  568. return true;
  569. }
  570. return false;
  571. }
  572. OpenCLDebugInfo100Instructions Instruction::GetOpenCL100DebugOpcode() const {
  573. if (opcode() != SpvOpExtInst) {
  574. return OpenCLDebugInfo100InstructionsMax;
  575. }
  576. if (!context()->get_feature_mgr()->GetExtInstImportId_OpenCL100DebugInfo()) {
  577. return OpenCLDebugInfo100InstructionsMax;
  578. }
  579. if (GetSingleWordInOperand(kExtInstSetIdInIdx) !=
  580. context()->get_feature_mgr()->GetExtInstImportId_OpenCL100DebugInfo()) {
  581. return OpenCLDebugInfo100InstructionsMax;
  582. }
  583. return OpenCLDebugInfo100Instructions(
  584. GetSingleWordInOperand(kExtInstInstructionInIdx));
  585. }
  586. NonSemanticShaderDebugInfo100Instructions Instruction::GetShader100DebugOpcode()
  587. const {
  588. if (opcode() != SpvOpExtInst) {
  589. return NonSemanticShaderDebugInfo100InstructionsMax;
  590. }
  591. if (!context()->get_feature_mgr()->GetExtInstImportId_Shader100DebugInfo()) {
  592. return NonSemanticShaderDebugInfo100InstructionsMax;
  593. }
  594. if (GetSingleWordInOperand(kExtInstSetIdInIdx) !=
  595. context()->get_feature_mgr()->GetExtInstImportId_Shader100DebugInfo()) {
  596. return NonSemanticShaderDebugInfo100InstructionsMax;
  597. }
  598. uint32_t opcode = GetSingleWordInOperand(kExtInstInstructionInIdx);
  599. if (opcode >= NonSemanticShaderDebugInfo100InstructionsMax) {
  600. return NonSemanticShaderDebugInfo100InstructionsMax;
  601. }
  602. return NonSemanticShaderDebugInfo100Instructions(opcode);
  603. }
  604. CommonDebugInfoInstructions Instruction::GetCommonDebugOpcode() const {
  605. if (opcode() != SpvOpExtInst) {
  606. return CommonDebugInfoInstructionsMax;
  607. }
  608. const uint32_t opencl_set_id =
  609. context()->get_feature_mgr()->GetExtInstImportId_OpenCL100DebugInfo();
  610. const uint32_t shader_set_id =
  611. context()->get_feature_mgr()->GetExtInstImportId_Shader100DebugInfo();
  612. if (!opencl_set_id && !shader_set_id) {
  613. return CommonDebugInfoInstructionsMax;
  614. }
  615. const uint32_t used_set_id = GetSingleWordInOperand(kExtInstSetIdInIdx);
  616. if (used_set_id != opencl_set_id && used_set_id != shader_set_id) {
  617. return CommonDebugInfoInstructionsMax;
  618. }
  619. return CommonDebugInfoInstructions(
  620. GetSingleWordInOperand(kExtInstInstructionInIdx));
  621. }
  622. bool Instruction::IsValidBaseImage() const {
  623. uint32_t tid = type_id();
  624. if (tid == 0) {
  625. return false;
  626. }
  627. Instruction* type = context()->get_def_use_mgr()->GetDef(tid);
  628. return (type->opcode() == SpvOpTypeImage ||
  629. type->opcode() == SpvOpTypeSampledImage);
  630. }
  631. bool Instruction::IsOpaqueType() const {
  632. if (opcode() == SpvOpTypeStruct) {
  633. bool is_opaque = false;
  634. ForEachInOperand([&is_opaque, this](const uint32_t* op_id) {
  635. Instruction* type_inst = context()->get_def_use_mgr()->GetDef(*op_id);
  636. is_opaque |= type_inst->IsOpaqueType();
  637. });
  638. return is_opaque;
  639. } else if (opcode() == SpvOpTypeArray) {
  640. uint32_t sub_type_id = GetSingleWordInOperand(0);
  641. Instruction* sub_type_inst =
  642. context()->get_def_use_mgr()->GetDef(sub_type_id);
  643. return sub_type_inst->IsOpaqueType();
  644. } else {
  645. return opcode() == SpvOpTypeRuntimeArray ||
  646. spvOpcodeIsBaseOpaqueType(opcode());
  647. }
  648. }
  649. bool Instruction::IsFoldable() const {
  650. return IsFoldableByFoldScalar() ||
  651. context()->get_instruction_folder().HasConstFoldingRule(this);
  652. }
  653. bool Instruction::IsFoldableByFoldScalar() const {
  654. const InstructionFolder& folder = context()->get_instruction_folder();
  655. if (!folder.IsFoldableOpcode(opcode())) {
  656. return false;
  657. }
  658. Instruction* type = context()->get_def_use_mgr()->GetDef(type_id());
  659. if (!folder.IsFoldableType(type)) {
  660. return false;
  661. }
  662. // Even if the type of the instruction is foldable, its operands may not be
  663. // foldable (e.g., comparisons of 64bit types). Check that all operand types
  664. // are foldable before accepting the instruction.
  665. return WhileEachInOperand([&folder, this](const uint32_t* op_id) {
  666. Instruction* def_inst = context()->get_def_use_mgr()->GetDef(*op_id);
  667. Instruction* def_inst_type =
  668. context()->get_def_use_mgr()->GetDef(def_inst->type_id());
  669. return folder.IsFoldableType(def_inst_type);
  670. });
  671. }
  672. bool Instruction::IsFloatingPointFoldingAllowed() const {
  673. // TODO: Add the rules for kernels. For now it will be pessimistic.
  674. // For now, do not support capabilities introduced by SPV_KHR_float_controls.
  675. if (!context_->get_feature_mgr()->HasCapability(SpvCapabilityShader) ||
  676. context_->get_feature_mgr()->HasCapability(SpvCapabilityDenormPreserve) ||
  677. context_->get_feature_mgr()->HasCapability(
  678. SpvCapabilityDenormFlushToZero) ||
  679. context_->get_feature_mgr()->HasCapability(
  680. SpvCapabilitySignedZeroInfNanPreserve) ||
  681. context_->get_feature_mgr()->HasCapability(
  682. SpvCapabilityRoundingModeRTZ) ||
  683. context_->get_feature_mgr()->HasCapability(
  684. SpvCapabilityRoundingModeRTE)) {
  685. return false;
  686. }
  687. bool is_nocontract = false;
  688. context_->get_decoration_mgr()->WhileEachDecoration(
  689. result_id(), SpvDecorationNoContraction,
  690. [&is_nocontract](const Instruction&) {
  691. is_nocontract = true;
  692. return false;
  693. });
  694. return !is_nocontract;
  695. }
  696. std::string Instruction::PrettyPrint(uint32_t options) const {
  697. // Convert the module to binary.
  698. std::vector<uint32_t> module_binary;
  699. context()->module()->ToBinary(&module_binary, /* skip_nop = */ false);
  700. // Convert the instruction to binary. This is used to identify the correct
  701. // stream of words to output from the module.
  702. std::vector<uint32_t> inst_binary;
  703. ToBinaryWithoutAttachedDebugInsts(&inst_binary);
  704. // Do not generate a header.
  705. return spvInstructionBinaryToText(
  706. context()->grammar().target_env(), inst_binary.data(), inst_binary.size(),
  707. module_binary.data(), module_binary.size(),
  708. options | SPV_BINARY_TO_TEXT_OPTION_NO_HEADER);
  709. }
  710. std::ostream& operator<<(std::ostream& str, const Instruction& inst) {
  711. str << inst.PrettyPrint();
  712. return str;
  713. }
  714. void Instruction::Dump() const {
  715. std::cerr << "Instruction #" << unique_id() << "\n" << *this << "\n";
  716. }
  717. bool Instruction::IsOpcodeCodeMotionSafe() const {
  718. switch (opcode_) {
  719. case SpvOpNop:
  720. case SpvOpUndef:
  721. case SpvOpLoad:
  722. case SpvOpAccessChain:
  723. case SpvOpInBoundsAccessChain:
  724. case SpvOpArrayLength:
  725. case SpvOpVectorExtractDynamic:
  726. case SpvOpVectorInsertDynamic:
  727. case SpvOpVectorShuffle:
  728. case SpvOpCompositeConstruct:
  729. case SpvOpCompositeExtract:
  730. case SpvOpCompositeInsert:
  731. case SpvOpCopyObject:
  732. case SpvOpTranspose:
  733. case SpvOpConvertFToU:
  734. case SpvOpConvertFToS:
  735. case SpvOpConvertSToF:
  736. case SpvOpConvertUToF:
  737. case SpvOpUConvert:
  738. case SpvOpSConvert:
  739. case SpvOpFConvert:
  740. case SpvOpQuantizeToF16:
  741. case SpvOpBitcast:
  742. case SpvOpSNegate:
  743. case SpvOpFNegate:
  744. case SpvOpIAdd:
  745. case SpvOpFAdd:
  746. case SpvOpISub:
  747. case SpvOpFSub:
  748. case SpvOpIMul:
  749. case SpvOpFMul:
  750. case SpvOpUDiv:
  751. case SpvOpSDiv:
  752. case SpvOpFDiv:
  753. case SpvOpUMod:
  754. case SpvOpSRem:
  755. case SpvOpSMod:
  756. case SpvOpFRem:
  757. case SpvOpFMod:
  758. case SpvOpVectorTimesScalar:
  759. case SpvOpMatrixTimesScalar:
  760. case SpvOpVectorTimesMatrix:
  761. case SpvOpMatrixTimesVector:
  762. case SpvOpMatrixTimesMatrix:
  763. case SpvOpOuterProduct:
  764. case SpvOpDot:
  765. case SpvOpIAddCarry:
  766. case SpvOpISubBorrow:
  767. case SpvOpUMulExtended:
  768. case SpvOpSMulExtended:
  769. case SpvOpAny:
  770. case SpvOpAll:
  771. case SpvOpIsNan:
  772. case SpvOpIsInf:
  773. case SpvOpLogicalEqual:
  774. case SpvOpLogicalNotEqual:
  775. case SpvOpLogicalOr:
  776. case SpvOpLogicalAnd:
  777. case SpvOpLogicalNot:
  778. case SpvOpSelect:
  779. case SpvOpIEqual:
  780. case SpvOpINotEqual:
  781. case SpvOpUGreaterThan:
  782. case SpvOpSGreaterThan:
  783. case SpvOpUGreaterThanEqual:
  784. case SpvOpSGreaterThanEqual:
  785. case SpvOpULessThan:
  786. case SpvOpSLessThan:
  787. case SpvOpULessThanEqual:
  788. case SpvOpSLessThanEqual:
  789. case SpvOpFOrdEqual:
  790. case SpvOpFUnordEqual:
  791. case SpvOpFOrdNotEqual:
  792. case SpvOpFUnordNotEqual:
  793. case SpvOpFOrdLessThan:
  794. case SpvOpFUnordLessThan:
  795. case SpvOpFOrdGreaterThan:
  796. case SpvOpFUnordGreaterThan:
  797. case SpvOpFOrdLessThanEqual:
  798. case SpvOpFUnordLessThanEqual:
  799. case SpvOpFOrdGreaterThanEqual:
  800. case SpvOpFUnordGreaterThanEqual:
  801. case SpvOpShiftRightLogical:
  802. case SpvOpShiftRightArithmetic:
  803. case SpvOpShiftLeftLogical:
  804. case SpvOpBitwiseOr:
  805. case SpvOpBitwiseXor:
  806. case SpvOpBitwiseAnd:
  807. case SpvOpNot:
  808. case SpvOpBitFieldInsert:
  809. case SpvOpBitFieldSExtract:
  810. case SpvOpBitFieldUExtract:
  811. case SpvOpBitReverse:
  812. case SpvOpBitCount:
  813. case SpvOpSizeOf:
  814. return true;
  815. default:
  816. return false;
  817. }
  818. }
  819. bool Instruction::IsScalarizable() const {
  820. if (spvOpcodeIsScalarizable(opcode())) {
  821. return true;
  822. }
  823. if (opcode() == SpvOpExtInst) {
  824. uint32_t instSetId =
  825. context()->get_feature_mgr()->GetExtInstImportId_GLSLstd450();
  826. if (GetSingleWordInOperand(kExtInstSetIdInIdx) == instSetId) {
  827. switch (GetSingleWordInOperand(kExtInstInstructionInIdx)) {
  828. case GLSLstd450Round:
  829. case GLSLstd450RoundEven:
  830. case GLSLstd450Trunc:
  831. case GLSLstd450FAbs:
  832. case GLSLstd450SAbs:
  833. case GLSLstd450FSign:
  834. case GLSLstd450SSign:
  835. case GLSLstd450Floor:
  836. case GLSLstd450Ceil:
  837. case GLSLstd450Fract:
  838. case GLSLstd450Radians:
  839. case GLSLstd450Degrees:
  840. case GLSLstd450Sin:
  841. case GLSLstd450Cos:
  842. case GLSLstd450Tan:
  843. case GLSLstd450Asin:
  844. case GLSLstd450Acos:
  845. case GLSLstd450Atan:
  846. case GLSLstd450Sinh:
  847. case GLSLstd450Cosh:
  848. case GLSLstd450Tanh:
  849. case GLSLstd450Asinh:
  850. case GLSLstd450Acosh:
  851. case GLSLstd450Atanh:
  852. case GLSLstd450Atan2:
  853. case GLSLstd450Pow:
  854. case GLSLstd450Exp:
  855. case GLSLstd450Log:
  856. case GLSLstd450Exp2:
  857. case GLSLstd450Log2:
  858. case GLSLstd450Sqrt:
  859. case GLSLstd450InverseSqrt:
  860. case GLSLstd450Modf:
  861. case GLSLstd450FMin:
  862. case GLSLstd450UMin:
  863. case GLSLstd450SMin:
  864. case GLSLstd450FMax:
  865. case GLSLstd450UMax:
  866. case GLSLstd450SMax:
  867. case GLSLstd450FClamp:
  868. case GLSLstd450UClamp:
  869. case GLSLstd450SClamp:
  870. case GLSLstd450FMix:
  871. case GLSLstd450Step:
  872. case GLSLstd450SmoothStep:
  873. case GLSLstd450Fma:
  874. case GLSLstd450Frexp:
  875. case GLSLstd450Ldexp:
  876. case GLSLstd450FindILsb:
  877. case GLSLstd450FindSMsb:
  878. case GLSLstd450FindUMsb:
  879. case GLSLstd450NMin:
  880. case GLSLstd450NMax:
  881. case GLSLstd450NClamp:
  882. return true;
  883. default:
  884. return false;
  885. }
  886. }
  887. }
  888. return false;
  889. }
  890. bool Instruction::IsOpcodeSafeToDelete() const {
  891. if (context()->IsCombinatorInstruction(this)) {
  892. return true;
  893. }
  894. switch (opcode()) {
  895. case SpvOpDPdx:
  896. case SpvOpDPdy:
  897. case SpvOpFwidth:
  898. case SpvOpDPdxFine:
  899. case SpvOpDPdyFine:
  900. case SpvOpFwidthFine:
  901. case SpvOpDPdxCoarse:
  902. case SpvOpDPdyCoarse:
  903. case SpvOpFwidthCoarse:
  904. case SpvOpImageQueryLod:
  905. return true;
  906. default:
  907. return false;
  908. }
  909. }
  910. bool Instruction::IsNonSemanticInstruction() const {
  911. if (!HasResultId()) return false;
  912. if (opcode() != SpvOpExtInst) return false;
  913. auto import_inst =
  914. context()->get_def_use_mgr()->GetDef(GetSingleWordInOperand(0));
  915. std::string import_name = import_inst->GetInOperand(0).AsString();
  916. return import_name.find("NonSemantic.") == 0;
  917. }
  918. void DebugScope::ToBinary(uint32_t type_id, uint32_t result_id,
  919. uint32_t ext_set,
  920. std::vector<uint32_t>* binary) const {
  921. uint32_t num_words = kDebugScopeNumWords;
  922. CommonDebugInfoInstructions dbg_opcode = CommonDebugInfoDebugScope;
  923. if (GetLexicalScope() == kNoDebugScope) {
  924. num_words = kDebugNoScopeNumWords;
  925. dbg_opcode = CommonDebugInfoDebugNoScope;
  926. } else if (GetInlinedAt() == kNoInlinedAt) {
  927. num_words = kDebugScopeNumWordsWithoutInlinedAt;
  928. }
  929. std::vector<uint32_t> operands = {
  930. (num_words << 16) | static_cast<uint16_t>(SpvOpExtInst),
  931. type_id,
  932. result_id,
  933. ext_set,
  934. static_cast<uint32_t>(dbg_opcode),
  935. };
  936. binary->insert(binary->end(), operands.begin(), operands.end());
  937. if (GetLexicalScope() != kNoDebugScope) {
  938. binary->push_back(GetLexicalScope());
  939. if (GetInlinedAt() != kNoInlinedAt) binary->push_back(GetInlinedAt());
  940. }
  941. }
  942. } // namespace opt
  943. } // namespace spvtools