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