Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/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
188
      : K(InK), LoopStmt(S), LCtx(L), maxStep(N) {}
35
36
public:
37
  static LoopState getNormal(const Stmt *S, const LocationContext *L,
38
88
                             unsigned N) {
39
88
    return LoopState(Normal, S, L, N);
40
88
  }
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.19k
  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
247
  void Profile(llvm::FoldingSetNodeID &ID) const {
53
247
    ID.AddInteger(K);
54
247
    ID.AddPointer(LoopStmt);
55
247
    ID.AddPointer(LCtx);
56
247
    ID.AddInteger(maxStep);
57
247
  }
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
141
ProgramStateRef processLoopEnd(const Stmt *LoopStmt, ProgramStateRef State) {
76
141
  auto LS = State->get<LoopStack>();
77
141
  if (!LS.isEmpty() && LS.getHead().getLoopStmt() == LoopStmt)
78
141
    State = State->set<LoopStack>(LS.getTail());
79
141
  return State;
80
141
}
81
82
164
static internal::Matcher<Stmt> simpleCondition(StringRef BindName) {
83
164
  return binaryOperator(anyOf(hasOperatorName("<"), hasOperatorName(">"),
84
164
                              hasOperatorName("<="), hasOperatorName(">="),
85
164
                              hasOperatorName("!=")),
86
164
                        hasEitherOperand(ignoringParenImpCasts(declRefExpr(
87
164
                            to(varDecl(hasType(isInteger())).bind(BindName))))),
88
164
                        hasEitherOperand(ignoringParenImpCasts(
89
164
                            integerLiteral().bind("boundNum"))))
90
164
      .bind("conditionOperator");
91
164
}
92
93
static internal::Matcher<Stmt>
94
164
changeIntBoundNode(internal::Matcher<Decl> VarNodeMatcher) {
95
164
  return anyOf(
96
164
      unaryOperator(anyOf(hasOperatorName("--"), hasOperatorName("++")),
97
164
                    hasUnaryOperand(ignoringParenImpCasts(
98
164
                        declRefExpr(to(varDecl(VarNodeMatcher)))))),
99
164
      binaryOperator(isAssignmentOperator(),
100
164
                     hasLHS(ignoringParenImpCasts(
101
164
                         declRefExpr(to(varDecl(VarNodeMatcher)))))));
102
164
}
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
164
static internal::Matcher<Stmt> hasSuspiciousStmt(StringRef NodeName) {
128
164
  return hasDescendant(stmt(
129
164
      anyOf(gotoStmt(), switchStmt(), returnStmt(),
130
164
            // Escaping and not known mutation of the loop counter is handled
131
164
            // by exclusion of assigning and address-of operators and
132
164
            // pass-by-ref function calls on the loop counter from the body.
133
164
            changeIntBoundNode(equalsBoundNode(NodeName)),
134
164
            callByRef(equalsBoundNode(NodeName)),
135
164
            getAddrTo(equalsBoundNode(NodeName)),
136
164
            assignedToRef(equalsBoundNode(NodeName)))));
137
164
}
138
139
164
static internal::Matcher<Stmt> forLoopMatcher() {
140
164
  return forStmt(
141
164
             hasCondition(simpleCondition("initVarName")),
142
164
             // Initialization should match the form: 'int i = 6' or 'i = 42'.
143
164
             hasLoopInit(
144
164
                 anyOf(declStmt(hasSingleDecl(
145
164
                           varDecl(allOf(hasInitializer(ignoringParenImpCasts(
146
164
                                             integerLiteral().bind("initNum"))),
147
164
                                         equalsBoundNode("initVarName"))))),
148
164
                       binaryOperator(hasLHS(declRefExpr(to(varDecl(
149
164
                                          equalsBoundNode("initVarName"))))),
150
164
                                      hasRHS(ignoringParenImpCasts(
151
164
                                          integerLiteral().bind("initNum")))))),
152
164
             // Incrementation should be a simple increment or decrement
153
164
             // operator call.
154
164
             hasIncrement(unaryOperator(
155
164
                 anyOf(hasOperatorName("++"), hasOperatorName("--")),
156
164
                 hasUnaryOperand(declRefExpr(
157
164
                     to(varDecl(allOf(equalsBoundNode("initVarName"),
158
164
                                      hasType(isInteger())))))))),
159
164
             unless(hasBody(hasSuspiciousStmt("initVarName")))).bind("forLoop");
160
164
}
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
    const Stmt *S = PathDiagnosticLocation::getStmt(N);
169
18.4k
    if (!S) {
170
2.40k
      N = N->getFirstPred();
171
2.40k
      continue;
172
2.40k
    }
173
16.0k
174
16.0k
    if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
175
180
      for (const Decl *D : DS->decls()) {
176
180
        // Once we reach the declaration of the VD we can return.
177
180
        if (D->getCanonicalDecl() == VD)
178
106
          return false;
179
180
      }
180
180
    }
181
16.0k
    // Check the usage of the pass-by-ref function calls and adress-of operator
182
16.0k
    // on VD and reference initialized by VD.
183
16.0k
    ASTContext &ASTCtx =
184
15.9k
        N->getLocationContext()->getAnalysisDeclContext()->getASTContext();
185
15.9k
    auto Match =
186
15.9k
        match(stmt(anyOf(callByRef(equalsNode(VD)), getAddrTo(equalsNode(VD)),
187
15.9k
                         assignedToRef(equalsNode(VD)))),
188
15.9k
              *S, ASTCtx);
