ccp_pass.cpp 12 KB

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