• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
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  */
15 #ifndef COMPILER_OPTIMIZER_ANALYSIS_COUNTABLE_LOOP_PARSER_H
16 #define COMPILER_OPTIMIZER_ANALYSIS_COUNTABLE_LOOP_PARSER_H
17 
18 #include "optimizer/ir/inst.h"
19 
20 namespace ark::compiler {
21 class Loop;
22 
23 /**
24  * Example of code
25  *  ---------------
26  * for (init(a); if_imm(compare(a,test)); update(a)) {...}
27  */
28 struct CountableLoopInfo {
29     Inst *ifImm;
30     Inst *init;
31     Inst *test;
32     Inst *update;
33     Inst *index;
34     uint64_t constStep;
35     ConditionCode normalizedCc;  // cc between `update` and `test`
36     bool isInc;
37 };
38 
39 /// Helper class to check if loop is countable and to get its parameters
40 class CountableLoopParser {
41 public:
CountableLoopParser(const Loop & loop)42     explicit CountableLoopParser(const Loop &loop) : loop_(loop) {}
43 
44     NO_MOVE_SEMANTIC(CountableLoopParser);
45     NO_COPY_SEMANTIC(CountableLoopParser);
46     ~CountableLoopParser() = default;
47 
48     std::optional<CountableLoopInfo> Parse();
49     bool ParseLoopExit();
50     static bool HasPreHeaderCompare(Loop *loop, const CountableLoopInfo &loopInfo);
51     static std::optional<uint64_t> GetLoopIterations(const CountableLoopInfo &loopInfo);
52 
53 private:
54     bool IsInstIncOrDec(Inst *inst);
55     bool SetUpdateAndTestInputs();
56     void SetIndexAndConstStep();
57     void SetNormalizedConditionCode();
58     bool IsConditionCodeAcceptable();
59     BasicBlock *FindLoopExitBlock();
60     bool CheckParsingLoopCorrectness();
61     bool TryProcessBackEdge();
62 
63 protected:
64     const Loop &loop_;               // NOLINT(misc-non-private-member-variables-in-classes)
65     CountableLoopInfo loopInfo_ {};  // NOLINT(misc-non-private-member-variables-in-classes)
66     bool isHeadLoopExit_ = false;    // NOLINT(misc-non-private-member-variables-in-classes)
67 };
68 }  // namespace ark::compiler
69 
70 #endif  // COMPILER_OPTIMIZER_ANALYSIS_COUNTABLE_LOOP_PARSER_H
71