-
Notifications
You must be signed in to change notification settings - Fork 348
/
ForwardAnalysisImpl.java
590 lines (564 loc) · 25.1 KB
/
ForwardAnalysisImpl.java
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
package org.checkerframework.dataflow.analysis;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.VariableTree;
import java.util.ArrayList;
import java.util.IdentityHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.lang.model.type.TypeMirror;
import org.checkerframework.checker.interning.qual.FindDistinct;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.checkerframework.checker.nullness.qual.RequiresNonNull;
import org.checkerframework.dataflow.cfg.ControlFlowGraph;
import org.checkerframework.dataflow.cfg.UnderlyingAST;
import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGLambda;
import org.checkerframework.dataflow.cfg.UnderlyingAST.CFGMethod;
import org.checkerframework.dataflow.cfg.UnderlyingAST.Kind;
import org.checkerframework.dataflow.cfg.block.Block;
import org.checkerframework.dataflow.cfg.block.ConditionalBlock;
import org.checkerframework.dataflow.cfg.block.ExceptionBlock;
import org.checkerframework.dataflow.cfg.block.RegularBlock;
import org.checkerframework.dataflow.cfg.block.SpecialBlock;
import org.checkerframework.dataflow.cfg.node.LocalVariableNode;
import org.checkerframework.dataflow.cfg.node.Node;
import org.checkerframework.dataflow.cfg.node.ReturnNode;
import org.checkerframework.javacutil.BugInCF;
import org.checkerframework.javacutil.Pair;
/**
* An implementation of a forward analysis to solve a org.checkerframework.dataflow problem given a
* control flow graph and a forward transfer function.
*
* @param <V> the abstract value type to be tracked by the analysis
* @param <S> the store type used in the analysis
* @param <T> the transfer function type that is used to approximate runtime behavior
*/
public class ForwardAnalysisImpl<
V extends AbstractValue<V>,
S extends Store<S>,
T extends ForwardTransferFunction<V, S>>
extends AbstractAnalysis<V, S, T> implements ForwardAnalysis<V, S, T> {
/**
* Number of times each block has been analyzed since the last time widening was applied. Null
* if maxCountBeforeWidening is -1, which implies widening isn't used for this analysis.
*/
protected final @Nullable IdentityHashMap<Block, Integer> blockCount;
/**
* Number of times a block can be analyzed before widening. -1 implies that widening shouldn't
* be used.
*/
protected final int maxCountBeforeWidening;
/** Then stores before every basic block (assumed to be 'no information' if not present). */
protected final IdentityHashMap<Block, S> thenStores;
/** Else stores before every basic block (assumed to be 'no information' if not present). */
protected final IdentityHashMap<Block, S> elseStores;
/** The stores after every return statement. */
protected final IdentityHashMap<ReturnNode, TransferResult<V, S>> storesAtReturnStatements;
// `@code`, not `@link`, because dataflow module doesn't depend on framework module.
/**
* Construct an object that can perform a org.checkerframework.dataflow forward analysis over a
* control flow graph. The transfer function is set by the subclass, e.g., {@code
* org.checkerframework.framework.flow.CFAbstractAnalysis}, later.
*
* @param maxCountBeforeWidening number of times a block can be analyzed before widening
*/
public ForwardAnalysisImpl(int maxCountBeforeWidening) {
super(Direction.FORWARD);
this.maxCountBeforeWidening = maxCountBeforeWidening;
this.blockCount = maxCountBeforeWidening == -1 ? null : new IdentityHashMap<>();
this.thenStores = new IdentityHashMap<>();
this.elseStores = new IdentityHashMap<>();
this.storesAtReturnStatements = new IdentityHashMap<>();
}
/**
* Construct an object that can perform a org.checkerframework.dataflow forward analysis over a
* control flow graph given a transfer function.
*
* @param transfer the transfer function
*/
public ForwardAnalysisImpl(@Nullable T transfer) {
this(-1);
this.transferFunction = transfer;
}
@Override
public void performAnalysis(ControlFlowGraph cfg) {
if (isRunning) {
throw new BugInCF(
"ForwardAnalysisImpl::performAnalysis() shouldn't be called when the analysis is running.");
}
isRunning = true;
try {
init(cfg);
while (!worklist.isEmpty()) {
Block b = worklist.poll();
performAnalysisBlock(b);
}
} finally {
assert isRunning;
// In case performAnalysisBlock crashed, reset isRunning to false.
isRunning = false;
}
}
@Override
public void performAnalysisBlock(Block b) {
switch (b.getType()) {
case REGULAR_BLOCK:
{
RegularBlock rb = (RegularBlock) b;
// Apply transfer function to contents
TransferInput<V, S> inputBefore = getInputBefore(rb);
assert inputBefore != null : "@AssumeAssertion(nullness): invariant";
currentInput = inputBefore.copy();
Node lastNode = null;
boolean addToWorklistAgain = false;
for (Node n : rb.getContents()) {
assert currentInput != null : "@AssumeAssertion(nullness): invariant";
TransferResult<V, S> transferResult = callTransferFunction(n, currentInput);
addToWorklistAgain |= updateNodeValues(n, transferResult);
currentInput = new TransferInput<>(n, this, transferResult);
lastNode = n;
}
assert currentInput != null : "@AssumeAssertion(nullness): invariant";
// Loop will run at least once, making transferResult non-null
// Propagate store to successors
Block succ = rb.getSuccessor();
assert succ != null
: "@AssumeAssertion(nullness): regular basic block without non-exceptional successor unexpected";
propagateStoresTo(
succ, lastNode, currentInput, rb.getFlowRule(), addToWorklistAgain);
break;
}
case EXCEPTION_BLOCK:
{
ExceptionBlock eb = (ExceptionBlock) b;
// Apply transfer function to content
TransferInput<V, S> inputBefore = getInputBefore(eb);
assert inputBefore != null : "@AssumeAssertion(nullness): invariant";
currentInput = inputBefore.copy();
Node node = eb.getNode();
TransferResult<V, S> transferResult = callTransferFunction(node, currentInput);
boolean addToWorklistAgain = updateNodeValues(node, transferResult);
// Propagate store to successor
Block succ = eb.getSuccessor();
if (succ != null) {
currentInput = new TransferInput<>(node, this, transferResult);
// TODO: Variable wasn't used.
// Store.FlowRule storeFlow = eb.getFlowRule();
propagateStoresTo(
succ, node, currentInput, eb.getFlowRule(), addToWorklistAgain);
}
// Propagate store to exceptional successors
for (Map.Entry<TypeMirror, Set<Block>> e :
eb.getExceptionalSuccessors().entrySet()) {
TypeMirror cause = e.getKey();
S exceptionalStore = transferResult.getExceptionalStore(cause);
if (exceptionalStore != null) {
for (Block exceptionSucc : e.getValue()) {
addStoreBefore(
exceptionSucc,
node,
exceptionalStore,
Store.Kind.BOTH,
addToWorklistAgain);
}
} else {
for (Block exceptionSucc : e.getValue()) {
addStoreBefore(
exceptionSucc,
node,
inputBefore.copy().getRegularStore(),
Store.Kind.BOTH,
addToWorklistAgain);
}
}
}
break;
}
case CONDITIONAL_BLOCK:
{
ConditionalBlock cb = (ConditionalBlock) b;
// Get store before
TransferInput<V, S> inputBefore = getInputBefore(cb);
assert inputBefore != null : "@AssumeAssertion(nullness): invariant";
TransferInput<V, S> input = inputBefore.copy();
// Propagate store to successor
Block thenSucc = cb.getThenSuccessor();
Block elseSucc = cb.getElseSuccessor();
propagateStoresTo(thenSucc, null, input, cb.getThenFlowRule(), false);
propagateStoresTo(elseSucc, null, input, cb.getElseFlowRule(), false);
break;
}
case SPECIAL_BLOCK:
{
// Special basic blocks are empty and cannot throw exceptions,
// thus there is no need to perform any analysis.
SpecialBlock sb = (SpecialBlock) b;
Block succ = sb.getSuccessor();
if (succ != null) {
TransferInput<V, S> input = getInputBefore(b);
assert input != null : "@AssumeAssertion(nullness): invariant";
propagateStoresTo(succ, null, input, sb.getFlowRule(), false);
}
break;
}
default:
throw new BugInCF("Unexpected block type: " + b.getType());
}
}
@Override
public @Nullable TransferInput<V, S> getInput(Block b) {
return getInputBefore(b);
}
@Override
@SuppressWarnings("nullness:contracts.precondition.override.invalid") // implementation field
@RequiresNonNull("cfg")
public List<Pair<ReturnNode, @Nullable TransferResult<V, S>>> getReturnStatementStores() {
List<Pair<ReturnNode, @Nullable TransferResult<V, S>>> result = new ArrayList<>();
for (ReturnNode returnNode : cfg.getReturnNodes()) {
TransferResult<V, S> store = storesAtReturnStatements.get(returnNode);
result.add(Pair.of(returnNode, store));
}
return result;
}
@Override
public S runAnalysisFor(
@FindDistinct Node node,
boolean before,
TransferInput<V, S> transferInput,
IdentityHashMap<Node, V> nodeValues,
Map<TransferInput<V, S>, IdentityHashMap<Node, TransferResult<V, S>>> analysisCaches) {
Block block = node.getBlock();
assert block != null : "@AssumeAssertion(nullness): invariant";
Node oldCurrentNode = currentNode;
// Prepare cache
IdentityHashMap<Node, TransferResult<V, S>> cache;
if (analysisCaches != null) {
cache = analysisCaches.get(transferInput);
if (cache == null) {
cache = new IdentityHashMap<>();
analysisCaches.put(transferInput, cache);
}
} else {
cache = null;
}
if (isRunning) {
assert currentInput != null : "@AssumeAssertion(nullness): invariant";
return currentInput.getRegularStore();
}
setNodeValues(nodeValues);
isRunning = true;
try {
switch (block.getType()) {
case REGULAR_BLOCK:
{
RegularBlock rb = (RegularBlock) block;
// Apply transfer function to contents until we found the node we are
// looking for.
TransferInput<V, S> store = transferInput;
TransferResult<V, S> transferResult;
for (Node n : rb.getContents()) {
setCurrentNode(n);
if (n == node && before) {
return store.getRegularStore();
}
if (cache != null && cache.containsKey(n)) {
transferResult = cache.get(n);
} else {
// Copy the store to avoid changing other blocks' transfer inputs in
// {@link #inputs}
transferResult = callTransferFunction(n, store.copy());
if (cache != null) {
cache.put(n, transferResult);
}
}
if (n == node) {
return transferResult.getRegularStore();
}
store = new TransferInput<>(n, this, transferResult);
}
// This point should never be reached. If the block of 'node' is
// 'block', then 'node' must be part of the contents of 'block'.
throw new BugInCF("This point should never be reached.");
}
case EXCEPTION_BLOCK:
{
ExceptionBlock eb = (ExceptionBlock) block;
// Apply the transfer function to content
if (eb.getNode() != node) {
throw new BugInCF(
"Node should be equal to eb.getNode(). But get: node: "
+ node
+ "\teb.getNode(): "
+ eb.getNode());
}
if (before) {
return transferInput.getRegularStore();
}
setCurrentNode(node);
// Copy the store to avoid changing other blocks' transfer inputs in {@link
// #inputs}
TransferResult<V, S> transferResult =
callTransferFunction(node, transferInput.copy());
return transferResult.getRegularStore();
}
default:
// Only regular blocks and exceptional blocks can hold nodes.
throw new BugInCF("Unexpected block type: " + block.getType());
}
} finally {
setCurrentNode(oldCurrentNode);
isRunning = false;
}
}
@Override
protected void initFields(ControlFlowGraph cfg) {
thenStores.clear();
elseStores.clear();
if (blockCount != null) {
blockCount.clear();
}
storesAtReturnStatements.clear();
super.initFields(cfg);
}
@Override
@RequiresNonNull("cfg")
protected void initInitialInputs() {
worklist.process(cfg);
Block entry = cfg.getEntryBlock();
worklist.add(entry);
List<LocalVariableNode> parameters = null;
UnderlyingAST underlyingAST = cfg.getUnderlyingAST();
if (underlyingAST.getKind() == Kind.METHOD) {
MethodTree tree = ((CFGMethod) underlyingAST).getMethod();
parameters = new ArrayList<>();
for (VariableTree p : tree.getParameters()) {
LocalVariableNode var = new LocalVariableNode(p);
parameters.add(var);
// TODO: document that LocalVariableNode has no block that it belongs to
}
} else if (underlyingAST.getKind() == Kind.LAMBDA) {
LambdaExpressionTree lambda = ((CFGLambda) underlyingAST).getLambdaTree();
parameters = new ArrayList<>();
for (VariableTree p : lambda.getParameters()) {
LocalVariableNode var = new LocalVariableNode(p);
parameters.add(var);
// TODO: document that LocalVariableNode has no block that it belongs to
}
}
assert transferFunction != null : "@AssumeAssertion(nullness): invariant";
S initialStore = transferFunction.initialStore(underlyingAST, parameters);
thenStores.put(entry, initialStore);
elseStores.put(entry, initialStore);
inputs.put(entry, new TransferInput<>(null, this, initialStore));
}
@Override
protected TransferResult<V, S> callTransferFunction(Node node, TransferInput<V, S> input) {
TransferResult<V, S> transferResult = super.callTransferFunction(node, input);
if (node instanceof ReturnNode) {
// Save a copy of the store to later check if some property holds at a given return
// statement
storesAtReturnStatements.put((ReturnNode) node, transferResult);
}
return transferResult;
}
@Override
protected void propagateStoresTo(
Block succ,
@Nullable Node node,
TransferInput<V, S> currentInput,
Store.FlowRule flowRule,
boolean addToWorklistAgain) {
switch (flowRule) {
case EACH_TO_EACH:
if (currentInput.containsTwoStores()) {
addStoreBefore(
succ,
node,
currentInput.getThenStore(),
Store.Kind.THEN,
addToWorklistAgain);
addStoreBefore(
succ,
node,
currentInput.getElseStore(),
Store.Kind.ELSE,
addToWorklistAgain);
} else {
addStoreBefore(
succ,
node,
currentInput.getRegularStore(),
Store.Kind.BOTH,
addToWorklistAgain);
}
break;
case THEN_TO_BOTH:
addStoreBefore(
succ,
node,
currentInput.getThenStore(),
Store.Kind.BOTH,
addToWorklistAgain);
break;
case ELSE_TO_BOTH:
addStoreBefore(
succ,
node,
currentInput.getElseStore(),
Store.Kind.BOTH,
addToWorklistAgain);
break;
case THEN_TO_THEN:
addStoreBefore(
succ,
node,
currentInput.getThenStore(),
Store.Kind.THEN,
addToWorklistAgain);
break;
case ELSE_TO_ELSE:
addStoreBefore(
succ,
node,
currentInput.getElseStore(),
Store.Kind.ELSE,
addToWorklistAgain);
break;
}
}
/**
* Add a store before the basic block {@code b} by merging with the existing stores for that
* location.
*
* @param b a basic block
* @param node the node of the basic block {@code b}
* @param s the store being added
* @param kind the kind of store {@code s}
* @param addBlockToWorklist whether the basic block {@code b} should be added back to {@code
* Worklist}
*/
protected void addStoreBefore(
Block b, @Nullable Node node, S s, Store.Kind kind, boolean addBlockToWorklist) {
S thenStore = getStoreBefore(b, Store.Kind.THEN);
S elseStore = getStoreBefore(b, Store.Kind.ELSE);
boolean shouldWiden = false;
if (blockCount != null) {
Integer count = blockCount.get(b);
if (count == null) {
count = 0;
}
shouldWiden = count >= maxCountBeforeWidening;
if (shouldWiden) {
blockCount.put(b, 0);
} else {
blockCount.put(b, count + 1);
}
}
switch (kind) {
case THEN:
{
// Update the then store
S newThenStore = mergeStores(s, thenStore, shouldWiden);
if (!newThenStore.equals(thenStore)) {
thenStores.put(b, newThenStore);
if (elseStore != null) {
inputs.put(b, new TransferInput<>(node, this, newThenStore, elseStore));
addBlockToWorklist = true;
}
}
break;
}
case ELSE:
{
// Update the else store
S newElseStore = mergeStores(s, elseStore, shouldWiden);
if (!newElseStore.equals(elseStore)) {
elseStores.put(b, newElseStore);
if (thenStore != null) {
inputs.put(b, new TransferInput<>(node, this, thenStore, newElseStore));
addBlockToWorklist = true;
}
}
break;
}
case BOTH:
@SuppressWarnings("interning:not.interned")
boolean sameStore = (thenStore == elseStore);
if (sameStore) {
// Currently there is only one regular store
S newStore = mergeStores(s, thenStore, shouldWiden);
if (!newStore.equals(thenStore)) {
thenStores.put(b, newStore);
elseStores.put(b, newStore);
inputs.put(b, new TransferInput<>(node, this, newStore));
addBlockToWorklist = true;
}
} else {
boolean storeChanged = false;
S newThenStore = mergeStores(s, thenStore, shouldWiden);
if (!newThenStore.equals(thenStore)) {
thenStores.put(b, newThenStore);
storeChanged = true;
}
S newElseStore = mergeStores(s, elseStore, shouldWiden);
if (!newElseStore.equals(elseStore)) {
elseStores.put(b, newElseStore);
storeChanged = true;
}
if (storeChanged) {
inputs.put(b, new TransferInput<>(node, this, newThenStore, newElseStore));
addBlockToWorklist = true;
}
}
}
if (addBlockToWorklist) {
addToWorklist(b);
}
}
/**
* Merge two stores, possibly widening the result.
*
* @param newStore the new Store
* @param previousStore the previous Store
* @param shouldWiden should widen or not
* @return the merged Store
*/
private S mergeStores(S newStore, @Nullable S previousStore, boolean shouldWiden) {
if (previousStore == null) {
return newStore;
} else if (shouldWiden) {
return newStore.widenedUpperBound(previousStore);
} else {
return newStore.leastUpperBound(previousStore);
}
}
/**
* Return the store corresponding to the location right before the basic block {@code b}.
*
* @param b a block
* @param kind the kind of store which will be returned
* @return the store corresponding to the location right before the basic block {@code b}
*/
protected @Nullable S getStoreBefore(Block b, Store.Kind kind) {
switch (kind) {
case THEN:
return readFromStore(thenStores, b);
case ELSE:
return readFromStore(elseStores, b);
default:
throw new BugInCF("Unexpected Store Kind: " + kind);
}
}
/**
* Returns the transfer input corresponding to the location right before the basic block {@code
* b}.
*
* @param b a block
* @return the transfer input corresponding to the location right before the basic block {@code
* b}
*/
protected @Nullable TransferInput<V, S> getInputBefore(Block b) {
return inputs.get(b);
}
}