ccp_pass.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377
  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. // This file implements conditional constant propagation as described in
  15. //
  16. // Constant propagation with conditional branches,
  17. // Wegman and Zadeck, ACM TOPLAS 13(2):181-210.
  18. #include "source/opt/ccp_pass.h"
  19. #include <algorithm>
  20. #include <limits>
  21. #include "source/opt/fold.h"
  22. #include "source/opt/function.h"
  23. #include "source/opt/propagator.h"
  24. namespace spvtools {
  25. namespace opt {
  26. namespace {
  27. // This SSA id is never defined nor referenced in the IR. It is a special ID
  28. // which represents varying values. When an ID is found to have a varying
  29. // value, its entry in the |values_| table maps to kVaryingSSAId.
  30. constexpr uint32_t kVaryingSSAId = std::numeric_limits<uint32_t>::max();
  31. } // namespace
  32. bool CCPPass::IsVaryingValue(uint32_t id) const { return id == kVaryingSSAId; }
  33. SSAPropagator::PropStatus CCPPass::MarkInstructionVarying(Instruction* instr) {
  34. assert(instr->result_id() != 0 &&
  35. "Instructions with no result cannot be marked varying.");
  36. values_[instr->result_id()] = kVaryingSSAId;
  37. return SSAPropagator::kVarying;
  38. }
  39. SSAPropagator::PropStatus CCPPass::VisitPhi(Instruction* phi) {
  40. uint32_t meet_val_id = 0;
  41. // Implement the lattice meet operation. The result of this Phi instruction is
  42. // interesting only if the meet operation over arguments coming through
  43. // executable edges yields the same constant value.
  44. for (uint32_t i = 2; i < phi->NumOperands(); i += 2) {
  45. if (!propagator_->IsPhiArgExecutable(phi, i)) {
  46. // Ignore arguments coming through non-executable edges.
  47. continue;
  48. }
  49. uint32_t phi_arg_id = phi->GetSingleWordOperand(i);
  50. auto it = values_.find(phi_arg_id);
  51. if (it != values_.end()) {
  52. // We found an argument with a constant value. Apply the meet operation
  53. // with the previous arguments.
  54. if (it->second == kVaryingSSAId) {
  55. // The "constant" value is actually a placeholder for varying. Return
  56. // varying for this phi.
  57. return MarkInstructionVarying(phi);
  58. } else if (meet_val_id == 0) {
  59. // This is the first argument we find. Initialize the result to its
  60. // constant value id.
  61. meet_val_id = it->second;
  62. } else if (it->second == meet_val_id) {
  63. // The argument is the same constant value already computed. Continue
  64. // looking.
  65. continue;
  66. } else {
  67. // We either found a varying value, or another constant value different
  68. // from the previous computed meet value. This Phi will never be
  69. // constant.
  70. return MarkInstructionVarying(phi);
  71. }
  72. } else {
  73. // The incoming value has no recorded value and is therefore not
  74. // interesting. A not interesting value joined with any other value is the
  75. // other value.
  76. continue;
  77. }
  78. }
  79. // If there are no incoming executable edges, the meet ID will still be 0. In
  80. // that case, return not interesting to evaluate the Phi node again.
  81. if (meet_val_id == 0) {
  82. return SSAPropagator::kNotInteresting;
  83. }
  84. // All the operands have the same constant value represented by |meet_val_id|.
  85. // Set the Phi's result to that value and declare it interesting.
  86. values_[phi->result_id()] = meet_val_id;
  87. return SSAPropagator::kInteresting;
  88. }
  89. uint32_t CCPPass::ComputeLatticeMeet(Instruction* instr, uint32_t val2) {
  90. // Given two values val1 and val2, the meet operation in the constant
  91. // lattice uses the following rules:
  92. //
  93. // meet(val1, UNDEFINED) = val1
  94. // meet(val1, VARYING) = VARYING
  95. // meet(val1, val2) = val1 if val1 == val2
  96. // meet(val1, val2) = VARYING if val1 != val2
  97. //
  98. // When two different values meet, the result is always varying because CCP
  99. // does not allow lateral transitions in the lattice. This prevents
  100. // infinite cycles during propagation.
  101. auto val1_it = values_.find(instr->result_id());
  102. if (val1_it == values_.end()) {
  103. return val2;
  104. }
  105. uint32_t val1 = val1_it->second;
  106. if (IsVaryingValue(val1)) {
  107. return val1;
  108. } else if (IsVaryingValue(val2)) {
  109. return val2;
  110. } else if (val1 != val2) {
  111. return kVaryingSSAId;
  112. }
  113. return val2;
  114. }
  115. SSAPropagator::PropStatus CCPPass::VisitAssignment(Instruction* instr) {
  116. assert(instr->result_id() != 0 &&
  117. "Expecting an instruction that produces a result");
  118. // If this is a copy operation, and the RHS is a known constant, assign its
  119. // value to the LHS.
  120. if (instr->opcode() == spv::Op::OpCopyObject) {
  121. uint32_t rhs_id = instr->GetSingleWordInOperand(0);
  122. auto it = values_.find(rhs_id);
  123. if (it != values_.end()) {
  124. if (IsVaryingValue(it->second)) {
  125. return MarkInstructionVarying(instr);
  126. } else {
  127. uint32_t new_val = ComputeLatticeMeet(instr, it->second);
  128. values_[instr->result_id()] = new_val;
  129. return IsVaryingValue(new_val) ? SSAPropagator::kVarying
  130. : SSAPropagator::kInteresting;
  131. }
  132. }
  133. return SSAPropagator::kNotInteresting;
  134. }
  135. // Instructions with a RHS that cannot produce a constant are always varying.
  136. if (!instr->IsFoldable()) {
  137. return MarkInstructionVarying(instr);
  138. }
  139. // See if the RHS of the assignment folds into a constant value.
  140. auto map_func = [this](uint32_t id) {
  141. auto it = values_.find(id);
  142. if (it == values_.end() || IsVaryingValue(it->second)) {
  143. return id;
  144. }
  145. return it->second;
  146. };
  147. Instruction* folded_inst =
  148. context()->get_instruction_folder().FoldInstructionToConstant(instr,
  149. map_func);
  150. if (folded_inst != nullptr) {
  151. // We do not want to change the body of the function by adding new
  152. // instructions. When folding we can only generate new constants.
  153. assert((folded_inst->IsConstant() ||
  154. IsSpecConstantInst(folded_inst->opcode())) &&
  155. "CCP is only interested in constant values.");
  156. uint32_t new_val = ComputeLatticeMeet(instr, folded_inst->result_id());
  157. values_[instr->result_id()] = new_val;
  158. return IsVaryingValue(new_val) ? SSAPropagator::kVarying
  159. : SSAPropagator::kInteresting;
  160. }
  161. // Conservatively mark this instruction as varying if any input id is varying.
  162. if (!instr->WhileEachInId([this](uint32_t* op_id) {
  163. auto iter = values_.find(*op_id);
  164. if (iter != values_.end() && IsVaryingValue(iter->second)) return false;
  165. return true;
  166. })) {
  167. return MarkInstructionVarying(instr);
  168. }
  169. // If not, see if there is a least one unknown operand to the instruction. If
  170. // so, we might be able to fold it later.
  171. if (!instr->WhileEachInId([this](uint32_t* op_id) {
  172. auto it = values_.find(*op_id);
  173. if (it == values_.end()) return false;
  174. return true;
  175. })) {
  176. return SSAPropagator::kNotInteresting;
  177. }
  178. // Otherwise, we will never be able to fold this instruction, so mark it
  179. // varying.
  180. return MarkInstructionVarying(instr);
  181. }
  182. SSAPropagator::PropStatus CCPPass::VisitBranch(Instruction* instr,
  183. BasicBlock** dest_bb) const {
  184. assert(instr->IsBranch() && "Expected a branch instruction.");
  185. *dest_bb = nullptr;
  186. uint32_t dest_label = 0;
  187. if (instr->opcode() == spv::Op::OpBranch) {
  188. // An unconditional jump always goes to its unique destination.
  189. dest_label = instr->GetSingleWordInOperand(0);
  190. } else if (instr->opcode() == spv::Op::OpBranchConditional) {
  191. // For a conditional branch, determine whether the predicate selector has a
  192. // known value in |values_|. If it does, set the destination block
  193. // according to the selector's boolean value.
  194. uint32_t pred_id = instr->GetSingleWordOperand(0);
  195. auto it = values_.find(pred_id);
  196. if (it == values_.end() || IsVaryingValue(it->second)) {
  197. // The predicate has an unknown value, either branch could be taken.
  198. return SSAPropagator::kVarying;
  199. }
  200. // Get the constant value for the predicate selector from the value table.
  201. // Use it to decide which branch will be taken.
  202. uint32_t pred_val_id = it->second;
  203. const analysis::Constant* c = const_mgr_->FindDeclaredConstant(pred_val_id);
  204. assert(c && "Expected to find a constant declaration for a known value.");
  205. // Undef values should have returned as varying above.
  206. assert(c->AsBoolConstant() || c->AsNullConstant());
  207. if (c->AsNullConstant()) {
  208. dest_label = instr->GetSingleWordOperand(2u);
  209. } else {
  210. const analysis::BoolConstant* val = c->AsBoolConstant();
  211. dest_label = val->value() ? instr->GetSingleWordOperand(1)
  212. : instr->GetSingleWordOperand(2);
  213. }
  214. } else {
  215. // For an OpSwitch, extract the value taken by the switch selector and check
  216. // which of the target literals it matches. The branch associated with that
  217. // literal is the taken branch.
  218. assert(instr->opcode() == spv::Op::OpSwitch);
  219. if (instr->GetOperand(0).words.size() != 1) {
  220. // If the selector is wider than 32-bits, return varying. TODO(dnovillo):
  221. // Add support for wider constants.
  222. return SSAPropagator::kVarying;
  223. }
  224. uint32_t select_id = instr->GetSingleWordOperand(0);
  225. auto it = values_.find(select_id);
  226. if (it == values_.end() || IsVaryingValue(it->second)) {
  227. // The selector has an unknown value, any of the branches could be taken.
  228. return SSAPropagator::kVarying;
  229. }
  230. // Get the constant value for the selector from the value table. Use it to
  231. // decide which branch will be taken.
  232. uint32_t select_val_id = it->second;
  233. const analysis::Constant* c =
  234. const_mgr_->FindDeclaredConstant(select_val_id);
  235. assert(c && "Expected to find a constant declaration for a known value.");
  236. // TODO: support 64-bit integer switches.
  237. uint32_t constant_cond = 0;
  238. if (const analysis::IntConstant* val = c->AsIntConstant()) {
  239. constant_cond = val->words()[0];
  240. } else {
  241. // Undef values should have returned varying above.
  242. assert(c->AsNullConstant());
  243. constant_cond = 0;
  244. }
  245. // Start assuming that the selector will take the default value;
  246. dest_label = instr->GetSingleWordOperand(1);
  247. for (uint32_t i = 2; i < instr->NumOperands(); i += 2) {
  248. if (constant_cond == instr->GetSingleWordOperand(i)) {
  249. dest_label = instr->GetSingleWordOperand(i + 1);
  250. break;
  251. }
  252. }
  253. }
  254. assert(dest_label && "Destination label should be set at this point.");
  255. *dest_bb = context()->cfg()->block(dest_label);
  256. return SSAPropagator::kInteresting;
  257. }
  258. SSAPropagator::PropStatus CCPPass::VisitInstruction(Instruction* instr,
  259. BasicBlock** dest_bb) {
  260. *dest_bb = nullptr;
  261. if (instr->opcode() == spv::Op::OpPhi) {
  262. return VisitPhi(instr);
  263. } else if (instr->IsBranch()) {
  264. return VisitBranch(instr, dest_bb);
  265. } else if (instr->result_id()) {
  266. return VisitAssignment(instr);
  267. }
  268. return SSAPropagator::kVarying;
  269. }
  270. bool CCPPass::ReplaceValues() {
  271. // Even if we make no changes to the function's IR, propagation may have
  272. // created new constants. Even if those constants cannot be replaced in
  273. // the IR, the constant definition itself is a change. To reflect this,
  274. // we check whether the next ID to be given by the module is different than
  275. // the original bound ID. If that happens, new instructions were added to the
  276. // module during propagation.
  277. //
  278. // See https://github.com/KhronosGroup/SPIRV-Tools/issues/3636 and
  279. // https://github.com/KhronosGroup/SPIRV-Tools/issues/3991 for details.
  280. bool changed_ir = (context()->module()->IdBound() > original_id_bound_);
  281. for (const auto& it : values_) {
  282. uint32_t id = it.first;
  283. uint32_t cst_id = it.second;
  284. if (!IsVaryingValue(cst_id) && id != cst_id) {
  285. context()->KillNamesAndDecorates(id);
  286. changed_ir |= context()->ReplaceAllUsesWith(id, cst_id);
  287. }
  288. }
  289. return changed_ir;
  290. }
  291. bool CCPPass::PropagateConstants(Function* fp) {
  292. if (fp->IsDeclaration()) {
  293. return false;
  294. }
  295. // Mark function parameters as varying.
  296. fp->ForEachParam([this](const Instruction* inst) {
  297. values_[inst->result_id()] = kVaryingSSAId;
  298. });
  299. const auto visit_fn = [this](Instruction* instr, BasicBlock** dest_bb) {
  300. return VisitInstruction(instr, dest_bb);
  301. };
  302. propagator_ =
  303. std::unique_ptr<SSAPropagator>(new SSAPropagator(context(), visit_fn));
  304. if (propagator_->Run(fp)) {
  305. return ReplaceValues();
  306. }
  307. return false;
  308. }
  309. void CCPPass::Initialize() {
  310. const_mgr_ = context()->get_constant_mgr();
  311. // Populate the constant table with values from constant declarations in the
  312. // module. The values of each OpConstant declaration is the identity
  313. // assignment (i.e., each constant is its own value).
  314. for (const auto& inst : get_module()->types_values()) {
  315. // Record compile time constant ids. Treat all other global values as
  316. // varying.
  317. if (inst.IsConstant()) {
  318. values_[inst.result_id()] = inst.result_id();
  319. } else {
  320. values_[inst.result_id()] = kVaryingSSAId;
  321. }
  322. }
  323. original_id_bound_ = context()->module()->IdBound();
  324. }
  325. Pass::Status CCPPass::Process() {
  326. Initialize();
  327. // Process all entry point functions.
  328. ProcessFunction pfn = [this](Function* fp) { return PropagateConstants(fp); };
  329. bool modified = context()->ProcessReachableCallTree(pfn);
  330. return modified ? Pass::Status::SuccessWithChange
  331. : Pass::Status::SuccessWithoutChange;
  332. }
  333. } // namespace opt
  334. } // namespace spvtools