ir_context.cpp 31 KB

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