scalar_analysis_simplification.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538
  1. // Copyright (c) 2018 Google LLC.
  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 <functional>
  15. #include <map>
  16. #include <memory>
  17. #include <set>
  18. #include <utility>
  19. #include <vector>
  20. #include "source/opt/scalar_analysis.h"
  21. // Simplifies scalar analysis DAGs.
  22. //
  23. // 1. Given a node passed to SimplifyExpression we first simplify the graph by
  24. // calling SimplifyPolynomial. This groups like nodes following basic arithmetic
  25. // rules, so multiple adds of the same load instruction could be grouped into a
  26. // single multiply of that instruction. SimplifyPolynomial will traverse the DAG
  27. // and build up an accumulator buffer for each class of instruction it finds.
  28. // For example take the loop:
  29. // for (i=0, i<N; i++) { i+B+23+4+B+C; }
  30. // In this example the expression "i+B+23+4+B+C" has four classes of
  31. // instruction, induction variable i, the two value unknowns B and C, and the
  32. // constants. The accumulator buffer is then used to rebuild the graph using
  33. // the accumulation of each type. This example would then be folded into
  34. // i+2*B+C+27.
  35. //
  36. // This new graph contains a single add node (or if only one type found then
  37. // just that node) with each of the like terms (or multiplication node) as a
  38. // child.
  39. //
  40. // 2. FoldRecurrentAddExpressions is then called on this new DAG. This will take
  41. // RecurrentAddExpressions which are with respect to the same loop and fold them
  42. // into a single new RecurrentAddExpression with respect to that same loop. An
  43. // expression can have multiple RecurrentAddExpression's with respect to
  44. // different loops in the case of nested loops. These expressions cannot be
  45. // folded further. For example:
  46. //
  47. // for (i=0; i<N;i++) for(j=0,k=1; j<N;++j,++k)
  48. //
  49. // The 'j' and 'k' are RecurrentAddExpression with respect to the second loop
  50. // and 'i' to the first. If 'j' and 'k' are used in an expression together then
  51. // they will be folded into a new RecurrentAddExpression with respect to the
  52. // second loop in that expression.
  53. //
  54. //
  55. // 3. If the DAG now only contains a single RecurrentAddExpression we can now
  56. // perform a final optimization SimplifyRecurrentAddExpression. This will
  57. // transform the entire DAG into a RecurrentAddExpression. Additions to the
  58. // RecurrentAddExpression are added to the offset field and multiplications to
  59. // the coefficient.
  60. //
  61. namespace spvtools {
  62. namespace opt {
  63. // Implementation of the functions which are used to simplify the graph. Graphs
  64. // of unknowns, multiplies, additions, and constants can be turned into a linear
  65. // add node with each term as a child. For instance a large graph built from, X
  66. // + X*2 + Y - Y*3 + 4 - 1, would become a single add expression with the
  67. // children X*3, -Y*2, and the constant 3. Graphs containing a recurrent
  68. // expression will be simplified to represent the entire graph around a single
  69. // recurrent expression. So for an induction variable (i=0, i++) if you add 1 to
  70. // i in an expression we can rewrite the graph of that expression to be a single
  71. // recurrent expression of (i=1,i++).
  72. class SENodeSimplifyImpl {
  73. public:
  74. SENodeSimplifyImpl(ScalarEvolutionAnalysis* analysis,
  75. SENode* node_to_simplify)
  76. : analysis_(*analysis),
  77. node_(node_to_simplify),
  78. constant_accumulator_(0) {}
  79. // Return the result of the simplification.
  80. SENode* Simplify();
  81. private:
  82. // Recursively descend through the graph to build up the accumulator objects
  83. // which are used to flatten the graph. |child| is the node currently being
  84. // traversed and the |negation| flag is used to signify that this operation
  85. // was preceded by a unary negative operation and as such the result should be
  86. // negated.
  87. void GatherAccumulatorsFromChildNodes(SENode* new_node, SENode* child,
  88. bool negation);
  89. // Given a |multiply| node add to the accumulators for the term type within
  90. // the |multiply| expression. Will return true if the accumulators could be
  91. // calculated successfully. If the |multiply| is in any form other than
  92. // unknown*constant then we return false. |negation| signifies that the
  93. // operation was preceded by a unary negative.
  94. bool AccumulatorsFromMultiply(SENode* multiply, bool negation);
  95. SERecurrentNode* UpdateCoefficient(SERecurrentNode* recurrent,
  96. int64_t coefficient_update) const;
  97. // If the graph contains a recurrent expression, ie, an expression with the
  98. // loop iterations as a term in the expression, then the whole expression
  99. // can be rewritten to be a recurrent expression.
  100. SENode* SimplifyRecurrentAddExpression(SERecurrentNode* node);
  101. // Simplify the whole graph by linking like terms together in a single flat
  102. // add node. So X*2 + Y -Y + 3 +6 would become X*2 + 9. Where X and Y are a
  103. // ValueUnknown node (i.e, a load) or a recurrent expression.
  104. SENode* SimplifyPolynomial();
  105. // Each recurrent expression is an expression with respect to a specific loop.
  106. // If we have two different recurrent terms with respect to the same loop in a
  107. // single expression then we can fold those terms into a single new term.
  108. // For instance:
  109. //
  110. // induction i = 0, i++
  111. // temp = i*10
  112. // array[i+temp]
  113. //
  114. // We can fold the i + temp into a single expression. Rec(0,1) + Rec(0,10) can
  115. // become Rec(0,11).
  116. SENode* FoldRecurrentAddExpressions(SENode*);
  117. // We can eliminate recurrent expressions which have a coefficient of zero by
  118. // replacing them with their offset value. We are able to do this because a
  119. // recurrent expression represents the equation coefficient*iterations +
  120. // offset.
  121. SENode* EliminateZeroCoefficientRecurrents(SENode* node);
  122. // A reference the analysis which requested the simplification.
  123. ScalarEvolutionAnalysis& analysis_;
  124. // The node being simplified.
  125. SENode* node_;
  126. // An accumulator of the net result of all the constant operations performed
  127. // in a graph.
  128. int64_t constant_accumulator_;
  129. // An accumulator for each of the non constant terms in the graph.
  130. std::map<SENode*, int64_t> accumulators_;
  131. };
  132. // From a |multiply| build up the accumulator objects.
  133. bool SENodeSimplifyImpl::AccumulatorsFromMultiply(SENode* multiply,
  134. bool negation) {
  135. if (multiply->GetChildren().size() != 2 ||
  136. multiply->GetType() != SENode::Multiply)
  137. return false;
  138. SENode* operand_1 = multiply->GetChild(0);
  139. SENode* operand_2 = multiply->GetChild(1);
  140. SENode* value_unknown = nullptr;
  141. SENode* constant = nullptr;
  142. // Work out which operand is the unknown value.
  143. if (operand_1->GetType() == SENode::ValueUnknown ||
  144. operand_1->GetType() == SENode::RecurrentAddExpr)
  145. value_unknown = operand_1;
  146. else if (operand_2->GetType() == SENode::ValueUnknown ||
  147. operand_2->GetType() == SENode::RecurrentAddExpr)
  148. value_unknown = operand_2;
  149. // Work out which operand is the constant coefficient.
  150. if (operand_1->GetType() == SENode::Constant)
  151. constant = operand_1;
  152. else if (operand_2->GetType() == SENode::Constant)
  153. constant = operand_2;
  154. // If the expression is not a variable multiplied by a constant coefficient,
  155. // exit out.
  156. if (!(value_unknown && constant)) {
  157. return false;
  158. }
  159. int64_t sign = negation ? -1 : 1;
  160. auto iterator = accumulators_.find(value_unknown);
  161. int64_t new_value = constant->AsSEConstantNode()->FoldToSingleValue() * sign;
  162. // Add the result of the multiplication to the accumulators.
  163. if (iterator != accumulators_.end()) {
  164. (*iterator).second += new_value;
  165. } else {
  166. accumulators_.insert({value_unknown, new_value});
  167. }
  168. return true;
  169. }
  170. SENode* SENodeSimplifyImpl::Simplify() {
  171. // We only handle graphs with an addition, multiplication, or negation, at the
  172. // root.
  173. if (node_->GetType() != SENode::Add && node_->GetType() != SENode::Multiply &&
  174. node_->GetType() != SENode::Negative)
  175. return node_;
  176. SENode* simplified_polynomial = SimplifyPolynomial();
  177. SERecurrentNode* recurrent_expr = nullptr;
  178. node_ = simplified_polynomial;
  179. // Fold recurrent expressions which are with respect to the same loop into a
  180. // single recurrent expression.
  181. simplified_polynomial = FoldRecurrentAddExpressions(simplified_polynomial);
  182. simplified_polynomial =
  183. EliminateZeroCoefficientRecurrents(simplified_polynomial);
  184. // Traverse the immediate children of the new node to find the recurrent
  185. // expression. If there is more than one there is nothing further we can do.
  186. for (SENode* child : simplified_polynomial->GetChildren()) {
  187. if (child->GetType() == SENode::RecurrentAddExpr) {
  188. recurrent_expr = child->AsSERecurrentNode();
  189. }
  190. }
  191. // We need to count the number of unique recurrent expressions in the DAG to
  192. // ensure there is only one.
  193. for (auto child_iterator = simplified_polynomial->graph_begin();
  194. child_iterator != simplified_polynomial->graph_end(); ++child_iterator) {
  195. if (child_iterator->GetType() == SENode::RecurrentAddExpr &&
  196. recurrent_expr != child_iterator->AsSERecurrentNode()) {
  197. return simplified_polynomial;
  198. }
  199. }
  200. if (recurrent_expr) {
  201. return SimplifyRecurrentAddExpression(recurrent_expr);
  202. }
  203. return simplified_polynomial;
  204. }
  205. // Traverse the graph to build up the accumulator objects.
  206. void SENodeSimplifyImpl::GatherAccumulatorsFromChildNodes(SENode* new_node,
  207. SENode* child,
  208. bool negation) {
  209. int32_t sign = negation ? -1 : 1;
  210. if (child->GetType() == SENode::Constant) {
  211. // Collect all the constants and add them together.
  212. constant_accumulator_ +=
  213. child->AsSEConstantNode()->FoldToSingleValue() * sign;
  214. } else if (child->GetType() == SENode::ValueUnknown ||
  215. child->GetType() == SENode::RecurrentAddExpr) {
  216. // To rebuild the graph of X+X+X*2 into 4*X we count the occurrences of X
  217. // and create a new node of count*X after. X can either be a ValueUnknown or
  218. // a RecurrentAddExpr. The count for each X is stored in the accumulators_
  219. // map.
  220. auto iterator = accumulators_.find(child);
  221. // If we've encountered this term before add to the accumulator for it.
  222. if (iterator == accumulators_.end())
  223. accumulators_.insert({child, sign});
  224. else
  225. iterator->second += sign;
  226. } else if (child->GetType() == SENode::Multiply) {
  227. if (!AccumulatorsFromMultiply(child, negation)) {
  228. new_node->AddChild(child);
  229. }
  230. } else if (child->GetType() == SENode::Add) {
  231. for (SENode* next_child : *child) {
  232. GatherAccumulatorsFromChildNodes(new_node, next_child, negation);
  233. }
  234. } else if (child->GetType() == SENode::Negative) {
  235. SENode* negated_node = child->GetChild(0);
  236. GatherAccumulatorsFromChildNodes(new_node, negated_node, !negation);
  237. } else {
  238. // If we can't work out how to fold the expression just add it back into
  239. // the graph.
  240. new_node->AddChild(child);
  241. }
  242. }
  243. SERecurrentNode* SENodeSimplifyImpl::UpdateCoefficient(
  244. SERecurrentNode* recurrent, int64_t coefficient_update) const {
  245. std::unique_ptr<SERecurrentNode> new_recurrent_node{new SERecurrentNode(
  246. recurrent->GetParentAnalysis(), recurrent->GetLoop())};
  247. SENode* new_coefficient = analysis_.CreateMultiplyNode(
  248. recurrent->GetCoefficient(),
  249. analysis_.CreateConstant(coefficient_update));
  250. // See if the node can be simplified.
  251. SENode* simplified = analysis_.SimplifyExpression(new_coefficient);
  252. if (simplified->GetType() != SENode::CanNotCompute)
  253. new_coefficient = simplified;
  254. if (coefficient_update < 0) {
  255. new_recurrent_node->AddOffset(
  256. analysis_.CreateNegation(recurrent->GetOffset()));
  257. } else {
  258. new_recurrent_node->AddOffset(recurrent->GetOffset());
  259. }
  260. new_recurrent_node->AddCoefficient(new_coefficient);
  261. return analysis_.GetCachedOrAdd(std::move(new_recurrent_node))
  262. ->AsSERecurrentNode();
  263. }
  264. // Simplify all the terms in the polynomial function.
  265. SENode* SENodeSimplifyImpl::SimplifyPolynomial() {
  266. std::unique_ptr<SENode> new_add{new SEAddNode(node_->GetParentAnalysis())};
  267. // Traverse the graph and gather the accumulators from it.
  268. GatherAccumulatorsFromChildNodes(new_add.get(), node_, false);
  269. // Fold all the constants into a single constant node.
  270. if (constant_accumulator_ != 0) {
  271. new_add->AddChild(analysis_.CreateConstant(constant_accumulator_));
  272. }
  273. for (auto& pair : accumulators_) {
  274. SENode* term = pair.first;
  275. int64_t count = pair.second;
  276. // We can eliminate the term completely.
  277. if (count == 0) continue;
  278. if (count == 1) {
  279. new_add->AddChild(term);
  280. } else if (count == -1 && term->GetType() != SENode::RecurrentAddExpr) {
  281. // If the count is -1 we can just add a negative version of that node,
  282. // unless it is a recurrent expression as we would rather the negative
  283. // goes on the recurrent expressions children. This makes it easier to
  284. // work with in other places.
  285. new_add->AddChild(analysis_.CreateNegation(term));
  286. } else {
  287. // Output value unknown terms as count*term and output recurrent
  288. // expression terms as rec(offset, coefficient + count) offset and
  289. // coefficient are the same as in the original expression.
  290. if (term->GetType() == SENode::ValueUnknown) {
  291. SENode* count_as_constant = analysis_.CreateConstant(count);
  292. new_add->AddChild(
  293. analysis_.CreateMultiplyNode(count_as_constant, term));
  294. } else {
  295. assert(term->GetType() == SENode::RecurrentAddExpr &&
  296. "We only handle value unknowns or recurrent expressions");
  297. // Create a new recurrent expression by adding the count to the
  298. // coefficient of the old one.
  299. new_add->AddChild(UpdateCoefficient(term->AsSERecurrentNode(), count));
  300. }
  301. }
  302. }
  303. // If there is only one term in the addition left just return that term.
  304. if (new_add->GetChildren().size() == 1) {
  305. return new_add->GetChild(0);
  306. }
  307. // If there are no terms left in the addition just return 0.
  308. if (new_add->GetChildren().size() == 0) {
  309. return analysis_.CreateConstant(0);
  310. }
  311. return analysis_.GetCachedOrAdd(std::move(new_add));
  312. }
  313. SENode* SENodeSimplifyImpl::FoldRecurrentAddExpressions(SENode* root) {
  314. std::unique_ptr<SEAddNode> new_node{new SEAddNode(&analysis_)};
  315. // A mapping of loops to the list of recurrent expressions which are with
  316. // respect to those loops.
  317. std::map<const Loop*, std::vector<std::pair<SERecurrentNode*, bool>>>
  318. loops_to_recurrent{};
  319. bool has_multiple_same_loop_recurrent_terms = false;
  320. for (SENode* child : *root) {
  321. bool negation = false;
  322. if (child->GetType() == SENode::Negative) {
  323. child = child->GetChild(0);
  324. negation = true;
  325. }
  326. if (child->GetType() == SENode::RecurrentAddExpr) {
  327. const Loop* loop = child->AsSERecurrentNode()->GetLoop();
  328. SERecurrentNode* rec = child->AsSERecurrentNode();
  329. if (loops_to_recurrent.find(loop) == loops_to_recurrent.end()) {
  330. loops_to_recurrent[loop] = {std::make_pair(rec, negation)};
  331. } else {
  332. loops_to_recurrent[loop].push_back(std::make_pair(rec, negation));
  333. has_multiple_same_loop_recurrent_terms = true;
  334. }
  335. } else {
  336. new_node->AddChild(child);
  337. }
  338. }
  339. if (!has_multiple_same_loop_recurrent_terms) return root;
  340. for (auto pair : loops_to_recurrent) {
  341. std::vector<std::pair<SERecurrentNode*, bool>>& recurrent_expressions =
  342. pair.second;
  343. const Loop* loop = pair.first;
  344. std::unique_ptr<SENode> new_coefficient{new SEAddNode(&analysis_)};
  345. std::unique_ptr<SENode> new_offset{new SEAddNode(&analysis_)};
  346. for (auto node_pair : recurrent_expressions) {
  347. SERecurrentNode* node = node_pair.first;
  348. bool negative = node_pair.second;
  349. if (!negative) {
  350. new_coefficient->AddChild(node->GetCoefficient());
  351. new_offset->AddChild(node->GetOffset());
  352. } else {
  353. new_coefficient->AddChild(
  354. analysis_.CreateNegation(node->GetCoefficient()));
  355. new_offset->AddChild(analysis_.CreateNegation(node->GetOffset()));
  356. }
  357. }
  358. std::unique_ptr<SERecurrentNode> new_recurrent{
  359. new SERecurrentNode(&analysis_, loop)};
  360. SENode* new_coefficient_simplified =
  361. analysis_.SimplifyExpression(new_coefficient.get());
  362. SENode* new_offset_simplified =
  363. analysis_.SimplifyExpression(new_offset.get());
  364. if (new_coefficient_simplified->GetType() == SENode::Constant &&
  365. new_coefficient_simplified->AsSEConstantNode()->FoldToSingleValue() ==
  366. 0) {
  367. return new_offset_simplified;
  368. }
  369. new_recurrent->AddCoefficient(new_coefficient_simplified);
  370. new_recurrent->AddOffset(new_offset_simplified);
  371. new_node->AddChild(analysis_.GetCachedOrAdd(std::move(new_recurrent)));
  372. }
  373. // If we only have one child in the add just return that.
  374. if (new_node->GetChildren().size() == 1) {
  375. return new_node->GetChild(0);
  376. }
  377. return analysis_.GetCachedOrAdd(std::move(new_node));
  378. }
  379. SENode* SENodeSimplifyImpl::EliminateZeroCoefficientRecurrents(SENode* node) {
  380. if (node->GetType() != SENode::Add) return node;
  381. bool has_change = false;
  382. std::vector<SENode*> new_children{};
  383. for (SENode* child : *node) {
  384. if (child->GetType() == SENode::RecurrentAddExpr) {
  385. SENode* coefficient = child->AsSERecurrentNode()->GetCoefficient();
  386. // If coefficient is zero then we can eliminate the recurrent expression
  387. // entirely and just return the offset as the recurrent expression is
  388. // representing the equation coefficient*iterations + offset.
  389. if (coefficient->GetType() == SENode::Constant &&
  390. coefficient->AsSEConstantNode()->FoldToSingleValue() == 0) {
  391. new_children.push_back(child->AsSERecurrentNode()->GetOffset());
  392. has_change = true;
  393. } else {
  394. new_children.push_back(child);
  395. }
  396. } else {
  397. new_children.push_back(child);
  398. }
  399. }
  400. if (!has_change) return node;
  401. std::unique_ptr<SENode> new_add{new SEAddNode(node_->GetParentAnalysis())};
  402. for (SENode* child : new_children) {
  403. new_add->AddChild(child);
  404. }
  405. return analysis_.GetCachedOrAdd(std::move(new_add));
  406. }
  407. SENode* SENodeSimplifyImpl::SimplifyRecurrentAddExpression(
  408. SERecurrentNode* recurrent_expr) {
  409. const std::vector<SENode*>& children = node_->GetChildren();
  410. std::unique_ptr<SERecurrentNode> recurrent_node{new SERecurrentNode(
  411. recurrent_expr->GetParentAnalysis(), recurrent_expr->GetLoop())};
  412. // Create and simplify the new offset node.
  413. std::unique_ptr<SENode> new_offset{
  414. new SEAddNode(recurrent_expr->GetParentAnalysis())};
  415. new_offset->AddChild(recurrent_expr->GetOffset());
  416. for (SENode* child : children) {
  417. if (child->GetType() != SENode::RecurrentAddExpr) {
  418. new_offset->AddChild(child);
  419. }
  420. }
  421. // Simplify the new offset.
  422. SENode* simplified_child = analysis_.SimplifyExpression(new_offset.get());
  423. // If the child can be simplified, add the simplified form otherwise, add it
  424. // via the usual caching mechanism.
  425. if (simplified_child->GetType() != SENode::CanNotCompute) {
  426. recurrent_node->AddOffset(simplified_child);
  427. } else {
  428. recurrent_expr->AddOffset(analysis_.GetCachedOrAdd(std::move(new_offset)));
  429. }
  430. recurrent_node->AddCoefficient(recurrent_expr->GetCoefficient());
  431. return analysis_.GetCachedOrAdd(std::move(recurrent_node));
  432. }
  433. /*
  434. * Scalar Analysis simplification public methods.
  435. */
  436. SENode* ScalarEvolutionAnalysis::SimplifyExpression(SENode* node) {
  437. SENodeSimplifyImpl impl{this, node};
  438. return impl.Simplify();
  439. }
  440. } // namespace opt
  441. } // namespace spvtools