ir_context.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942
  1. // Copyright (c) 2017 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/ir_context.h"
  15. #include <cstring>
  16. #include "source/latest_version_glsl_std_450_header.h"
  17. #include "source/opt/log.h"
  18. #include "source/opt/mem_pass.h"
  19. #include "source/opt/reflect.h"
  20. namespace {
  21. static const int kSpvDecorateTargetIdInIdx = 0;
  22. static const int kSpvDecorateDecorationInIdx = 1;
  23. static const int kSpvDecorateBuiltinInIdx = 2;
  24. static const int kEntryPointInterfaceInIdx = 3;
  25. static const int kEntryPointFunctionIdInIdx = 1;
  26. } // anonymous namespace
  27. namespace spvtools {
  28. namespace opt {
  29. void IRContext::BuildInvalidAnalyses(IRContext::Analysis set) {
  30. if (set & kAnalysisDefUse) {
  31. BuildDefUseManager();
  32. }
  33. if (set & kAnalysisInstrToBlockMapping) {
  34. BuildInstrToBlockMapping();
  35. }
  36. if (set & kAnalysisDecorations) {
  37. BuildDecorationManager();
  38. }
  39. if (set & kAnalysisCFG) {
  40. BuildCFG();
  41. }
  42. if (set & kAnalysisDominatorAnalysis) {
  43. ResetDominatorAnalysis();
  44. }
  45. if (set & kAnalysisLoopAnalysis) {
  46. ResetLoopAnalysis();
  47. }
  48. if (set & kAnalysisBuiltinVarId) {
  49. ResetBuiltinAnalysis();
  50. }
  51. if (set & kAnalysisNameMap) {
  52. BuildIdToNameMap();
  53. }
  54. if (set & kAnalysisScalarEvolution) {
  55. BuildScalarEvolutionAnalysis();
  56. }
  57. if (set & kAnalysisRegisterPressure) {
  58. BuildRegPressureAnalysis();
  59. }
  60. if (set & kAnalysisValueNumberTable) {
  61. BuildValueNumberTable();
  62. }
  63. if (set & kAnalysisStructuredCFG) {
  64. BuildStructuredCFGAnalysis();
  65. }
  66. if (set & kAnalysisIdToFuncMapping) {
  67. BuildIdToFuncMapping();
  68. }
  69. if (set & kAnalysisConstants) {
  70. BuildConstantManager();
  71. }
  72. if (set & kAnalysisTypes) {
  73. BuildTypeManager();
  74. }
  75. }
  76. void IRContext::InvalidateAnalysesExceptFor(
  77. IRContext::Analysis preserved_analyses) {
  78. uint32_t analyses_to_invalidate = valid_analyses_ & (~preserved_analyses);
  79. InvalidateAnalyses(static_cast<IRContext::Analysis>(analyses_to_invalidate));
  80. }
  81. void IRContext::InvalidateAnalyses(IRContext::Analysis analyses_to_invalidate) {
  82. // The ConstantManager contains Type pointers. If the TypeManager goes
  83. // away, the ConstantManager has to go away.
  84. if (analyses_to_invalidate & kAnalysisTypes) {
  85. analyses_to_invalidate |= kAnalysisConstants;
  86. }
  87. // The dominator analysis hold the psuedo entry and exit nodes from the CFG.
  88. // Also if the CFG change the dominators many changed as well, so the
  89. // dominator analysis should be invalidated as well.
  90. if (analyses_to_invalidate & kAnalysisCFG) {
  91. analyses_to_invalidate |= kAnalysisDominatorAnalysis;
  92. }
  93. if (analyses_to_invalidate & kAnalysisDefUse) {
  94. def_use_mgr_.reset(nullptr);
  95. }
  96. if (analyses_to_invalidate & kAnalysisInstrToBlockMapping) {
  97. instr_to_block_.clear();
  98. }
  99. if (analyses_to_invalidate & kAnalysisDecorations) {
  100. decoration_mgr_.reset(nullptr);
  101. }
  102. if (analyses_to_invalidate & kAnalysisCombinators) {
  103. combinator_ops_.clear();
  104. }
  105. if (analyses_to_invalidate & kAnalysisBuiltinVarId) {
  106. builtin_var_id_map_.clear();
  107. }
  108. if (analyses_to_invalidate & kAnalysisCFG) {
  109. cfg_.reset(nullptr);
  110. }
  111. if (analyses_to_invalidate & kAnalysisDominatorAnalysis) {
  112. dominator_trees_.clear();
  113. post_dominator_trees_.clear();
  114. }
  115. if (analyses_to_invalidate & kAnalysisNameMap) {
  116. id_to_name_.reset(nullptr);
  117. }
  118. if (analyses_to_invalidate & kAnalysisValueNumberTable) {
  119. vn_table_.reset(nullptr);
  120. }
  121. if (analyses_to_invalidate & kAnalysisStructuredCFG) {
  122. struct_cfg_analysis_.reset(nullptr);
  123. }
  124. if (analyses_to_invalidate & kAnalysisIdToFuncMapping) {
  125. id_to_func_.clear();
  126. }
  127. if (analyses_to_invalidate & kAnalysisConstants) {
  128. constant_mgr_.reset(nullptr);
  129. }
  130. if (analyses_to_invalidate & kAnalysisTypes) {
  131. type_mgr_.reset(nullptr);
  132. }
  133. valid_analyses_ = Analysis(valid_analyses_ & ~analyses_to_invalidate);
  134. }
  135. Instruction* IRContext::KillInst(Instruction* inst) {
  136. if (!inst) {
  137. return nullptr;
  138. }
  139. KillNamesAndDecorates(inst);
  140. if (AreAnalysesValid(kAnalysisDefUse)) {
  141. get_def_use_mgr()->ClearInst(inst);
  142. }
  143. if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
  144. instr_to_block_.erase(inst);
  145. }
  146. if (AreAnalysesValid(kAnalysisDecorations)) {
  147. if (inst->IsDecoration()) {
  148. decoration_mgr_->RemoveDecoration(inst);
  149. }
  150. }
  151. if (type_mgr_ && IsTypeInst(inst->opcode())) {
  152. type_mgr_->RemoveId(inst->result_id());
  153. }
  154. if (constant_mgr_ && IsConstantInst(inst->opcode())) {
  155. constant_mgr_->RemoveId(inst->result_id());
  156. }
  157. if (inst->opcode() == SpvOpCapability || inst->opcode() == SpvOpExtension) {
  158. // We reset the feature manager, instead of updating it, because it is just
  159. // as much work. We would have to remove all capabilities implied by this
  160. // capability that are not also implied by the remaining OpCapability
  161. // instructions. We could update extensions, but we will see if it is
  162. // needed.
  163. ResetFeatureManager();
  164. }
  165. RemoveFromIdToName(inst);
  166. Instruction* next_instruction = nullptr;
  167. if (inst->IsInAList()) {
  168. next_instruction = inst->NextNode();
  169. inst->RemoveFromList();
  170. delete inst;
  171. } else {
  172. // Needed for instructions that are not part of a list like OpLabels,
  173. // OpFunction, OpFunctionEnd, etc..
  174. inst->ToNop();
  175. }
  176. return next_instruction;
  177. }
  178. bool IRContext::KillDef(uint32_t id) {
  179. Instruction* def = get_def_use_mgr()->GetDef(id);
  180. if (def != nullptr) {
  181. KillInst(def);
  182. return true;
  183. }
  184. return false;
  185. }
  186. bool IRContext::ReplaceAllUsesWith(uint32_t before, uint32_t after) {
  187. return ReplaceAllUsesWithPredicate(
  188. before, after, [](Instruction*, uint32_t) { return true; });
  189. }
  190. bool IRContext::ReplaceAllUsesWithPredicate(
  191. uint32_t before, uint32_t after,
  192. const std::function<bool(Instruction*, uint32_t)>& predicate) {
  193. if (before == after) return false;
  194. // Ensure that |after| has been registered as def.
  195. assert(get_def_use_mgr()->GetDef(after) &&
  196. "'after' is not a registered def.");
  197. std::vector<std::pair<Instruction*, uint32_t>> uses_to_update;
  198. get_def_use_mgr()->ForEachUse(
  199. before, [&predicate, &uses_to_update](Instruction* user, uint32_t index) {
  200. if (predicate(user, index)) {
  201. uses_to_update.emplace_back(user, index);
  202. }
  203. });
  204. Instruction* prev = nullptr;
  205. for (auto p : uses_to_update) {
  206. Instruction* user = p.first;
  207. uint32_t index = p.second;
  208. if (prev == nullptr || prev != user) {
  209. ForgetUses(user);
  210. prev = user;
  211. }
  212. const uint32_t type_result_id_count =
  213. (user->result_id() != 0) + (user->type_id() != 0);
  214. if (index < type_result_id_count) {
  215. // Update the type_id. Note that result id is immutable so it should
  216. // never be updated.
  217. if (user->type_id() != 0 && index == 0) {
  218. user->SetResultType(after);
  219. } else if (user->type_id() == 0) {
  220. SPIRV_ASSERT(consumer_, false,
  221. "Result type id considered as use while the instruction "
  222. "doesn't have a result type id.");
  223. (void)consumer_; // Makes the compiler happy for release build.
  224. } else {
  225. SPIRV_ASSERT(consumer_, false,
  226. "Trying setting the immutable result id.");
  227. }
  228. } else {
  229. // Update an in-operand.
  230. uint32_t in_operand_pos = index - type_result_id_count;
  231. // Make the modification in the instruction.
  232. user->SetInOperand(in_operand_pos, {after});
  233. }
  234. AnalyzeUses(user);
  235. }
  236. return true;
  237. }
  238. bool IRContext::IsConsistent() {
  239. #ifndef SPIRV_CHECK_CONTEXT
  240. return true;
  241. #endif
  242. if (AreAnalysesValid(kAnalysisDefUse)) {
  243. analysis::DefUseManager new_def_use(module());
  244. if (*get_def_use_mgr() != new_def_use) {
  245. return false;
  246. }
  247. }
  248. if (AreAnalysesValid(kAnalysisInstrToBlockMapping)) {
  249. for (auto& func : *module()) {
  250. for (auto& block : func) {
  251. if (!block.WhileEachInst([this, &block](Instruction* inst) {
  252. if (get_instr_block(inst) != &block) {
  253. return false;
  254. }
  255. return true;
  256. }))
  257. return false;
  258. }
  259. }
  260. }
  261. if (!CheckCFG()) {
  262. return false;
  263. }
  264. if (AreAnalysesValid(kAnalysisDecorations)) {
  265. analysis::DecorationManager* dec_mgr = get_decoration_mgr();
  266. analysis::DecorationManager current(module());
  267. if (*dec_mgr != current) {
  268. return false;
  269. }
  270. }
  271. if (feature_mgr_ != nullptr) {
  272. FeatureManager current(grammar_);
  273. current.Analyze(module());
  274. if (current != *feature_mgr_) {
  275. return false;
  276. }
  277. }
  278. return true;
  279. }
  280. void IRContext::ForgetUses(Instruction* inst) {
  281. if (AreAnalysesValid(kAnalysisDefUse)) {
  282. get_def_use_mgr()->EraseUseRecordsOfOperandIds(inst);
  283. }
  284. if (AreAnalysesValid(kAnalysisDecorations)) {
  285. if (inst->IsDecoration()) {
  286. get_decoration_mgr()->RemoveDecoration(inst);
  287. }
  288. }
  289. RemoveFromIdToName(inst);
  290. }
  291. void IRContext::AnalyzeUses(Instruction* inst) {
  292. if (AreAnalysesValid(kAnalysisDefUse)) {
  293. get_def_use_mgr()->AnalyzeInstUse(inst);
  294. }
  295. if (AreAnalysesValid(kAnalysisDecorations)) {
  296. if (inst->IsDecoration()) {
  297. get_decoration_mgr()->AddDecoration(inst);
  298. }
  299. }
  300. if (id_to_name_ &&
  301. (inst->opcode() == SpvOpName || inst->opcode() == SpvOpMemberName)) {
  302. id_to_name_->insert({inst->GetSingleWordInOperand(0), inst});
  303. }
  304. }
  305. void IRContext::KillNamesAndDecorates(uint32_t id) {
  306. analysis::DecorationManager* dec_mgr = get_decoration_mgr();
  307. dec_mgr->RemoveDecorationsFrom(id);
  308. std::vector<Instruction*> name_to_kill;
  309. for (auto name : GetNames(id)) {
  310. name_to_kill.push_back(name.second);
  311. }
  312. for (Instruction* name_inst : name_to_kill) {
  313. KillInst(name_inst);
  314. }
  315. }
  316. void IRContext::KillNamesAndDecorates(Instruction* inst) {
  317. const uint32_t rId = inst->result_id();
  318. if (rId == 0) return;
  319. KillNamesAndDecorates(rId);
  320. }
  321. void IRContext::AddCombinatorsForCapability(uint32_t capability) {
  322. if (capability == SpvCapabilityShader) {
  323. combinator_ops_[0].insert({SpvOpNop,
  324. SpvOpUndef,
  325. SpvOpConstant,
  326. SpvOpConstantTrue,
  327. SpvOpConstantFalse,
  328. SpvOpConstantComposite,
  329. SpvOpConstantSampler,
  330. SpvOpConstantNull,
  331. SpvOpTypeVoid,
  332. SpvOpTypeBool,
  333. SpvOpTypeInt,
  334. SpvOpTypeFloat,
  335. SpvOpTypeVector,
  336. SpvOpTypeMatrix,
  337. SpvOpTypeImage,
  338. SpvOpTypeSampler,
  339. SpvOpTypeSampledImage,
  340. SpvOpTypeAccelerationStructureNV,
  341. SpvOpTypeArray,
  342. SpvOpTypeRuntimeArray,
  343. SpvOpTypeStruct,
  344. SpvOpTypeOpaque,
  345. SpvOpTypePointer,
  346. SpvOpTypeFunction,
  347. SpvOpTypeEvent,
  348. SpvOpTypeDeviceEvent,
  349. SpvOpTypeReserveId,
  350. SpvOpTypeQueue,
  351. SpvOpTypePipe,
  352. SpvOpTypeForwardPointer,
  353. SpvOpVariable,
  354. SpvOpImageTexelPointer,
  355. SpvOpLoad,
  356. SpvOpAccessChain,
  357. SpvOpInBoundsAccessChain,
  358. SpvOpArrayLength,
  359. SpvOpVectorExtractDynamic,
  360. SpvOpVectorInsertDynamic,
  361. SpvOpVectorShuffle,
  362. SpvOpCompositeConstruct,
  363. SpvOpCompositeExtract,
  364. SpvOpCompositeInsert,
  365. SpvOpCopyObject,
  366. SpvOpTranspose,
  367. SpvOpSampledImage,
  368. SpvOpImageSampleImplicitLod,
  369. SpvOpImageSampleExplicitLod,
  370. SpvOpImageSampleDrefImplicitLod,
  371. SpvOpImageSampleDrefExplicitLod,
  372. SpvOpImageSampleProjImplicitLod,
  373. SpvOpImageSampleProjExplicitLod,
  374. SpvOpImageSampleProjDrefImplicitLod,
  375. SpvOpImageSampleProjDrefExplicitLod,
  376. SpvOpImageFetch,
  377. SpvOpImageGather,
  378. SpvOpImageDrefGather,
  379. SpvOpImageRead,
  380. SpvOpImage,
  381. SpvOpImageQueryFormat,
  382. SpvOpImageQueryOrder,
  383. SpvOpImageQuerySizeLod,
  384. SpvOpImageQuerySize,
  385. SpvOpImageQueryLevels,
  386. SpvOpImageQuerySamples,
  387. SpvOpConvertFToU,
  388. SpvOpConvertFToS,
  389. SpvOpConvertSToF,
  390. SpvOpConvertUToF,
  391. SpvOpUConvert,
  392. SpvOpSConvert,
  393. SpvOpFConvert,
  394. SpvOpQuantizeToF16,
  395. SpvOpBitcast,
  396. SpvOpSNegate,
  397. SpvOpFNegate,
  398. SpvOpIAdd,
  399. SpvOpFAdd,
  400. SpvOpISub,
  401. SpvOpFSub,
  402. SpvOpIMul,
  403. SpvOpFMul,
  404. SpvOpUDiv,
  405. SpvOpSDiv,
  406. SpvOpFDiv,
  407. SpvOpUMod,
  408. SpvOpSRem,
  409. SpvOpSMod,
  410. SpvOpFRem,
  411. SpvOpFMod,
  412. SpvOpVectorTimesScalar,
  413. SpvOpMatrixTimesScalar,
  414. SpvOpVectorTimesMatrix,
  415. SpvOpMatrixTimesVector,
  416. SpvOpMatrixTimesMatrix,
  417. SpvOpOuterProduct,
  418. SpvOpDot,
  419. SpvOpIAddCarry,
  420. SpvOpISubBorrow,
  421. SpvOpUMulExtended,
  422. SpvOpSMulExtended,
  423. SpvOpAny,
  424. SpvOpAll,
  425. SpvOpIsNan,
  426. SpvOpIsInf,
  427. SpvOpLogicalEqual,
  428. SpvOpLogicalNotEqual,
  429. SpvOpLogicalOr,
  430. SpvOpLogicalAnd,
  431. SpvOpLogicalNot,
  432. SpvOpSelect,
  433. SpvOpIEqual,
  434. SpvOpINotEqual,
  435. SpvOpUGreaterThan,
  436. SpvOpSGreaterThan,
  437. SpvOpUGreaterThanEqual,
  438. SpvOpSGreaterThanEqual,
  439. SpvOpULessThan,
  440. SpvOpSLessThan,
  441. SpvOpULessThanEqual,
  442. SpvOpSLessThanEqual,
  443. SpvOpFOrdEqual,
  444. SpvOpFUnordEqual,
  445. SpvOpFOrdNotEqual,
  446. SpvOpFUnordNotEqual,
  447. SpvOpFOrdLessThan,
  448. SpvOpFUnordLessThan,
  449. SpvOpFOrdGreaterThan,
  450. SpvOpFUnordGreaterThan,
  451. SpvOpFOrdLessThanEqual,
  452. SpvOpFUnordLessThanEqual,
  453. SpvOpFOrdGreaterThanEqual,
  454. SpvOpFUnordGreaterThanEqual,
  455. SpvOpShiftRightLogical,
  456. SpvOpShiftRightArithmetic,
  457. SpvOpShiftLeftLogical,
  458. SpvOpBitwiseOr,
  459. SpvOpBitwiseXor,
  460. SpvOpBitwiseAnd,
  461. SpvOpNot,
  462. SpvOpBitFieldInsert,
  463. SpvOpBitFieldSExtract,
  464. SpvOpBitFieldUExtract,
  465. SpvOpBitReverse,
  466. SpvOpBitCount,
  467. SpvOpPhi,
  468. SpvOpImageSparseSampleImplicitLod,
  469. SpvOpImageSparseSampleExplicitLod,
  470. SpvOpImageSparseSampleDrefImplicitLod,
  471. SpvOpImageSparseSampleDrefExplicitLod,
  472. SpvOpImageSparseSampleProjImplicitLod,
  473. SpvOpImageSparseSampleProjExplicitLod,
  474. SpvOpImageSparseSampleProjDrefImplicitLod,
  475. SpvOpImageSparseSampleProjDrefExplicitLod,
  476. SpvOpImageSparseFetch,
  477. SpvOpImageSparseGather,
  478. SpvOpImageSparseDrefGather,
  479. SpvOpImageSparseTexelsResident,
  480. SpvOpImageSparseRead,
  481. SpvOpSizeOf});
  482. }
  483. }
  484. void IRContext::AddCombinatorsForExtension(Instruction* extension) {
  485. assert(extension->opcode() == SpvOpExtInstImport &&
  486. "Expecting an import of an extension's instruction set.");
  487. const char* extension_name =
  488. reinterpret_cast<const char*>(&extension->GetInOperand(0).words[0]);
  489. if (!strcmp(extension_name, "GLSL.std.450")) {
  490. combinator_ops_[extension->result_id()] = {GLSLstd450Round,
  491. GLSLstd450RoundEven,
  492. GLSLstd450Trunc,
  493. GLSLstd450FAbs,
  494. GLSLstd450SAbs,
  495. GLSLstd450FSign,
  496. GLSLstd450SSign,
  497. GLSLstd450Floor,
  498. GLSLstd450Ceil,
  499. GLSLstd450Fract,
  500. GLSLstd450Radians,
  501. GLSLstd450Degrees,
  502. GLSLstd450Sin,
  503. GLSLstd450Cos,
  504. GLSLstd450Tan,
  505. GLSLstd450Asin,
  506. GLSLstd450Acos,
  507. GLSLstd450Atan,
  508. GLSLstd450Sinh,
  509. GLSLstd450Cosh,
  510. GLSLstd450Tanh,
  511. GLSLstd450Asinh,
  512. GLSLstd450Acosh,
  513. GLSLstd450Atanh,
  514. GLSLstd450Atan2,
  515. GLSLstd450Pow,
  516. GLSLstd450Exp,
  517. GLSLstd450Log,
  518. GLSLstd450Exp2,
  519. GLSLstd450Log2,
  520. GLSLstd450Sqrt,
  521. GLSLstd450InverseSqrt,
  522. GLSLstd450Determinant,
  523. GLSLstd450MatrixInverse,
  524. GLSLstd450ModfStruct,
  525. GLSLstd450FMin,
  526. GLSLstd450UMin,
  527. GLSLstd450SMin,
  528. GLSLstd450FMax,
  529. GLSLstd450UMax,
  530. GLSLstd450SMax,
  531. GLSLstd450FClamp,
  532. GLSLstd450UClamp,
  533. GLSLstd450SClamp,
  534. GLSLstd450FMix,
  535. GLSLstd450IMix,
  536. GLSLstd450Step,
  537. GLSLstd450SmoothStep,
  538. GLSLstd450Fma,
  539. GLSLstd450FrexpStruct,
  540. GLSLstd450Ldexp,
  541. GLSLstd450PackSnorm4x8,
  542. GLSLstd450PackUnorm4x8,
  543. GLSLstd450PackSnorm2x16,
  544. GLSLstd450PackUnorm2x16,
  545. GLSLstd450PackHalf2x16,
  546. GLSLstd450PackDouble2x32,
  547. GLSLstd450UnpackSnorm2x16,
  548. GLSLstd450UnpackUnorm2x16,
  549. GLSLstd450UnpackHalf2x16,
  550. GLSLstd450UnpackSnorm4x8,
  551. GLSLstd450UnpackUnorm4x8,
  552. GLSLstd450UnpackDouble2x32,
  553. GLSLstd450Length,
  554. GLSLstd450Distance,
  555. GLSLstd450Cross,
  556. GLSLstd450Normalize,
  557. GLSLstd450FaceForward,
  558. GLSLstd450Reflect,
  559. GLSLstd450Refract,
  560. GLSLstd450FindILsb,
  561. GLSLstd450FindSMsb,
  562. GLSLstd450FindUMsb,
  563. GLSLstd450InterpolateAtCentroid,
  564. GLSLstd450InterpolateAtSample,
  565. GLSLstd450InterpolateAtOffset,
  566. GLSLstd450NMin,
  567. GLSLstd450NMax,
  568. GLSLstd450NClamp};
  569. } else {
  570. // Map the result id to the empty set.
  571. combinator_ops_[extension->result_id()];
  572. }
  573. }
  574. void IRContext::InitializeCombinators() {
  575. get_feature_mgr()->GetCapabilities()->ForEach(
  576. [this](SpvCapability cap) { AddCombinatorsForCapability(cap); });
  577. for (auto& extension : module()->ext_inst_imports()) {
  578. AddCombinatorsForExtension(&extension);
  579. }
  580. valid_analyses_ |= kAnalysisCombinators;
  581. }
  582. void IRContext::RemoveFromIdToName(const Instruction* inst) {
  583. if (id_to_name_ &&
  584. (inst->opcode() == SpvOpName || inst->opcode() == SpvOpMemberName)) {
  585. auto range = id_to_name_->equal_range(inst->GetSingleWordInOperand(0));
  586. for (auto it = range.first; it != range.second; ++it) {
  587. if (it->second == inst) {
  588. id_to_name_->erase(it);
  589. break;
  590. }
  591. }
  592. }
  593. }
  594. LoopDescriptor* IRContext::GetLoopDescriptor(const Function* f) {
  595. if (!AreAnalysesValid(kAnalysisLoopAnalysis)) {
  596. ResetLoopAnalysis();
  597. }
  598. std::unordered_map<const Function*, LoopDescriptor>::iterator it =
  599. loop_descriptors_.find(f);
  600. if (it == loop_descriptors_.end()) {
  601. return &loop_descriptors_
  602. .emplace(std::make_pair(f, LoopDescriptor(this, f)))
  603. .first->second;
  604. }
  605. return &it->second;
  606. }
  607. uint32_t IRContext::FindBuiltinInputVar(uint32_t builtin) {
  608. for (auto& a : module_->annotations()) {
  609. if (a.opcode() != SpvOpDecorate) continue;
  610. if (a.GetSingleWordInOperand(kSpvDecorateDecorationInIdx) !=
  611. SpvDecorationBuiltIn)
  612. continue;
  613. if (a.GetSingleWordInOperand(kSpvDecorateBuiltinInIdx) != builtin) continue;
  614. uint32_t target_id = a.GetSingleWordInOperand(kSpvDecorateTargetIdInIdx);
  615. Instruction* b_var = get_def_use_mgr()->GetDef(target_id);
  616. if (b_var->opcode() != SpvOpVariable) continue;
  617. if (b_var->GetSingleWordInOperand(0) != SpvStorageClassInput) continue;
  618. return target_id;
  619. }
  620. return 0;
  621. }
  622. void IRContext::AddVarToEntryPoints(uint32_t var_id) {
  623. uint32_t ocnt = 0;
  624. for (auto& e : module()->entry_points()) {
  625. bool found = false;
  626. e.ForEachInOperand([&ocnt, &found, &var_id](const uint32_t* idp) {
  627. if (ocnt >= kEntryPointInterfaceInIdx) {
  628. if (*idp == var_id) found = true;
  629. }
  630. ++ocnt;
  631. });
  632. if (!found) {
  633. e.AddOperand({SPV_OPERAND_TYPE_ID, {var_id}});
  634. get_def_use_mgr()->AnalyzeInstDefUse(&e);
  635. }
  636. }
  637. }
  638. uint32_t IRContext::GetBuiltinInputVarId(uint32_t builtin) {
  639. if (!AreAnalysesValid(kAnalysisBuiltinVarId)) ResetBuiltinAnalysis();
  640. // If cached, return it.
  641. std::unordered_map<uint32_t, uint32_t>::iterator it =
  642. builtin_var_id_map_.find(builtin);
  643. if (it != builtin_var_id_map_.end()) return it->second;
  644. // Look for one in shader
  645. uint32_t var_id = FindBuiltinInputVar(builtin);
  646. if (var_id == 0) {
  647. // If not found, create it
  648. // TODO(greg-lunarg): Add support for all builtins
  649. analysis::TypeManager* type_mgr = get_type_mgr();
  650. analysis::Type* reg_type;
  651. switch (builtin) {
  652. case SpvBuiltInFragCoord: {
  653. analysis::Float float_ty(32);
  654. analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
  655. analysis::Vector v4float_ty(reg_float_ty, 4);
  656. reg_type = type_mgr->GetRegisteredType(&v4float_ty);
  657. break;
  658. }
  659. case SpvBuiltInVertexIndex:
  660. case SpvBuiltInInstanceIndex:
  661. case SpvBuiltInPrimitiveId:
  662. case SpvBuiltInInvocationId:
  663. case SpvBuiltInSubgroupLocalInvocationId: {
  664. analysis::Integer uint_ty(32, false);
  665. reg_type = type_mgr->GetRegisteredType(&uint_ty);
  666. break;
  667. }
  668. case SpvBuiltInGlobalInvocationId:
  669. case SpvBuiltInLaunchIdNV: {
  670. analysis::Integer uint_ty(32, false);
  671. analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
  672. analysis::Vector v3uint_ty(reg_uint_ty, 3);
  673. reg_type = type_mgr->GetRegisteredType(&v3uint_ty);
  674. break;
  675. }
  676. case SpvBuiltInTessCoord: {
  677. analysis::Float float_ty(32);
  678. analysis::Type* reg_float_ty = type_mgr->GetRegisteredType(&float_ty);
  679. analysis::Vector v3float_ty(reg_float_ty, 3);
  680. reg_type = type_mgr->GetRegisteredType(&v3float_ty);
  681. break;
  682. }
  683. case SpvBuiltInSubgroupLtMask: {
  684. analysis::Integer uint_ty(32, false);
  685. analysis::Type* reg_uint_ty = type_mgr->GetRegisteredType(&uint_ty);
  686. analysis::Vector v4uint_ty(reg_uint_ty, 4);
  687. reg_type = type_mgr->GetRegisteredType(&v4uint_ty);
  688. break;
  689. }
  690. default: {
  691. assert(false && "unhandled builtin");
  692. return 0;
  693. }
  694. }
  695. uint32_t type_id = type_mgr->GetTypeInstruction(reg_type);
  696. uint32_t varTyPtrId =
  697. type_mgr->FindPointerToType(type_id, SpvStorageClassInput);
  698. // TODO(1841): Handle id overflow.
  699. var_id = TakeNextId();
  700. std::unique_ptr<Instruction> newVarOp(
  701. new Instruction(this, SpvOpVariable, varTyPtrId, var_id,
  702. {{spv_operand_type_t::SPV_OPERAND_TYPE_LITERAL_INTEGER,
  703. {SpvStorageClassInput}}}));
  704. get_def_use_mgr()->AnalyzeInstDefUse(&*newVarOp);
  705. module()->AddGlobalValue(std::move(newVarOp));
  706. get_decoration_mgr()->AddDecorationVal(var_id, SpvDecorationBuiltIn,
  707. builtin);
  708. AddVarToEntryPoints(var_id);
  709. }
  710. builtin_var_id_map_[builtin] = var_id;
  711. return var_id;
  712. }
  713. void IRContext::AddCalls(const Function* func, std::queue<uint32_t>* todo) {
  714. for (auto bi = func->begin(); bi != func->end(); ++bi)
  715. for (auto ii = bi->begin(); ii != bi->end(); ++ii)
  716. if (ii->opcode() == SpvOpFunctionCall)
  717. todo->push(ii->GetSingleWordInOperand(0));
  718. }
  719. bool IRContext::ProcessEntryPointCallTree(ProcessFunction& pfn) {
  720. // Collect all of the entry points as the roots.
  721. std::queue<uint32_t> roots;
  722. for (auto& e : module()->entry_points()) {
  723. roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
  724. }
  725. return ProcessCallTreeFromRoots(pfn, &roots);
  726. }
  727. bool IRContext::ProcessReachableCallTree(ProcessFunction& pfn) {
  728. std::queue<uint32_t> roots;
  729. // Add all entry points since they can be reached from outside the module.
  730. for (auto& e : module()->entry_points())
  731. roots.push(e.GetSingleWordInOperand(kEntryPointFunctionIdInIdx));
  732. // Add all exported functions since they can be reached from outside the
  733. // module.
  734. for (auto& a : annotations()) {
  735. // TODO: Handle group decorations as well. Currently not generate by any
  736. // front-end, but could be coming.
  737. if (a.opcode() == SpvOp::SpvOpDecorate) {
  738. if (a.GetSingleWordOperand(1) ==
  739. SpvDecoration::SpvDecorationLinkageAttributes) {
  740. uint32_t lastOperand = a.NumOperands() - 1;
  741. if (a.GetSingleWordOperand(lastOperand) ==
  742. SpvLinkageType::SpvLinkageTypeExport) {
  743. uint32_t id = a.GetSingleWordOperand(0);
  744. if (GetFunction(id)) {
  745. roots.push(id);
  746. }
  747. }
  748. }
  749. }
  750. }
  751. return ProcessCallTreeFromRoots(pfn, &roots);
  752. }
  753. bool IRContext::ProcessCallTreeFromRoots(ProcessFunction& pfn,
  754. std::queue<uint32_t>* roots) {
  755. // Process call tree
  756. bool modified = false;
  757. std::unordered_set<uint32_t> done;
  758. while (!roots->empty()) {
  759. const uint32_t fi = roots->front();
  760. roots->pop();
  761. if (done.insert(fi).second) {
  762. Function* fn = GetFunction(fi);
  763. modified = pfn(fn) || modified;
  764. AddCalls(fn, roots);
  765. }
  766. }
  767. return modified;
  768. }
  769. void IRContext::EmitErrorMessage(std::string message, Instruction* inst) {
  770. if (!consumer()) {
  771. return;
  772. }
  773. Instruction* line_inst = inst;
  774. while (line_inst != nullptr) { // Stop at the beginning of the basic block.
  775. if (!line_inst->dbg_line_insts().empty()) {
  776. line_inst = &line_inst->dbg_line_insts().back();
  777. if (line_inst->opcode() == SpvOpNoLine) {
  778. line_inst = nullptr;
  779. }
  780. break;
  781. }
  782. line_inst = line_inst->PreviousNode();
  783. }
  784. uint32_t line_number = 0;
  785. uint32_t col_number = 0;
  786. char* source = nullptr;
  787. if (line_inst != nullptr) {
  788. Instruction* file_name =
  789. get_def_use_mgr()->GetDef(line_inst->GetSingleWordInOperand(0));
  790. source = reinterpret_cast<char*>(&file_name->GetInOperand(0).words[0]);
  791. // Get the line number and column number.
  792. line_number = line_inst->GetSingleWordInOperand(1);
  793. col_number = line_inst->GetSingleWordInOperand(2);
  794. }
  795. message +=
  796. "\n " + inst->PrettyPrint(SPV_BINARY_TO_TEXT_OPTION_FRIENDLY_NAMES);
  797. consumer()(SPV_MSG_ERROR, source, {line_number, col_number, 0},
  798. message.c_str());
  799. }
  800. // Gets the dominator analysis for function |f|.
  801. DominatorAnalysis* IRContext::GetDominatorAnalysis(const Function* f) {
  802. if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
  803. ResetDominatorAnalysis();
  804. }
  805. if (dominator_trees_.find(f) == dominator_trees_.end()) {
  806. dominator_trees_[f].InitializeTree(*cfg(), f);
  807. }
  808. return &dominator_trees_[f];
  809. }
  810. // Gets the postdominator analysis for function |f|.
  811. PostDominatorAnalysis* IRContext::GetPostDominatorAnalysis(const Function* f) {
  812. if (!AreAnalysesValid(kAnalysisDominatorAnalysis)) {
  813. ResetDominatorAnalysis();
  814. }
  815. if (post_dominator_trees_.find(f) == post_dominator_trees_.end()) {
  816. post_dominator_trees_[f].InitializeTree(*cfg(), f);
  817. }
  818. return &post_dominator_trees_[f];
  819. }
  820. bool IRContext::CheckCFG() {
  821. std::unordered_map<uint32_t, std::vector<uint32_t>> real_preds;
  822. if (!AreAnalysesValid(kAnalysisCFG)) {
  823. return true;
  824. }
  825. for (Function& function : *module()) {
  826. for (const auto& bb : function) {
  827. bb.ForEachSuccessorLabel([&bb, &real_preds](const uint32_t lab_id) {
  828. real_preds[lab_id].push_back(bb.id());
  829. });
  830. }
  831. for (auto& bb : function) {
  832. std::vector<uint32_t> preds = cfg()->preds(bb.id());
  833. std::vector<uint32_t> real = real_preds[bb.id()];
  834. std::sort(preds.begin(), preds.end());
  835. std::sort(real.begin(), real.end());
  836. bool same = true;
  837. if (preds.size() != real.size()) {
  838. same = false;
  839. }
  840. for (size_t i = 0; i < real.size() && same; i++) {
  841. if (preds[i] != real[i]) {
  842. same = false;
  843. }
  844. }
  845. if (!same) {
  846. std::cerr << "Predecessors for " << bb.id() << " are different:\n";
  847. std::cerr << "Real:";
  848. for (uint32_t i : real) {
  849. std::cerr << ' ' << i;
  850. }
  851. std::cerr << std::endl;
  852. std::cerr << "Recorded:";
  853. for (uint32_t i : preds) {
  854. std::cerr << ' ' << i;
  855. }
  856. std::cerr << std::endl;
  857. }
  858. if (!same) return false;
  859. }
  860. }
  861. return true;
  862. }
  863. } // namespace opt
  864. } // namespace spvtools