Coverage Report

Created: 2020-03-31 06:27

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/StaticAnalyzer/Core/LoopUnrolling.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- LoopUnrolling.cpp - Unroll loops -----------------------*- C++ -*-===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
///
9
/// This file contains functions which are used to decide if a loop worth to be
10
/// unrolled. Moreover, these functions manages the stack of loop which is
11
/// tracked by the ProgramState.
12
///
13
//===----------------------------------------------------------------------===//
14
15
#include "clang/ASTMatchers/ASTMatchers.h"
16
#include "clang/ASTMatchers/ASTMatchFinder.h"
17
#include "clang/StaticAnalyzer/Core/PathSensitive/CallEvent.h"
18
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
19
#include "clang/StaticAnalyzer/Core/PathSensitive/LoopUnrolling.h"
20
21
using namespace clang;
22
using namespace ento;
23
using namespace clang::ast_matchers;
24
25
static const int MAXIMUM_STEP_UNROLLED = 128;
26
27
struct LoopState {
28
private:
29
  enum Kind { Normal, Unrolled } K;
30
  const Stmt *LoopStmt;
31
  const LocationContext *LCtx;
32
  unsigned maxStep;
33
  LoopState(Kind InK, const Stmt *S, const LocationContext *L, unsigned N)
34
185
      : K(InK), LoopStmt(S), LCtx(L), maxStep(N) {}
35
36
public:
37
  static LoopState getNormal(const Stmt *S, const LocationContext *L,
38
85
                             unsigned N) {
39
85
    return LoopState(Normal, S, L, N);
40
85
  }
41
  static LoopState getUnrolled(const Stmt *S, const LocationContext *L,
42
100
                               unsigned N) {
43
100
    return LoopState(Unrolled, S, L, N);
44
100
  }
45
7.20k
  bool isUnrolled() const { return K == Unrolled; }
46
64
  unsigned getMaxStep() const { return maxStep; }
47
1.88k
  const Stmt *getLoopStmt() const { return LoopStmt; }
48
1.67k
  const LocationContext *getLocationContext() const { return LCtx; }
49
0
  bool operator==(const LoopState &X) const {
50
0
    return K == X.K && LoopStmt == X.LoopStmt;
51
0
  }
52
231
  void Profile(llvm::FoldingSetNodeID &ID) const {
53
231
    ID.AddInteger(K);
54
231
    ID.AddPointer(LoopStmt);
55
231
    ID.AddPointer(LCtx);
56
231
    ID.AddInteger(maxStep);
57
231
  }
58
};
59
60
// The tracked stack of loops. The stack indicates that which loops the
61
// simulated element contained by. The loops are marked depending if we decided
62
// to unroll them.
63
// TODO: The loop stack should not need to be in the program state since it is
64
// lexical in nature. Instead, the stack of loops should be tracked in the
65
// LocationContext.
66
REGISTER_LIST_WITH_PROGRAMSTATE(LoopStack, LoopState)
67
68
namespace clang {
69
namespace ento {
70
71
2.15k
static bool isLoopStmt(const Stmt *S) {
72
2.15k
  return S && (isa<ForStmt>(S) || 
isa<WhileStmt>(S)160
||
isa<DoStmt>(S)160
);
73
2.15k
}
74
75
142
ProgramStateRef processLoopEnd(const Stmt *LoopStmt, ProgramStateRef State) {
76
142
  auto LS = State->get<LoopStack>();
77
142
  if (!LS.isEmpty() && LS.getHead().getLoopStmt() == LoopStmt)
78
142
    State = State->set<LoopStack>(LS.getTail());
79
142
  return State;
80
142
}
81
82
161
static internal::Matcher<Stmt> simpleCondition(StringRef BindName) {
83
161
  return binaryOperator(anyOf(hasOperatorName("<"), hasOperatorName(">"),
84
161
                              hasOperatorName("<="), hasOperatorName(">="),
85
161
                              hasOperatorName("!=")),
86
161
                        hasEitherOperand(ignoringParenImpCasts(declRefExpr(
87
161
                            to(varDecl(hasType(isInteger())).bind(BindName))))),
88
161
                        hasEitherOperand(ignoringParenImpCasts(
89
161
                            integerLiteral().bind("boundNum"))))
90
161
      .bind("conditionOperator");
91
161
}
92
93
static internal::Matcher<Stmt>
94
161
changeIntBoundNode(internal::Matcher<Decl> VarNodeMatcher) {
95
161
  return anyOf(
96
161
      unaryOperator(anyOf(hasOperatorName("--"), hasOperatorName("++")),
97
161
                    hasUnaryOperand(ignoringParenImpCasts(
98
161
                        declRefExpr(to(varDecl(VarNodeMatcher)))))),
99
161
      binaryOperator(isAssignmentOperator(),
100
161
                     hasLHS(ignoringParenImpCasts(
101
161
                         declRefExpr(to(varDecl(VarNodeMatcher)))))));
102
161
}
103
104
static internal::Matcher<Stmt>
105
16.1k
callByRef(internal::Matcher<Decl> VarNodeMatcher) {
106
16.1k
  return callExpr(forEachArgumentWithParam(
107
16.1k
      declRefExpr(to(varDecl(VarNodeMatcher))),
108
16.1k
      parmVarDecl(hasType(references(qualType(unless(isConstQualified())))))));
109
16.1k
}
110
111
static internal::Matcher<Stmt>
112
16.1k
assignedToRef(internal::Matcher<Decl> VarNodeMatcher) {
113
16.1k
  return declStmt(hasDescendant(varDecl(
114
16.1k
      allOf(hasType(referenceType()),
115
16.1k
            hasInitializer(anyOf(
116
16.1k
                initListExpr(has(declRefExpr(to(varDecl(VarNodeMatcher))))),
117
16.1k
                declRefExpr(to(varDecl(VarNodeMatcher)))))))));
118
16.1k
}
119
120
static internal::Matcher<Stmt>
121
16.1k
getAddrTo(internal::Matcher<Decl> VarNodeMatcher) {
122
16.1k
  return unaryOperator(
123
16.1k
      hasOperatorName("&"),
124
16.1k
      hasUnaryOperand(declRefExpr(hasDeclaration(VarNodeMatcher))));
125
16.1k
}
126
127
161
static internal::Matcher<Stmt> hasSuspiciousStmt(StringRef NodeName) {
128
161
  return hasDescendant(stmt(
129
161
      anyOf(gotoStmt(), switchStmt(), returnStmt(),
130
161
            // Escaping and not known mutation of the loop counter is handled
131
161
            // by exclusion of assigning and address-of operators and
132
161
            // pass-by-ref function calls on the loop counter from the body.
133
161
            changeIntBoundNode(equalsBoundNode(std::string(NodeName))),
134
161
            callByRef(equalsBoundNode(std::string(NodeName))),
135
161
            getAddrTo(equalsBoundNode(std::string(NodeName))),
136
161
            assignedToRef(equalsBoundNode(std::string(NodeName))))));
137
161
}
138
139
161
static internal::Matcher<Stmt> forLoopMatcher() {
140
161
  return forStmt(
141
161
             hasCondition(simpleCondition("initVarName")),
142
161
             // Initialization should match the form: 'int i = 6' or 'i = 42'.
143
161
             hasLoopInit(
144
161
                 anyOf(declStmt(hasSingleDecl(
145
161
                           varDecl(allOf(hasInitializer(ignoringParenImpCasts(
146
161
                                             integerLiteral().bind("initNum"))),
147
161
                                         equalsBoundNode("initVarName"))))),
148
161
                       binaryOperator(hasLHS(declRefExpr(to(varDecl(
149
161
                                          equalsBoundNode("initVarName"))))),
150
161
                                      hasRHS(ignoringParenImpCasts(
151
161
                                          integerLiteral().bind("initNum")))))),
152
161
             // Incrementation should be a simple increment or decrement
153
161
             // operator call.
154
161
             hasIncrement(unaryOperator(
155
161
                 anyOf(hasOperatorName("++"), hasOperatorName("--")),
156
161
                 hasUnaryOperand(declRefExpr(
157
161
                     to(varDecl(allOf(equalsBoundNode("initVarName"),
158
161
                                      hasType(isInteger())))))))),
159
161
             unless(hasBody(hasSuspiciousStmt("initVarName")))).bind("forLoop");
160
161
}
161
162
112
static bool isPossiblyEscaped(const VarDecl *VD, ExplodedNode *N) {
163
112
  // Global variables assumed as escaped variables.
164
112
  if (VD->hasGlobalStorage())
165
0
    return true;
166
112
167
18.4k
  
while (112
!N->pred_empty()) {
168
18.4k
    // FIXME: getStmtForDiagnostics() does nasty things in order to provide
169
18.4k
    // a valid statement for body farms, do we need this behavior here?
170
18.4k
    const Stmt *S = N->getStmtForDiagnostics();
171
18.4k
    if (!S) {
172
2.40k
      N = N->getFirstPred();
173
2.40k
      continue;
174
2.40k
    }
175
16.0k
176
16.0k
    if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
177
180
      for (const Decl *D : DS->decls()) {
178
180
        // Once we reach the declaration of the VD we can return.
179
180
        if (D->getCanonicalDecl() == VD)
180
106
          return false;
181
180
      }
182
180
    }
183
16.0k
    // Check the usage of the pass-by-ref function calls and adress-of operator
184
16.0k
    // on VD and reference initialized by VD.
185
16.0k
    ASTContext &ASTCtx =
186
15.9k
        N->getLocationContext()->getAnalysisDeclContext()->getASTContext();
187
15.9k
    auto Match =
188
15.9k
        match(stmt(anyOf(callByRef(equalsNode(VD)), getAddrTo(equalsNode(VD)),
189
15.9k
                         assignedToRef(equalsNode(VD)))),
190
15.9k
              *S, ASTCtx);
191
15.9k
    if (!Match.empty())
192
6
      return true;
193
15.9k
194
15.9k
    N = N->getFirstPred();
195
15.9k
  }
196
112
  
llvm_unreachable0
("Reached root without finding the declaration of VD");
197
112
}
198
199
bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx,
200
161
                            ExplodedNode *Pred, unsigned &maxStep) {
201
161
202
161
  if (!isLoopStmt(LoopStmt))
203
0
    return false;
204
161
205
161
  // TODO: Match the cases where the bound is not a concrete literal but an
206
161
  // integer with known value
207
161
  auto Matches = match(forLoopMatcher(), *LoopStmt, ASTCtx);
208
161
  if (Matches.empty())
209
49
    return false;
210
112
211
112
  auto CounterVar = Matches[0].getNodeAs<VarDecl>("initVarName");
212
112
  llvm::APInt BoundNum =
213
112
      Matches[0].getNodeAs<IntegerLiteral>("boundNum")->getValue();
214
112
  llvm::APInt InitNum =
215
112
      Matches[0].getNodeAs<IntegerLiteral>("initNum")->getValue();
216
112
  auto CondOp = Matches[0].getNodeAs<BinaryOperator>("conditionOperator");
217
112
  if (InitNum.getBitWidth() != BoundNum.getBitWidth()) {
218
2
    InitNum = InitNum.zextOrSelf(BoundNum.getBitWidth());
219
2
    BoundNum = BoundNum.zextOrSelf(InitNum.getBitWidth());
220
2
  }
221
112
222
112
  if (CondOp->getOpcode() == BO_GE || CondOp->getOpcode() == BO_LE)
223
4
    maxStep = (BoundNum - InitNum + 1).abs().getZExtValue();
224
108
  else
225
108
    maxStep = (BoundNum - InitNum).abs().getZExtValue();
226
112
227
112
  // Check if the counter of the loop is not escaped before.
228
112
  return !isPossiblyEscaped(CounterVar->getCanonicalDecl(), Pred);
229
112
}
230
231
1.34k
bool madeNewBranch(ExplodedNode *N, const Stmt *LoopStmt) {
232
1.34k
  const Stmt *S = nullptr;
233
56.3k
  while (!N->pred_empty()) {
234
56.3k
    if (N->succ_size() > 1)
235
24
      return true;
236
56.2k
237
56.2k
    ProgramPoint P = N->getLocation();
238
56.2k
    if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>())
239
5.70k
      S = BE->getBlock()->getTerminatorStmt();
240
56.2k
241
56.2k
    if (S == LoopStmt)
242
1.31k
      return false;
243
54.9k
244
54.9k
    N = N->getFirstPred();
245
54.9k
  }