189
15.9k
    if (!Match.empty())
190
6
      return true;
191
15.9k
192
15.9k
    N = N->getFirstPred();
193
15.9k
  }
194
112
  
llvm_unreachable0
("Reached root without finding the declaration of VD");
195
112
}
196
197
bool shouldCompletelyUnroll(const Stmt *LoopStmt, ASTContext &ASTCtx,
198
164
                            ExplodedNode *Pred, unsigned &maxStep) {
199
164
200
164
  if (!isLoopStmt(LoopStmt))
201
0
    return false;
202
164
203
164
  // TODO: Match the cases where the bound is not a concrete literal but an
204
164
  // integer with known value
205
164
  auto Matches = match(forLoopMatcher(), *LoopStmt, ASTCtx);
206
164
  if (Matches.empty())
207
52
    return false;
208
112
209
112
  auto CounterVar = Matches[0].getNodeAs<VarDecl>("initVarName");
210
112
  llvm::APInt BoundNum =
211
112
      Matches[0].getNodeAs<IntegerLiteral>("boundNum")->getValue();
212
112
  llvm::APInt InitNum =
213
112
      Matches[0].getNodeAs<IntegerLiteral>("initNum")->getValue();
214
112
  auto CondOp = Matches[0].getNodeAs<BinaryOperator>("conditionOperator");
215
112
  if (InitNum.getBitWidth() != BoundNum.getBitWidth()) {
216
2
    InitNum = InitNum.zextOrSelf(BoundNum.getBitWidth());
217
2
    BoundNum = BoundNum.zextOrSelf(InitNum.getBitWidth());
218
2
  }
219
112
220
112
  if (CondOp->getOpcode() == BO_GE || CondOp->getOpcode() == BO_LE)
221
4
    maxStep = (BoundNum - InitNum + 1).abs().getZExtValue();
222
108
  else
223
108
    maxStep = (BoundNum - InitNum).abs().getZExtValue();
224
112
225
112
  // Check if the counter of the loop is not escaped before.
226
112
  return !isPossiblyEscaped(CounterVar->getCanonicalDecl(), Pred);
227
112
}
228
229
1.34k
bool madeNewBranch(ExplodedNode *N, const Stmt *LoopStmt) {
230
1.34k
  const Stmt *S = nullptr;
231
56.3k
  while (!N->pred_empty()) {
232
56.3k
    if (N->succ_size() > 1)
233
24
      return true;
234
56.2k
235
56.2k
    ProgramPoint P = N->getLocation();
236
56.2k
    if (Optional<BlockEntrance> BE = P.getAs<BlockEntrance>())
237
5.70k
      S = BE->getBlock()->getTerminatorStmt();
238
56.2k
239
56.2k
    if (S == LoopStmt)
240
1.31k
      return false;
241
54.9k
242
54.9k
    N = N->getFirstPred();
243
54.9k
  }
244
1.34k
245
1.34k
  
llvm_unreachable0
("Reached root without encountering the previous step");
246
1.34k
}
247
248
// updateLoopStack is called on every basic block, therefore it needs to be fast
249
ProgramStateRef updateLoopStack(const Stmt *LoopStmt, ASTContext &ASTCtx,
250
1.98k
                                ExplodedNode *Pred, unsigned maxVisitOnPath) {
251
1.98k
  auto State = Pred->getState();
252
1.98k
  auto LCtx = Pred->getLocationContext();
253
1.98k
254
1.98k
  if (!isLoopStmt(LoopStmt))
255
160
    return State;
256
1.82k
257
1.82k
  auto LS = State->get<LoopStack>();
258
1.82k
  if (!LS.isEmpty() && 
LoopStmt == LS.getHead().getLoopStmt()1.74k
&&
259
1.82k
      
LCtx == LS.getHead().getLocationContext()1.67k
) {
260
1.66k
    if (LS.getHead().isUnrolled() && 
madeNewBranch(Pred, LoopStmt)1.34k
) {
261
24
      State = State->set<LoopStack>(LS.getTail());
262
24
      State = State->add<LoopStack>(
263
24
          LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
264
24
    }
265
1.66k
    return State;
266
1.66k
  }
267
164
  unsigned maxStep;
268
164
  if (!shouldCompletelyUnroll(LoopStmt, ASTCtx, Pred, maxStep)) {
269
58
    State = State->add<LoopStack>(
270
58
        LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
271
58
    return State;
272
58
  }
273
106
274
106
  unsigned outerStep = (LS.isEmpty() ? 
142
:
LS.getHead().getMaxStep()64
);
275
106
276
106
  unsigned innerMaxStep = maxStep * outerStep;
277
106
  if (innerMaxStep > MAXIMUM_STEP_UNROLLED)
278
6
    State = State->add<LoopStack>(
279
6
        LoopState::getNormal(LoopStmt, LCtx, maxVisitOnPath));
280
100
  else
281
100
    State = State->add<LoopStack>(
282
100
        LoopState::getUnrolled(LoopStmt, LCtx, innerMaxStep));
283
106
  return State;
284
106
}
285
286
5.61k
bool isUnrolledState(ProgramStateRef State) {
287
5.61k
  auto LS = State->get<LoopStack>();
288
5.61k
  if (LS.isEmpty() || 
!LS.getHead().isUnrolled()5.52k
)
289
1.32k
    return false;
290
4.29k
  return true;
291
4.29k
}
292
}
293
}