Repository navigation
Expand file tree
/
Copy pathforwardanalyzer.cpp
More file actions
1264 lines (1188 loc) · 60 KB
/
Copy pathforwardanalyzer.cpp
File metadata and controls
1264 lines (1188 loc) · 60 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
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Cppcheck - A tool for static C/C++ code analysis
* Copyright (C) 2007-2026 Cppcheck team.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "forwardanalyzer.h"
#include "analyzer.h"
#include "astutils.h"
#include "config.h"
#include "errorlogger.h"
#include "errortypes.h"
#include "mathlib.h"
#include "refthunk.h"
#include "settings.h"
#include "symboldatabase.h"
#include "token.h"
#include "tokenlist.h"
#include "utils.h"
#include "valueptr.h"
#include <algorithm>
#include <cassert>
#include <cstdio>
#include <cstdint>
#include <functional>
#include <list>
#include <memory>
#include <numeric>
#include <string>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
namespace {
// A traversal walks one path through the code: the tracked value with the state assumed on the
// way. Where the paths part, another path is walked on a fork().
struct ForwardTraversal {
enum class Progress : std::uint8_t { Continue, Break, Skip };
ForwardTraversal(const ValuePtr<Analyzer>& analyzer, const TokenList& tokenList, ErrorLogger& errorLogger, const Settings& settings)
: analyzer(analyzer), tokenList(tokenList), errorLogger(errorLogger), settings(settings)
{}
// What became of the paths through a range
struct Outcome {
Analyzer::Action action = Analyzer::Action::None;
int reached = 0;
// How each path that did not reach the end stopped
std::vector<Analyzer::Terminate> stops;
void reach(Analyzer::Action a) {
action |= a;
++reached;
}
void stop(Analyzer::Action a, Analyzer::Terminate t) {
action |= a;
stops.push_back(t);
}
// The paths that stopped in a block of the range stopped in the range. If another path
// covers the code they did not walk, only an escape or a changed value counts.
void add(const Outcome& block, bool covered) {
action |= block.action;
for (Analyzer::Terminate t : block.stops) {
if (covered && t != Analyzer::Terminate::Escape && t != Analyzer::Terminate::Modified)
t = Analyzer::Terminate::None;
stops.push_back(t);
}
}
// Paths that were followed to the end of the same range
void join(const Outcome& paths) {
add(paths, false);
reached += paths.reached;
}
bool hasEscape() const {
return contains(stops, Analyzer::Terminate::Escape);
}
bool allEscape() const {
return reached == 0 && !stops.empty() && std::all_of(stops.cbegin(), stops.cend(), [](Analyzer::Terminate t) {
return t == Analyzer::Terminate::Escape;
});
}
Analyzer::Terminate worst() const {
Analyzer::Terminate result = Analyzer::Terminate::None;
for (Analyzer::Terminate t : stops) {
if (rank(t) > rank(result))
result = t;
}
return result;
}
// A path stopped without walking the rest of the range
bool unwalked() const {
const Analyzer::Terminate t = worst();
return t != Analyzer::Terminate::None && t != Analyzer::Terminate::Modified;
}
static int rank(Analyzer::Terminate t) {
switch (t) {
case Analyzer::Terminate::None:
case Analyzer::Terminate::Escape:
return 0;
case Analyzer::Terminate::Modified:
return 1;
case Analyzer::Terminate::Conditional:
return 2;
case Analyzer::Terminate::Inconclusive:
return 3;
case Analyzer::Terminate::Bail:
return 4;
case Analyzer::Terminate::Partial:
break;
}
cppcheck::unreachable();
}
};
ValuePtr<Analyzer> analyzer;
RefThunk<const TokenList> tokenList;
RefThunk<ErrorLogger> errorLogger;
RefThunk<const Settings> settings;
Analyzer::Action actions;
bool analyzeOnly{};
bool analyzeTerminate{};
Analyzer::Terminate terminate = Analyzer::Terminate::None;
std::vector<Token*> loopEnds;
int branchCount = 0;
// Nested condition-fork depth on this lineage (copied by fork()); bounds the fan-out.
int forkDepth = 0;
// Total forks of the traversal (shared via the fork() copy); backstop past the depth bound.
std::shared_ptr<int> forkBudget = std::make_shared<int>(0);
// The paths that parted from this one in the range being walked and do not go on with it
Outcome parted;
Progress Break(Analyzer::Terminate t = Analyzer::Terminate::None) {
if ((!analyzeOnly || analyzeTerminate) && t != Analyzer::Terminate::None)
terminate = t;
return Progress::Break;
}
struct Branch {
explicit Branch(Token* tok = nullptr) : endBlock(tok) {}
// nullptr if there is nothing to walk, e.g. an if without else
Token* endBlock = nullptr;
Analyzer::Action action = Analyzer::Action::None;
bool escape = false;
bool escapeUnknown = false;
// The path that walked the block is at its end
bool reachesEnd = true;
// The traversal that walked the block
ForwardTraversal* traversal = nullptr;
// The condition that holds on it, if it is a fork
const Token* condTok = nullptr;
// The paths that stopped in the block, if it was walked on a fork
Outcome stoppedPaths;
bool isEscape() const {
return escape || escapeUnknown;
}
bool isConclusiveEscape() const {
return escape && !escapeUnknown;
}
bool isModified() const {
return action.isModified() && !isConclusiveEscape();
}
bool isInconclusive() const {
return action.isInconclusive() && !isConclusiveEscape();
}
bool isDead() const {
return action.isModified() || action.isInconclusive() || isEscape();
}
bool hasGoto() const {
return endBlock ? ForwardTraversal::hasGoto(endBlock) : false;
}
};
bool stopUpdates() {
analyzeOnly = true;
return actions.isModified();
}
bool stopOnCondition(const Token* condTok) const
{
if (analyzer->isConditional() && findAstNode(condTok, [](const Token* tok) {
return tok->isIncompleteVar();
}))
return true;
return analyzer->stopOnCondition(condTok);
}
std::pair<bool, bool> evalCond(const Token* tok, const Token* ctx = nullptr) const {
if (!tok)
return std::make_pair(false, false);
std::vector<MathLib::bigint> result = analyzer->evaluate(tok, ctx);
// TODO: We should convert to bool
const bool checkThen = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) {
return x != 0;
});
const bool checkElse = std::any_of(result.cbegin(), result.cend(), [](MathLib::bigint x) {
return x == 0;
});
return std::make_pair(checkThen, checkElse);
}
bool isConditionTrue(const Token* tok, const Token* ctx = nullptr) const {
return evalCond(tok, ctx).first;
}
bool isConditionFalse(const Token* tok, const Token* ctx = nullptr) const {
const std::pair<bool, bool> check = evalCond(tok, ctx);
return !check.first && check.second;
}
template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
Progress traverseTok(T* tok, const F &f, bool traverseUnknown, T** out = nullptr) {
if (Token::Match(tok, "asm|goto"))
return Break(Analyzer::Terminate::Bail);
if (Token::Match(tok, "setjmp|longjmp (")) {
// Traverse the parameters of the function before escaping
traverseRecursive(tok->next()->astOperand2(), f, traverseUnknown);
return Break(Analyzer::Terminate::Bail);
}
if (Token::simpleMatch(tok, "continue")) {
if (loopEnds.empty())
return Break(Analyzer::Terminate::Escape);
// If we are in a loop then jump to the end
if (out)
*out = loopEnds.back();
} else if (isEscapeKeyword(tok, settings)) {
traverseRecursive(tok->astOperand2(), f, traverseUnknown);
traverseRecursive(tok->astOperand1(), f, traverseUnknown);
return Break(Analyzer::Terminate::Escape);
} else if (Token::Match(tok, "%name% (") && isEscapeFunction(tok, settings().library)) {
// Traverse the parameters of the function before escaping
traverseRecursive(tok->next()->astOperand2(), f, traverseUnknown);
return Break(Analyzer::Terminate::Escape);
} else if (isUnevaluated(tok->previous())) {
if (out)
*out = tok->link();
return Progress::Skip;
} else if (tok->astOperand1() && tok->astOperand2() && Token::Match(tok, "?|&&|%oror%")) {
if (traverseConditional(tok, f, traverseUnknown) == Progress::Break)
return Break();
if (out)
*out = nextAfterAstRightmostLeaf(tok);
return Progress::Skip;
// Skip lambdas
} else if (T* lambdaEndToken = findLambdaEndToken(tok)) {
if (checkScope(lambdaEndToken).isModified())
return Break(Analyzer::Terminate::Bail);
if (out)
*out = lambdaEndToken->next();
// Skip class scope
} else if (tok->str() == "{" && tok->scope() && tok->scope()->isClassOrStruct()) {
if (out)
*out = tok->link();
} else {
if (f(tok) == Progress::Break)
return Break();
}
return Progress::Continue;
}
template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
Progress traverseRecursive(T* tok, const F &f, bool traverseUnknown, unsigned int recursion=0) {
if (!tok)
return Progress::Continue;
if (recursion > 10000)
return Progress::Skip;
T* firstOp = tok->astOperand1();
T* secondOp = tok->astOperand2();
// Evaluate:
// 1. RHS of assignment before LHS
// 2. Unary op before operand
// 3. Function arguments before function call
if (tok->isAssignmentOp() || !secondOp || isFunctionCall(tok))
std::swap(firstOp, secondOp);
if (firstOp && traverseRecursive(firstOp, f, traverseUnknown, recursion+1) == Progress::Break)
return Break();
const Progress p = tok->isAssignmentOp() ? Progress::Continue : traverseTok(tok, f, traverseUnknown);
if (p == Progress::Break)
return Break();
if (p == Progress::Continue && secondOp && traverseRecursive(secondOp, f, traverseUnknown, recursion+1) == Progress::Break)
return Break();
if (tok->isAssignmentOp() && traverseTok(tok, f, traverseUnknown) == Progress::Break)
return Break();
return Progress::Continue;
}
template<class T, class F, REQUIRES("T must be a Token class", std::is_convertible<T*, const Token*> )>
Progress traverseConditional(T* tok, F f, bool traverseUnknown) {
Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward);
if (action.isNone() && Token::Match(tok, "?|&&|%oror%") && tok->astOperand1() && tok->astOperand2()) {
const T* condTok = tok->astOperand1();
T* childTok = tok->astOperand2();
bool checkThen, checkElse;
std::tie(checkThen, checkElse) = evalCond(condTok);
if (!checkThen && !checkElse) {
if (!traverseUnknown && stopOnCondition(condTok) && tok->str() != "?" && stopUpdates()) {
return Progress::Continue;
}
checkThen = true;
checkElse = true;
}
if (childTok->str() == ":") {
if (checkThen && traverseRecursive(childTok->astOperand1(), f, traverseUnknown) == Progress::Break)
return Break();
if (checkElse && traverseRecursive(childTok->astOperand2(), f, traverseUnknown) == Progress::Break)
return Break();
} else {
if (!checkThen && tok->str() == "&&")
return Progress::Continue;
if (!checkElse && tok->str() == "||")
return Progress::Continue;
if (traverseRecursive(childTok, f, traverseUnknown) == Progress::Break)
return Break();
}
} else {
return f(tok, action);
}
return Progress::Continue;
}
Progress update(Token* tok) {
Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward);
return update(tok, action);
}
Progress update(Token* tok, Analyzer::Action action)
{
actions |= action;
if (!action.isNone() && !analyzeOnly)
analyzer->update(tok, action, Analyzer::Direction::Forward);
if (action.isInconclusive() && !analyzer->lowerToInconclusive())
return Break(Analyzer::Terminate::Inconclusive);
if (action.isInvalid())
return Break(Analyzer::Terminate::Modified);
if (action.isWrite() && !action.isRead())
// Analysis of this write will continue separately
return Break(Analyzer::Terminate::Modified);
return Progress::Continue;
}
struct AsUpdate {
ForwardTraversal* self = nullptr;
explicit AsUpdate(ForwardTraversal* self) : self(self) {}
template<class... Ts>
Progress operator()(Ts... xs) const
{
assert(self);
return self->update(xs ...);
}
};
Progress updateTok(Token* tok, Token** out = nullptr) {
return traverseTok(tok, AsUpdate{this}, false, out);
}
Progress updateRecursive(Token* tok) {
return traverseRecursive(tok, AsUpdate{this}, false);
}
struct AsAnalyze {
ForwardTraversal* self = nullptr;
Analyzer::Action* result = nullptr;
AsAnalyze(ForwardTraversal* self, Analyzer::Action* result) : self(self), result(result) {}
Progress operator()(const Token* tok) const
{
assert(self);
assert(result);
return (*this)(tok, self->analyzer->analyze(tok, Analyzer::Direction::Forward));
}
Progress operator()(const Token* /*unused*/, Analyzer::Action action) const
{
assert(self);
assert(result);
*result = action;
if (result->isModified() || result->isInconclusive())
return self->Break();
return Progress::Continue;
}
};
Analyzer::Action analyzeRecursive(const Token* start) {
Analyzer::Action result = Analyzer::Action::None;
traverseRecursive(start, AsAnalyze{this, &result}, true);
return result;
}
Analyzer::Action analyzeRange(const Token* start, const Token* end) const {
Analyzer::Action result = Analyzer::Action::None;
for (const Token* tok = start; tok && tok != end; tok = tok->next()) {
Analyzer::Action action = analyzer->analyze(tok, Analyzer::Direction::Forward);
if (action.isModified() || action.isInconclusive())
return action;
result |= action;
}
return result;
}
ForwardTraversal fork(bool analyze = false) const {
ForwardTraversal ft = *this;
if (analyze) {
ft.analyzeOnly = true;
ft.analyzeTerminate = true;
}
ft.actions = Analyzer::Action::None;
ft.parted = Outcome{};
return ft;
}
// Another condition-fork may continue past its if: forkDepth bounds nesting, forkBudget the
// total. <0 = off.
bool canFork() const {
assert(forkBudget != nullptr);
const int depthLimit = settings().vfOptions.maxForwardConditionForkDepth;
const int budgetLimit = settings().vfOptions.maxForwardConditionForks;
return (depthLimit < 0 || forkDepth < depthLimit) && (budgetLimit < 0 || *forkBudget < budgetLimit);
}
// A value changed in one of the branches is only possible past them, on every path. False
// if it cannot be lowered.
static bool lowerAfterBranches(Analyzer& a, const std::vector<Branch>& branches) {
if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isModified)) && !a.lowerToPossible())
return false;
if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isInconclusive)) &&
!a.lowerToInconclusive())
return false;
return true;
}
std::vector<ForwardTraversal> tryForkScope(Token* endBlock, bool isModified = false) const {
if (analyzer->updateScope(endBlock, isModified)) {
ForwardTraversal ft = fork();
return {std::move(ft)};
}
return std::vector<ForwardTraversal> {};
}
std::vector<ForwardTraversal> tryForkUpdateScope(Token* endBlock, bool isModified = false) const {
std::vector<ForwardTraversal> result = tryForkScope(endBlock, isModified);
for (ForwardTraversal& ft : result)
ft.updateAllScopePaths(endBlock);
return result;
}
static bool hasGoto(const Token* endBlock) {
return Token::findsimplematch(endBlock->link(), "goto", endBlock);
}
static bool hasJump(const Token* endBlock) {
return Token::findmatch(endBlock->link(), "goto|break", endBlock);
}
bool isEscapeScope(const Token* endBlock, bool& unknown) const {
const Token* ftok = nullptr;
const bool r = isReturnScope(endBlock, settings().library, &ftok);
if (!r && ftok)
unknown = true;
return r;
}
Analyzer::Action analyzeScope(const Token* endBlock) const {
return analyzeRange(endBlock->link(), endBlock);
}
Analyzer::Action checkScope(Token* endBlock) const {
Analyzer::Action a = analyzeScope(endBlock);
tryForkUpdateScope(endBlock, a.isModified());
return a;
}
Analyzer::Action checkScope(const Token* endBlock) const {
Analyzer::Action a = analyzeScope(endBlock);
return a;
}
// What became of this path and of the paths that parted from it
Outcome outcome(Progress p) const
{
Outcome paths = parted;
if (p == Progress::Break)
paths.stop(actions, terminate);
else
paths.reach(actions);
return paths;
}
// Walk a block on this traversal. The paths do not part for good inside it: each one would
// have to be followed past the block to the end of the range, which costs too much.
Branch updateBranch(Token* endBlock, int depth)
{
const Analyzer::Action outerActions = actions;
actions = Analyzer::Action::None;
Outcome outer = std::move(parted);
parted = Outcome{};
const Progress p = updateRange(endBlock->link(), endBlock, false, depth);
const Outcome paths = outcome(p);
outer.add(parted, false);
parted = std::move(outer);
actions |= outerActions;
Branch branch{endBlock};
branch.action = paths.action;
branch.reachesEnd = paths.reached > 0;
if (paths.allEscape()) {
branch.escape = true;
// The paths can miss a way through the block: a call is taken to return what an
// earlier call of the same function returned. Unless the block structurally always
// escapes, it may fall through and change the value on the way.
bool structuralUnknown = false;
const bool structuralEscape = isEscapeScope(endBlock, structuralUnknown);
branch.escapeUnknown = !structuralEscape || structuralUnknown;
if (branch.escapeUnknown)
branch.action |= analyzeScope(endBlock);
} else {
// Detect an escape the paths did not flag (e.g. an unknown noreturn call);
// escapeUnknown reports a possible (unknown) escape.
branch.escape = isEscapeScope(endBlock, branch.escapeUnknown);
if (paths.unwalked())
branch.action |= analyzeScope(endBlock);
}
return branch;
}
// The condition was evaluated: walk the one block of the if that it selects
Progress updateSingleIfBranch(Token* endBlock, const Token* skippedBlock, const Token* condTok, int depth)
{
// The condition is only "known" because of an earlier assumption, so the
// skipped block could still modify the value -> lower to possible
if (!condTok->hasKnownIntValue() && skippedBlock && analyzeScope(skippedBlock).isModified() &&
!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
if (!endBlock) {
// Record the state past the skipped block, so that the conditions evaluated later do
// not each look for changes in it
if (skippedBlock->next())
analyzer->updateState(skippedBlock->next());
return Progress::Continue;
}
updateScopeState(endBlock);
const Branch branch = updateBranch(endBlock, depth - 1);
if (!branch.reachesEnd)
return Progress::Break;
// The branch was entered because of the tracked value; if it might not
// return (it ends in a call to an unknown, possibly noreturn function)
// then the value might not flow past the branch.
if (!condTok->hasKnownIntValue() && !branch.escape && branch.escapeUnknown && !analyzer->lowerToInconclusive())
return Break(Analyzer::Terminate::Bail);
return Progress::Continue;
}
// A path that parted from this one stops
void stopFork(ForwardTraversal& ft, Analyzer::Terminate t = Analyzer::Terminate::None)
{
ft.Break(t);
parted.stop(ft.actions, ft.terminate);
}
// This path stopped; the path of a fork goes on in its place
void replaceWith(ForwardTraversal ft)
{
Outcome paths = std::move(parted);
paths.stop(actions, terminate);
*this = std::move(ft);
parted = std::move(paths);
}
// Walk a block on a fork of this traversal, on which the condition holds
Branch updateForkedBranch(ForwardTraversal& ft, const Token* condTok, Token* endBlock, bool split, int depth) const
{
ft.actions = actions;
if (split) {
++(*forkBudget);
++ft.forkDepth;
}
ft.analyzer->assume(condTok, true, Analyzer::Assume::Pending);
Branch branch = ft.updateBranch(endBlock, depth);
branch.traversal = &ft;
branch.condTok = condTok;
// The branch limit counts the branches on the way past the block, as it does for this path
ft.branchCount = branchCount;
// A fork that does not split uses up the fork limit as well. Otherwise the whole limit is
// left for the forks that walk to the end of the range, which are the expensive ones.
if (!split && branch.reachesEnd && canFork())
++(*forkBudget);
branch.stoppedPaths = std::move(ft.parted);
ft.parted = Outcome{};
if (!branch.reachesEnd)
branch.stoppedPaths.stop(ft.actions, ft.terminate);
return branch;
}
// Neither outcome of the condition is known: the then block is walked on a fork, the else
// block on this traversal.
Progress updateIfBranches(const Token* condTok, Token* thenEnd, Token* elseEnd, const Token* end, bool conditional, bool split, int depth)
{
Token* ifEnd = elseEnd ? elseEnd : thenEnd;
// The value only flows into the then block when the condition can split it; for an opaque
// or correlated condition (e.g. 'if (f(x))') it does not, so the fork is analyze-only: the
// block's effect is still tracked but nothing is reported in it.
ForwardTraversal ft = fork(!analyzer->updateScope(thenEnd, false));
const Branch thenBranch = updateForkedBranch(ft, condTok, thenEnd, split, depth - 1);
// The condition is an assumption on this path if the then path drops the value. If the
// then path goes on past the if, the value is the same with and without it. Otherwise
// this path stands for the then path as well and records that the condition is false
// only if that holds on both (e.g. 'if (x > 5) x = 5;'). With an else block the state is
// recorded after it.
const unsigned int pending = elseEnd ? Analyzer::Assume::Pending : Analyzer::Assume::None;
bool assumed = true;
if (thenBranch.isDead())
analyzer->assume(condTok, false, pending);
else if (thenBranch.reachesEnd && (split || ft.isConditionFalse(condTok, thenEnd->previous())))
analyzer->assume(condTok, false, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute | pending);
else
assumed = false;
Branch elseBranch;
if (elseEnd) {
if (!assumed)
updateScopeState(elseEnd);
elseBranch = updateBranch(elseEnd, depth - 1);
if (elseBranch.reachesEnd)
analyzer->updateState(elseEnd->previous());
} else if (!assumed && ifEnd->next()) {
// An assumption records the state where the path goes on. Without one the state stays
// at an earlier token, and every condition evaluated later looks for changes from there.
analyzer->updateState(ifEnd->next());
}
elseBranch.traversal = this;
return continueAfterBranches({thenBranch, elseBranch}, conditional, ifEnd->next(), end, split, depth);
}
// The blocks of a branching statement were walked, each on a fork or on this traversal.
// Decide which of the paths go on past the statement. split: every path goes on to the end
// of the range on its own. Otherwise one path goes on for all of them.
Progress continueAfterBranches(const std::vector<Branch>& branches, bool conditional, Token* next, const Token* end, bool split, int depth)
{
const Analyzer::Action action =
std::accumulate(branches.cbegin(), branches.cend(), Analyzer::Action{}, [](Analyzer::Action a, const Branch& branch) {
return a | branch.action;
});
// With a split the block of a fork is not on this path
for (const Branch& branch : branches) {
if (split && branch.traversal != this)
parted.action |= branch.action;
else
actions |= branch.action;
}
const bool jumps = std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::hasGoto));
const bool reachesEnd = std::all_of(branches.cbegin(), branches.cend(), [this](const Branch& branch) {
return branch.traversal != this || branch.reachesEnd;
});
Progress progress = reachesEnd ? Progress::Continue : Progress::Break;
if (reachesEnd) {
if (std::any_of(branches.cbegin(), branches.cend(), std::mem_fn(&Branch::isDead)) && conditional &&
(stopUpdates() || action.isModified()))
progress = Break(Analyzer::Terminate::Conditional);
else if (!lowerAfterBranches(*analyzer, branches) || jumps)
progress = Break(Analyzer::Terminate::Bail);
}
// Without a split this path goes on for the forks. If it stopped, a fork goes on in its place.
const bool forksGoOn = split || progress == Progress::Break;
std::vector<ForwardTraversal*> successors;
for (const Branch& branch : branches) {
if (branch.traversal == this || !branch.reachesEnd)
continue;
ForwardTraversal& ft = *branch.traversal;
ft.actions |= action;
if (jumps) {
stopFork(ft, Analyzer::Terminate::Bail);
} else if (branch.isEscape()) {
stopFork(ft, Analyzer::Terminate::Escape);
} else if (forksGoOn && !lowerAfterBranches(*ft.analyzer, branches)) {
stopFork(ft);
} else if (forksGoOn) {
// Anchor the state (and the block's assignments) at the block end
ft.analyzer->assume(branch.condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute);
if (split)
parted.join(ft.updatePaths(next, end, depth - 1));
else
successors.push_back(&ft);
}
}
// Each fork holds its own condition, so one of several cannot go on for the others
const bool replaced = successors.size() == 1;
// A path that stopped in a block is covered only if a path goes on for it past the
// statement. Otherwise nothing walks the code that follows on its way.
const bool covered = !split && (replaced || progress == Progress::Continue);
for (const Branch& branch : branches)
parted.add(branch.stoppedPaths, covered);
if (replaced) {
replaceWith(std::move(*successors.front()));
return Progress::Continue;
}
for (ForwardTraversal* ft : successors)
stopFork(*ft, Analyzer::Terminate::Bail);
return progress;
}
bool reentersLoop(Token* endBlock, const Token* condTok, const Token* stepTok) const {
if (!condTok)
return true;
if (Token::simpleMatch(condTok, ":"))
return true;
bool stepChangesCond = false;
if (stepTok) {
std::pair<const Token*, const Token*> exprToks = stepTok->findExpressionStartEndTokens();
if (exprToks.first != nullptr && exprToks.second != nullptr)
stepChangesCond |=
findExpressionChanged(condTok, exprToks.first, exprToks.second->next(), settings) != nullptr;
}
const bool bodyChangesCond = findExpressionChanged(condTok, endBlock->link(), endBlock, settings);
// Check for mutation in the condition
const bool condChanged =
nullptr != findAstNode(condTok, [&](const Token* tok) {
return isVariableChanged(tok, 0, settings);
});
const bool changed = stepChangesCond || bodyChangesCond || condChanged;
if (!changed)
return true;
ForwardTraversal ft = fork(true);
ft.updateScope(endBlock);
return ft.isConditionTrue(condTok) && bodyChangesCond;
}
Progress updateInnerLoop(Token* endBlock, Token* stepTok, Token* condTok) {
loopEnds.push_back(endBlock);
OnExit oe{[&] {
loopEnds.pop_back();
}};
if (endBlock && updateScope(endBlock) == Progress::Break)
return Break();
if (stepTok && updateRecursive(stepTok) == Progress::Break)
return Break();
if (condTok && !Token::simpleMatch(condTok, ":") && updateRecursive(condTok) == Progress::Break)
return Break();
return Progress::Continue;
}
Progress updateLoop(const Token* endToken,
Token* endBlock,
Token* condTok,
Token* initTok = nullptr,
Token* stepTok = nullptr,
bool exit = false) {
if (initTok && updateRecursive(initTok) == Progress::Break)
return Break();
const bool isDoWhile = precedes(endBlock, condTok);
bool checkThen = true;
bool checkElse = false;
if (condTok && !Token::simpleMatch(condTok, ":"))
std::tie(checkThen, checkElse) = evalCond(condTok, isDoWhile ? endBlock->previous() : nullptr);
// exiting a do while(false)
if (checkElse && exit) {
if (hasJump(endBlock)) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
if (analyzer->isConditional() && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
}
return Progress::Continue;
}
Analyzer::Action bodyAnalysis = analyzeScope(endBlock);
Analyzer::Action allAnalysis = bodyAnalysis;
Analyzer::Action condAnalysis;
if (condTok) {
condAnalysis = analyzeRecursive(condTok);
allAnalysis |= condAnalysis;
}
if (stepTok)
allAnalysis |= analyzeRecursive(stepTok);
actions |= allAnalysis;
// do while(false) is not really a loop
if (checkElse && isDoWhile &&
(condTok->hasKnownIntValue() ||
(!bodyAnalysis.isModified() && !condAnalysis.isModified() && condAnalysis.isRead()))) {
if (updateScope(endBlock) == Progress::Break)
return Break();
return updateRecursive(condTok);
}
if (allAnalysis.isInconclusive()) {
if (!analyzer->lowerToInconclusive())
return Break(Analyzer::Terminate::Bail);
} else if (allAnalysis.isModified() || (exit && allAnalysis.isIdempotent())) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
}
if (condTok && !Token::simpleMatch(condTok, ":")) {
if (!isDoWhile || (!bodyAnalysis.isModified() && !bodyAnalysis.isIdempotent()))
if (updateRecursive(condTok) == Progress::Break)
return Break();
}
if (!checkThen && !checkElse && !isDoWhile && stopOnCondition(condTok) && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
// condition is false, we don't enter the loop
if (checkElse && !isDoWhile)
return Progress::Continue;
if (checkThen || isDoWhile) {
// Since we are re-entering the loop then assume the condition is true to update the state
if (exit)
analyzer->assume(condTok, true, Analyzer::Assume::Quiet | Analyzer::Assume::Absolute);
if (updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break)
return Break();
// If loop re-enters then it could be modified again
if (allAnalysis.isModified() && reentersLoop(endBlock, condTok, stepTok))
return Break(Analyzer::Terminate::Bail);
if (allAnalysis.isIncremental())
return Break(Analyzer::Terminate::Bail);
} else if (allAnalysis.isModified()) {
std::vector<ForwardTraversal> ftv = tryForkScope(endBlock, allAnalysis.isModified());
bool forkContinue = true;
for (ForwardTraversal& ft : ftv) {
if (condTok)
ft.analyzer->assume(condTok, false, Analyzer::Assume::Quiet);
if (ft.updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break)
forkContinue = false;
}
// TODO: Don't bail on missing condition
if (!condTok)
return Break(Analyzer::Terminate::Bail);
if (analyzer->isConditional() && stopUpdates())
return Break(Analyzer::Terminate::Conditional);
analyzer->assume(condTok, false);
if (forkContinue) {
for (ForwardTraversal& ft : ftv) {
if (!ft.actions.isIncremental())
ft.updateAllPaths(endBlock, endToken);
}
}
if (allAnalysis.isIncremental())
return Break(Analyzer::Terminate::Bail);
} else {
if (updateInnerLoop(endBlock, stepTok, condTok) == Progress::Break)
return Progress::Break;
if (allAnalysis.isIncremental())
return Break(Analyzer::Terminate::Bail);
}
return Progress::Continue;
}
Progress updateLoopExit(const Token* endToken,
Token* endBlock,
Token* condTok,
Token* initTok = nullptr,
Token* stepTok = nullptr) {
return updateLoop(endToken, endBlock, condTok, initTok, stepTok, true);
}
void updateScopeState(const Token* endBlock)
{
assert(endBlock->link());
const Token* ctx = endBlock->link()->previous();
if (Token::simpleMatch(ctx, ")"))
ctx = ctx->link()->previous();
if (ctx)
analyzer->updateState(ctx);
}
Progress updateScope(Token* endBlock, int depth = 20)
{
if (!endBlock)
return Break();
updateScopeState(endBlock);
return updateRange(endBlock->link(), endBlock, false, depth);
}
void updateAllScopePaths(Token* endBlock, int depth = 20)
{
if (!endBlock)
return;
updateScopeState(endBlock);
updateAllPaths(endBlock->link(), endBlock, depth);
}
// Walk this path and every path that parts from it to the end of the range
Outcome updatePaths(Token* start, const Token* end, int depth)
{
return outcome(updateRange(start, end, true, depth));
}
// As updatePaths(), and this traversal gets the joint result of the paths. It must not go on
// after the range.
void updateAllPaths(Token* start, const Token* end, int depth = 20) {
setJointResult(updatePaths(start, end, depth), end);
}
// As updateAllPaths(), for a caller that may go on with the value after the range. The joint
// result alone would drop a value that this path keeps to the end while a path that parted
// from it for good changes it or stops (e.g. 'if (g()) w = 1; if (w) x = 1;' when g()
// returns false).
Analyzer::Result updateRangeResult(Token* start, const Token* end) {
const Progress p = updateRange(start, end, true);
const bool unchanged = p == Progress::Continue && !actions.isModified();
setJointResult(outcome(p), end);
if (unchanged && (actions.isModified() || terminate != Analyzer::Terminate::None))
terminate = Analyzer::Terminate::Partial;
return Analyzer::Result{actions, terminate};
}
void setJointResult(const Outcome& paths, const Token* end) {
// A path that stopped without an escape was not followed to one, but the code can show
// that there is no way to the end of the range
const bool escapes = paths.allEscape() ||
(paths.reached == 0 && paths.hasEscape() && isReturnScope(end, settings().library));
actions = paths.action;
terminate = escapes ? Analyzer::Terminate::Escape : paths.worst();
}
/**
* Walk this path from start to end.
* @param split the paths may part for good at an undecided if: nothing goes on after the
* range on this traversal. Otherwise one path has to stand for all of them at its end.
* @throws InternalError thrown on cyclic analysis
*/
Progress updateRange(Token* start, const Token* end, bool split, int depth = 20) {
if (depth < 0)
return Break(Analyzer::Terminate::Bail);
std::size_t i = 0;
for (Token* tok = start; precedes(tok, end); tok = tok->next()) {
Token* next = nullptr;
if (tok->index() <= i)
throw InternalError(tok, "Cyclic forward analysis.");
i = tok->index();
if (tok->link()) {
// Skip casts..
if (tok->str() == "(" && !tok->astOperand2() && tok->isCast()) {
tok = tok->link();
continue;
}
// Skip template arguments..
if (tok->str() == "<") {
tok = tok->link();
continue;
}
}
// Evaluate RHS of assignment before LHS
if (Token* assignTok = assignExpr(tok)) {
if (updateRecursive(assignTok) == Progress::Break)
return Break();
tok = nextAfterAstRightmostLeaf(assignTok);
if (!tok)
return Break();
} else if (Token::simpleMatch(tok, ") {") && Token::Match(tok->link()->previous(), "for|while (") &&
!Token::simpleMatch(tok->link()->astOperand2(), ":")) {
// In the middle of a loop structure so bail
return Break(Analyzer::Terminate::Bail);
} else if (tok->str() == ";" && tok->astParent()) {
Token* top = tok->astTop();
if (Token::Match(top->previous(), "for|while (") && Token::simpleMatch(top->link(), ") {")) {
Token* endCond = top->link();
Token* endBlock = endCond->linkAt(1);
Token* condTok = getCondTok(top);
Token* stepTok = getStepTok(top);
// The semicolon should belong to the initTok otherwise something went wrong, so just bail
if (tok->astOperand2() != condTok && !Token::simpleMatch(tok->astOperand2(), ";"))
return Break(Analyzer::Terminate::Bail);
if (updateLoop(end, endBlock, condTok, nullptr, stepTok) == Progress::Break)
return Break();
}
} else if (tok->str() == "break") {
const Token *scopeEndToken = findNextTokenFromBreak(tok);
if (!scopeEndToken)
return Break();
tok = skipTo(tok, scopeEndToken, end);
if (!precedes(tok, end))
return Break(Analyzer::Terminate::Escape);
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
// TODO: Don't break, instead move to the outer scope
if (!tok)
return Break();
} else if (!tok->variable() && (Token::Match(tok, "%name% :") || tok->str() == "case")) {
if (!analyzer->lowerToPossible())
return Break(Analyzer::Terminate::Bail);
} else if (tok->link() && tok->str() == "}" && tok == tok->scope()->bodyEnd) { // might be an init list
const Scope* scope = tok->scope();
if (contains({ScopeType::eDo, ScopeType::eFor, ScopeType::eWhile, ScopeType::eIf, ScopeType::eElse, ScopeType::eSwitch}, scope->type)) {
const bool inElse = scope->type == ScopeType::eElse;
const bool inDoWhile = scope->type == ScopeType::eDo;
const bool inLoop = contains({ScopeType::eDo, ScopeType::eFor, ScopeType::eWhile}, scope->type);