246
1.34k
247
1.34k
  
llvm_unreachable0
("Reached root without encountering the previous step");
248
1.34k
}
249
250
// updateLoopStack is called on every basic block, therefore it needs to be fast
251
ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx,
252
1.99k
                                ExplodedNode *Pred, unsigned maxVisitOnPath) {
253
1.99k
  auto State = Pred->getState();
254
1.99k
  auto LCtx = Pred->getLocationContext();
255
1.99k
256
1.99k
  if (!isLoopStmt(LoopStmt))
257
160
    return State;
258
1.83k
259
1.83k
  auto LS = State->get<LoopStack>();
260
1.83k
  if (!LS.isEmpty() && 
LoopStmt == LS.getHead().getLoopStmt()1.74k
&&
261
1.83k
      
LCtx == LS.getHead().getLocationContext()1.67k
) {
262
1.67k
    if (LS.getHead().isUnrolled() && 
madeNewBranch(Pred, LoopStmt)1.34k
) {
263
24
      State = State->set<LoopStack>(LS.getTail());
264
24
      State = State->add<LoopStack>(
265
24
          LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
266
24
    }
267
1.67k
    return State;
268
1.67k
  }
269
161
  unsigned maxStep;
270
161
  if (!shouldCompletelyUnroll(LoopStmt, ASTCtx, Pred, maxStep)) {
271
55
    State = State->add<LoopStack>(
272
55
        LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
273
55
    return State;
274
55
  }
275
106
276
106
  unsigned outerStep = (LS.isEmpty() ? 
142
:
LS.getHead().getMaxStep()64
);
277
106
278
106
  unsigned innerMaxStep = maxStep * outerStep;
279
106
  if (innerMaxStep > MAXIMUM_STEP_UNROLLED)
280
6
    State = State->add<LoopStack>(
281
6
        LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
282
100
  else
283
100
    State = State->add<LoopStack>(
284
100
        LoopState::getUnrolled(LoopStmt, LCtx, innerMaxStep));
285
106
  return State;
286
106
}
287
288
5.62k
bool isUnrolledState(ProgramStateRef State) {
289
5.62k
  auto LS = State->get<LoopStack>();
290
5.62k
  if (LS.isEmpty() || 
!LS.getHead().isUnrolled()5.53k
)
291
1.33k
    return false;
292
4.29k
  return true;
293
4.29k
}
294
}
295
}