-
Notifications
You must be signed in to change notification settings - Fork 39
/
pointer_nullability_analysis.cc
1606 lines (1419 loc) · 64.7 KB
/
pointer_nullability_analysis.cc
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
// Part of the Crubit project, under the Apache License v2.0 with LLVM
// Exceptions. See /LICENSE for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
#include "nullability/pointer_nullability_analysis.h"
#include <cassert>
#include <functional>
#include <optional>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/log/check.h"
#include "nullability/pointer_nullability.h"
#include "nullability/pointer_nullability_lattice.h"
#include "nullability/pointer_nullability_matchers.h"
#include "nullability/type_nullability.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/FlowSensitive/Arena.h"
#include "clang/Analysis/FlowSensitive/CFGMatchSwitch.h"
#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
#include "clang/Analysis/FlowSensitive/StorageLocation.h"
#include "clang/Analysis/FlowSensitive/Value.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/Specifiers.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
namespace clang::tidy::nullability {
using ast_matchers::MatchFinder;
using dataflow::Arena;
using dataflow::BoolValue;
using dataflow::CFGMatchSwitchBuilder;
using dataflow::ComparisonResult;
using dataflow::DataflowAnalysisContext;
using dataflow::Environment;
using dataflow::Formula;
using dataflow::PointerValue;
using dataflow::RecordStorageLocation;
using dataflow::StorageLocation;
using dataflow::TransferState;
using dataflow::Value;
#define DEBUG_TYPE "pointer_nullability_analysis.cc"
namespace {
TypeNullability prepend(NullabilityKind Head, const TypeNullability &Tail) {
TypeNullability Result = {Head};
Result.insert(Result.end(), Tail.begin(), Tail.end());
return Result;
}
void computeNullability(absl::Nonnull<const Expr *> E,
TransferState<PointerNullabilityLattice> &State,
std::function<TypeNullability()> Compute) {
(void)State.Lattice.insertExprNullabilityIfAbsent(E, [&] {
auto Nullability = Compute();
if (unsigned ExpectedSize = countPointersInType(E);
ExpectedSize != Nullability.size()) {
// A nullability vector must have one entry per pointer in the type.
// If this is violated, we probably failed to handle some AST node.
LLVM_DEBUG({
llvm::dbgs()
<< "=== Nullability vector has wrong number of entries: ===\n";
llvm::dbgs() << "Expression: \n";
dump(E, llvm::dbgs());
llvm::dbgs() << "\nNullability (" << Nullability.size()
<< " pointers): " << nullabilityToString(Nullability)
<< "\n";
llvm::dbgs() << "\nType (" << ExpectedSize << " pointers): \n";
dump(exprType(E), llvm::dbgs());
llvm::dbgs() << "=================================\n";
});
// We can't meaningfully interpret the vector, so discard it.
// TODO: fix all broken cases and upgrade to CHECK or DCHECK or so.
Nullability.assign(ExpectedSize, NullabilityKind::Unspecified);
}
return Nullability;
});
}
// Returns the computed nullability for a subexpr of the current expression.
// This is always available as we compute bottom-up.
const TypeNullability &getNullabilityForChild(
absl::Nonnull<const Expr *> E,
TransferState<PointerNullabilityLattice> &State) {
return State.Lattice.insertExprNullabilityIfAbsent(E, [&] {
// Since we process child nodes before parents, we should already have
// computed the child nullability. However, this is not true in all test
// cases. So, we return unspecified nullability annotations.
// TODO: fix this issue, and CHECK() instead.
LLVM_DEBUG({
llvm::dbgs() << "=== Missing child nullability: ===\n";
dump(E, llvm::dbgs());
llvm::dbgs() << "==================================\n";
});
return unspecifiedNullability(E);
});
}
/// Compute the nullability annotation of type `T`, which contains types
/// originally written as a class template type parameter.
///
/// Example:
///
/// \code
/// template <typename F, typename S>
/// struct pair {
/// S *_Nullable getNullablePtrToSecond();
/// };
/// \endcode
///
/// Consider the following member call:
///
/// \code
/// pair<int *, int *_Nonnull> x;
/// x.getNullablePtrToSecond();
/// \endcode
///
/// The class template specialization `x` has the following substitutions:
///
/// F=int *, whose nullability is [_Unspecified]
/// S=int * _Nonnull, whose nullability is [_Nonnull]
///
/// The return type of the member call `x.getNullablePtrToSecond()` is
/// S * _Nullable.
///
/// When we call `substituteNullabilityAnnotationsInClassTemplate` with the type
/// `S * _Nullable` and the `base` node of the member call (in this case, a
/// `DeclRefExpr`), it returns the nullability of the given type after applying
/// substitutions, which in this case is [_Nullable, _Nonnull].
TypeNullability substituteNullabilityAnnotationsInClassTemplate(
QualType T, const TypeNullability &BaseNullabilityAnnotations,
QualType BaseType) {
return getNullabilityAnnotationsFromType(
T,
[&](const SubstTemplateTypeParmType *ST)
-> std::optional<TypeNullability> {
// The class specialization that is BaseType and owns ST.
const ClassTemplateSpecializationDecl *Specialization = nullptr;
if (const auto *RT = BaseType->getAs<RecordType>())
Specialization =
dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
// TODO: handle nested templates, where associated decl != base type
// (e.g. PointerNullabilityTest.MemberFunctionTemplateOfTemplateStruct)
if (!Specialization || Specialization != ST->getAssociatedDecl())
return std::nullopt;
// TODO: The code below does not deal correctly with partial
// specializations. We should eventually handle these, but for now, just
// bail out.
if (isa<ClassTemplatePartialSpecializationDecl>(
ST->getReplacedParameter()->getDeclContext()))
return std::nullopt;
unsigned ArgIndex = ST->getIndex();
auto TemplateArgs = Specialization->getTemplateArgs().asArray();
// TODO: If the type was substituted from a pack template argument,
// we must find the slice that pertains to this particular type.
// For now, just give up on resugaring this type.
if (ST->getPackIndex().has_value()) return std::nullopt;
unsigned PointerCount =
countPointersInType(Specialization->getDeclContext());
for (auto TA : TemplateArgs.take_front(ArgIndex)) {
PointerCount += countPointersInType(TA);
}
unsigned SliceSize = countPointersInType(TemplateArgs[ArgIndex]);
return ArrayRef(BaseNullabilityAnnotations)
.slice(PointerCount, SliceSize)
.vec();
});
}
/// Compute nullability annotations of `T`, which might contain template type
/// variable substitutions bound by the call `CE`.
///
/// Example:
///
/// \code
/// template<typename F, typename S>
/// std::pair<S, F> flip(std::pair<F, S> p);
/// \endcode
///
/// Consider the following CallExpr:
///
/// \code
/// flip<int * _Nonnull, int * _Nullable>(std::make_pair(&x, &y));
/// \endcode
///
/// This CallExpr has the following substitutions:
/// F=int * _Nonnull, whose nullability is [_Nonnull]
/// S=int * _Nullable, whose nullability is [_Nullable]
///
/// The return type of this CallExpr is `std::pair<S, F>`.
///
/// When we call `substituteNullabilityAnnotationsInFunctionTemplate` with the
/// type `std::pair<S, F>` and the above CallExpr, it returns the nullability
/// the given type after applying substitutions, which in this case is
/// [_Nullable, _Nonnull].
TypeNullability substituteNullabilityAnnotationsInFunctionTemplate(
QualType T, absl::Nonnull<const CallExpr *> CE) {
return getNullabilityAnnotationsFromType(
T,
[&](const SubstTemplateTypeParmType *ST)
-> std::optional<TypeNullability> {
auto *DRE = dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreImpCasts());
if (DRE == nullptr) return std::nullopt;
// TODO: Handle calls that use template argument deduction.
// Does this refer to a parameter of the function template?
// If not (e.g. nested templates, template specialization types in the
// return value), we handle the desugaring elsewhere.
auto *ReferencedFunction = dyn_cast<FunctionDecl>(DRE->getDecl());
if (!ReferencedFunction) return std::nullopt;
if (ReferencedFunction->getPrimaryTemplate() != ST->getAssociatedDecl())
return std::nullopt;
// Some or all of the template arguments may be deduced, and we won't
// see those on the `DeclRefExpr`. If the template argument was deduced,
// we don't have any sugar for it.
// TODO(b/268348533): Can we somehow obtain it from the function param
// it was deduced from?
// TODO(b/268345783): This check, as well as the index into
// `template_arguments` below, may be incorrect in the presence of
// parameters packs. In function templates, parameter packs may appear
// anywhere in the parameter list. The index may therefore refer to one
// of the pack arguments, but we might incorrectly interpret it as
// referring to an argument that follows the pack.
if (ST->getIndex() >= DRE->template_arguments().size())
return std::nullopt;
TypeSourceInfo *TSI =
DRE->template_arguments()[ST->getIndex()].getTypeSourceInfo();
if (TSI == nullptr) return std::nullopt;
return getNullabilityAnnotationsFromType(TSI->getType());
});
}
PointerTypeNullability getPointerTypeNullability(
absl::Nonnull<const Expr *> E, PointerNullabilityAnalysis::Lattice &L) {
// TODO: handle this in non-flow-sensitive transfer instead
if (auto FromClang = E->getType()->getNullability();
FromClang && *FromClang != NullabilityKind::Unspecified)
return *FromClang;
if (const auto *NonFlowSensitive = L.getExprNullability(E)) {
if (!NonFlowSensitive->empty())
// Return the nullability of the topmost pointer in the type.
return NonFlowSensitive->front();
}
return NullabilityKind::Unspecified;
}
void initPointerFromTypeNullability(
PointerValue &PointerVal, absl::Nonnull<const Expr *> E,
TransferState<PointerNullabilityLattice> &State) {
initPointerNullState(PointerVal, State.Env.getDataflowAnalysisContext(),
getPointerTypeNullability(E, State.Lattice));
}
/// Returns a new pointer value referencing the same location as `PointerVal`
/// but with any "top" nullability properties unpacked into fresh atoms.
/// This is analogous to the unpacking done on `TopBoolValue`s in the framework.
/// TODO(mboehme): When we add support for smart pointers, this function will
/// also need to be called when accessing the `PointerValue` that underlies the
/// smart pointer.
absl::Nullable<PointerValue *> unpackPointerValue(PointerValue &PointerVal,
Environment &Env) {
auto [FromNullable, Null] = getPointerNullState(PointerVal);
if (FromNullable && Null) return nullptr;
auto &A = Env.getDataflowAnalysisContext().arena();
auto &NewPointerVal = Env.create<PointerValue>(PointerVal.getPointeeLoc());
initPointerNullState(NewPointerVal, Env.getDataflowAnalysisContext());
auto NewNullability = getPointerNullState(NewPointerVal);
assert(NewNullability.FromNullable != nullptr);
assert(NewNullability.IsNull != nullptr);
if (FromNullable != nullptr)
Env.assume(A.makeEquals(*NewNullability.FromNullable, *FromNullable));
if (Null != nullptr) Env.assume(A.makeEquals(*NewNullability.IsNull, *Null));
return &NewPointerVal;
}
void setToPointerWithNullability(StorageLocation &PtrLoc, NullabilityKind NK,
Environment &Env) {
auto &Val = *cast<PointerValue>(Env.createValue(PtrLoc.getType()));
initPointerNullState(Val, Env.getDataflowAnalysisContext(), NK);
Env.setValue(PtrLoc, Val);
}
void transferValue_NullPointer(
absl::Nonnull<const Expr *> NullPointer, const MatchFinder::MatchResult &,
TransferState<PointerNullabilityLattice> &State) {
if (auto *PointerVal = getPointerValueFromExpr(NullPointer, State.Env)) {
initNullPointer(*PointerVal, State.Env.getDataflowAnalysisContext());
}
}
void transferValue_NotNullPointer(
absl::Nonnull<const Expr *> NotNullPointer,
const MatchFinder::MatchResult &,
TransferState<PointerNullabilityLattice> &State) {
if (auto *PointerVal = getPointerValueFromExpr(NotNullPointer, State.Env)) {
initPointerNullState(*PointerVal, State.Env.getDataflowAnalysisContext(),
NullabilityKind::NonNull);
}
}
bool isStdWeakPtrType(QualType Ty) {
const CXXRecordDecl *RD = Ty.getCanonicalType()->getAsCXXRecordDecl();
if (RD == nullptr) return false;
if (!RD->getDeclContext()->isStdNamespace()) return false;
const IdentifierInfo *ID = RD->getIdentifier();
if (ID == nullptr) return false;
return ID->getName() == "weak_ptr";
}
void transferValue_SmartPointerConstructor(
const CXXConstructExpr *Ctor, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
RecordStorageLocation &Loc = State.Env.getResultObjectLocation(*Ctor);
// Create a `RecordValue`, associate it with the `Loc` and the expression.
State.Env.setValue(*Ctor, refreshRecordValue(Loc, State.Env));
// Default and `nullptr_t` constructor.
if (Ctor->getConstructor()->isDefaultConstructor() ||
(Ctor->getNumArgs() >= 1 &&
Ctor->getArg(0)->getType()->isNullPtrType())) {
setSmartPointerToNull(Loc, State.Env);
return;
}
// Construct from raw pointer.
if (Ctor->getNumArgs() >= 1 &&
isSupportedRawPointerType(Ctor->getArg(0)->getType())) {
setSmartPointerValue(
Loc, getPointerValueFromExpr(Ctor->getArg(0), State.Env), State.Env);
return;
}
// Copy or move from an existing smart pointer.
if (Ctor->getNumArgs() >= 1 &&
isSupportedSmartPointerType(Ctor->getArg(0)->getType())) {
auto *SrcLoc = cast_or_null<RecordStorageLocation>(
State.Env.getStorageLocation(*Ctor->getArg(0)));
if (Ctor->getNumArgs() == 2 &&
isSupportedRawPointerType(Ctor->getArg(1)->getType())) {
// `shared_ptr` aliasing constructor.
setSmartPointerValue(
Loc, getPointerValueFromExpr(Ctor->getArg(1), State.Env), State.Env);
} else {
setSmartPointerValue(
Loc, getPointerValueFromSmartPointer(SrcLoc, State.Env), State.Env);
}
if (Ctor->getConstructor()
->getParamDecl(0)
->getType()
->isRValueReferenceType() &&
SrcLoc != nullptr) {
setSmartPointerToNull(*SrcLoc, State.Env);
}
return;
}
// Construct from `weak_ptr`. This throws if the `weak_ptr` is empty, so we
// can assume the `shared_ptr` is non-null if the constructor returns.
if (Ctor->getNumArgs() == 1 && isStdWeakPtrType(Ctor->getArg(0)->getType()))
setToPointerWithNullability(Loc.getSyntheticField(PtrField),
NullabilityKind::NonNull, State.Env);
}
void transferValue_SmartPointerAssignment(
const CXXOperatorCallExpr *OpCall, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
auto *Loc = cast_or_null<RecordStorageLocation>(
State.Env.getStorageLocation(*OpCall->getArg(0)));
if (Loc == nullptr) return;
if (OpCall->getArg(1)->getType()->isNullPtrType()) {
setSmartPointerToNull(*Loc, State.Env);
return;
}
auto *SrcLoc = cast_or_null<RecordStorageLocation>(
State.Env.getStorageLocation(*OpCall->getArg(1)));
setSmartPointerValue(*Loc, getPointerValueFromSmartPointer(SrcLoc, State.Env),
State.Env);
// If this is the move assignment operator, set the source to null.
auto *Method = dyn_cast_or_null<CXXMethodDecl>(OpCall->getCalleeDecl());
if (Method != nullptr &&
Method->getParamDecl(0)->getType()->isRValueReferenceType()) {
setSmartPointerToNull(*SrcLoc, State.Env);
}
}
void transferValue_SmartPointerReleaseCall(
const CXXMemberCallExpr *MCE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
RecordStorageLocation *Loc = getImplicitObjectLocation(*MCE, State.Env);
if (Loc == nullptr) return;
StorageLocation &PtrLoc = Loc->getSyntheticField(PtrField);
if (auto *Val = cast_or_null<PointerValue>(State.Env.getValue(PtrLoc)))
State.Env.setValue(*MCE, *Val);
State.Env.setValue(
PtrLoc, createNullPointer(PtrLoc.getType()->getPointeeType(), State.Env));
}
void transferValue_SmartPointerResetCall(
const CXXMemberCallExpr *MCE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
RecordStorageLocation *Loc = getImplicitObjectLocation(*MCE, State.Env);
if (Loc == nullptr) return;
// Zero-arg and `nullptr_t` overloads, as well as single-argument constructor
// with default argument.
if (MCE->getNumArgs() == 0 ||
(MCE->getNumArgs() == 1 && MCE->getArg(0)->getType()->isNullPtrType()) ||
(MCE->getNumArgs() == 1 && MCE->getArg(0)->isDefaultArgument())) {
setSmartPointerToNull(*Loc, State.Env);
return;
}
setSmartPointerValue(*Loc, getPointerValueFromExpr(MCE->getArg(0), State.Env),
State.Env);
}
void swapSmartPointers(RecordStorageLocation *Loc1, RecordStorageLocation *Loc2,
Environment &Env) {
PointerValue *Val1 = getPointerValueFromSmartPointer(Loc1, Env);
PointerValue *Val2 = getPointerValueFromSmartPointer(Loc2, Env);
if (Loc1) setSmartPointerValue(*Loc1, Val2, Env);
if (Loc2) setSmartPointerValue(*Loc2, Val1, Env);
}
void transferValue_SmartPointerMemberSwapCall(
const CXXMemberCallExpr *MCE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
swapSmartPointers(getImplicitObjectLocation(*MCE, State.Env),
cast_or_null<RecordStorageLocation>(
State.Env.getStorageLocation(*MCE->getArg(0))),
State.Env);
}
void transferValue_SmartPointerFreeSwapCall(
const CallExpr *CE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
swapSmartPointers(cast_or_null<RecordStorageLocation>(
State.Env.getStorageLocation(*CE->getArg(0))),
cast_or_null<RecordStorageLocation>(
State.Env.getStorageLocation(*CE->getArg(1))),
State.Env);
}
void transferValue_SmartPointerGetCall(
const CXXMemberCallExpr *MCE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
if (Value *Val = getPointerValueFromSmartPointer(
getImplicitObjectLocation(*MCE, State.Env), State.Env))
State.Env.setValue(*MCE, *Val);
}
void transferValue_SmartPointerBoolConversionCall(
const CXXMemberCallExpr *MCE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
if (PointerValue *Val = getPointerValueFromSmartPointer(
getImplicitObjectLocation(*MCE, State.Env), State.Env)) {
if (const Formula *IsNull = getPointerNullState(*Val).IsNull)
State.Env.setValue(
*MCE, State.Env.makeNot(State.Env.arena().makeBoolValue(*IsNull)));
}
}
void transferValue_SmartPointerOperatorStar(
const CXXOperatorCallExpr *OpCall, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
if (PointerValue *Val =
getPointerValueFromSmartPointerExpr(OpCall->getArg(0), State.Env)) {
State.Env.setStorageLocation(*OpCall, Val->getPointeeLoc());
}
}
void transferValue_SmartPointerOperatorArrow(
const CXXOperatorCallExpr *OpCall, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
if (PointerValue *Val =
getPointerValueFromSmartPointerExpr(OpCall->getArg(0), State.Env)) {
State.Env.setValue(*OpCall, *Val);
}
}
void transferValue_SmartPointerFactoryCall(
const CallExpr *CE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
RecordStorageLocation &Loc = State.Env.getResultObjectLocation(*CE);
// Create a `RecordValue`, associate it with the `Loc` and the expression.
State.Env.setValue(*CE, refreshRecordValue(Loc, State.Env));
StorageLocation &PtrLoc = Loc.getSyntheticField(PtrField);
setToPointerWithNullability(PtrLoc, NullabilityKind::NonNull, State.Env);
}
void transferValue_SmartPointerComparisonOpCall(
const CXXOperatorCallExpr *OpCall, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
// Formula representing an equality (`==`) comparison of the two operands.
// If the operator is `!=`, this will need to be negated below.
const Formula *EqualityFormula = nullptr;
bool NullPtr1 = OpCall->getArg(0)->getType()->isNullPtrType();
bool NullPtr2 = OpCall->getArg(1)->getType()->isNullPtrType();
assert(!NullPtr1 || !NullPtr2);
PointerValue *Val1 = nullptr;
if (!NullPtr1)
Val1 = getPointerValueFromSmartPointerExpr(OpCall->getArg(0), State.Env);
PointerValue *Val2 = nullptr;
if (!NullPtr2)
Val2 = getPointerValueFromSmartPointerExpr(OpCall->getArg(1), State.Env);
if (NullPtr1) {
if (Val2 == nullptr) return;
EqualityFormula = getPointerNullState(*Val2).IsNull;
} else if (NullPtr2) {
if (Val1 == nullptr) return;
EqualityFormula = getPointerNullState(*Val1).IsNull;
} else {
if (Val1 == nullptr || Val2 == nullptr) return;
EqualityFormula = &State.Env.arena().makeLiteral(&Val1->getPointeeLoc() ==
&Val2->getPointeeLoc());
}
if (EqualityFormula == nullptr) return;
BoolValue &EqualityValue = State.Env.arena().makeBoolValue(*EqualityFormula);
if (OpCall->getOperator() == OO_EqualEqual)
State.Env.setValue(*OpCall, EqualityValue);
else
State.Env.setValue(*OpCall, State.Env.makeNot(EqualityValue));
}
void transferValue_SharedPtrCastCall(
const CallExpr *CE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
if (!smartPointersEnabled()) return;
Environment &Env = State.Env;
DataflowAnalysisContext &Ctx = Env.getDataflowAnalysisContext();
Arena &A = Env.arena();
auto *Callee = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
if (Callee == nullptr) return;
auto *SrcLoc = cast_or_null<RecordStorageLocation>(
Env.getStorageLocation(*CE->getArg(0)));
if (SrcLoc == nullptr) return;
StorageLocation &SrcPtrLoc = SrcLoc->getSyntheticField(PtrField);
auto *SrcPtrVal = cast_or_null<PointerValue>(Env.getValue(SrcPtrLoc));
if (SrcPtrVal == nullptr) return;
RecordStorageLocation &DestLoc = Env.getResultObjectLocation(*CE);
// Create a `RecordValue`, associate it with the `DestLoc` and the expression.
Env.setValue(*CE, refreshRecordValue(DestLoc, Env));
StorageLocation &DestPtrLoc = DestLoc.getSyntheticField(PtrField);
if (Callee->getName() == "const_pointer_cast") {
// A `const_pointer_cast` will definitely produce a pointer with the same
// storage location as the source, so we can simply copy the underlying
// pointer value.
Env.setValue(DestPtrLoc, *SrcPtrVal);
} else {
auto &DestPtrVal =
*cast<PointerValue>(Env.createValue(DestPtrLoc.getType()));
initPointerNullState(DestPtrVal, Ctx);
State.Env.setValue(DestPtrLoc, DestPtrVal);
PointerNullState SrcNullability = getPointerNullState(*SrcPtrVal);
PointerNullState DestNullability = getPointerNullState(DestPtrVal);
assert(DestNullability.IsNull != nullptr);
assert(DestNullability.FromNullable != nullptr);
if (Callee->getName() == "dynamic_pointer_cast") {
// A `dynamic_pointer_cast` may fail. So source `IsNull` implies
// destination `IsNull` (but not the other way around), and the result is
// always nullable.
if (SrcNullability.IsNull != nullptr)
Env.assume(
A.makeImplies(*SrcNullability.IsNull, *DestNullability.IsNull));
Env.assume(*DestNullability.FromNullable);
} else {
if (SrcNullability.IsNull != nullptr)
Env.assume(
A.makeEquals(*SrcNullability.IsNull, *DestNullability.IsNull));
if (SrcNullability.FromNullable != nullptr)
Env.assume(A.makeEquals(*SrcNullability.FromNullable,
*DestNullability.FromNullable));
}
}
// Is this an overload taking an rvalue reference?
if (Callee->getParamDecl(0)->getType()->isRValueReferenceType()) {
if (Callee->getName() == "dynamic_pointer_cast") {
// `dynamic_pointer_cast` sets its argument to null only if the cast
// succeeded. So if the argument wasn't yet nullable, replace it with a
// new nullable pointer.
PointerNullState SrcNullability = getPointerNullState(*SrcPtrVal);
if (SrcNullability.FromNullable == nullptr ||
!Env.proves(*SrcNullability.FromNullable))
setToPointerWithNullability(SrcPtrLoc, NullabilityKind::Nullable,
State.Env);
} else {
setSmartPointerToNull(*SrcLoc, State.Env);
}
}
}
void transferValue_WeakPtrLockCall(
const CXXMemberCallExpr *MCE, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
if (!smartPointersEnabled()) return;
RecordStorageLocation &Loc = State.Env.getResultObjectLocation(*MCE);
// Create a `RecordValue`, associate it with the `Loc` and the expression.
State.Env.setValue(*MCE, refreshRecordValue(Loc, State.Env));
StorageLocation &PtrLoc = Loc.getSyntheticField(PtrField);
setToPointerWithNullability(PtrLoc, NullabilityKind::Nullable, State.Env);
}
void transferValue_SmartPointer(
const Expr *PointerExpr, const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
auto *Loc = cast_or_null<RecordStorageLocation>(
State.Env.getStorageLocation(*PointerExpr));
if (Loc == nullptr) {
Loc = &cast<RecordStorageLocation>(
State.Env.createStorageLocation(*PointerExpr));
State.Env.setStorageLocation(*PointerExpr, *Loc);
}
StorageLocation &PtrLoc = Loc->getSyntheticField(PtrField);
auto *Val = cast_or_null<PointerValue>(State.Env.getValue(PtrLoc));
if (Val == nullptr) {
Val = cast<PointerValue>(State.Env.createValue(PtrLoc.getType()));
State.Env.setValue(PtrLoc, *Val);
}
initPointerFromTypeNullability(*Val, PointerExpr, State);
}
void transferValue_Pointer(absl::Nonnull<const Expr *> PointerExpr,
const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
auto *PointerVal = getPointerValueFromExpr(PointerExpr, State.Env);
if (!PointerVal) return;
initPointerFromTypeNullability(*PointerVal, PointerExpr, State);
if (const auto *Cast = dyn_cast<CastExpr>(PointerExpr);
Cast && Cast->getCastKind() == CK_LValueToRValue) {
PointerValue *NewPointerVal = unpackPointerValue(*PointerVal, State.Env);
if (!NewPointerVal) return;
if (StorageLocation *Loc =
State.Env.getStorageLocation(*Cast->getSubExpr()))
State.Env.setValue(*Loc, *NewPointerVal);
State.Env.setValue(*PointerExpr, *NewPointerVal);
}
}
// TODO(b/233582219): Implement promotion of nullability for initially
// unknown pointers when there is evidence that it is nullable, for example
// when the pointer is compared to nullptr, or casted to boolean.
void transferValue_NullCheckComparison(
absl::Nonnull<const BinaryOperator *> BinaryOp,
const MatchFinder::MatchResult &result,
TransferState<PointerNullabilityLattice> &State) {
auto &A = State.Env.arena();
auto *LHS = getPointerValueFromExpr(BinaryOp->getLHS(), State.Env);
auto *RHS = getPointerValueFromExpr(BinaryOp->getRHS(), State.Env);
if (!LHS || !RHS) return;
if (!hasPointerNullState(*LHS) || !hasPointerNullState(*RHS)) return;
auto *LHSNull = getPointerNullState(*LHS).IsNull;
auto *RHSNull = getPointerNullState(*RHS).IsNull;
// If the null state of either pointer is "top", the result of the comparison
// is a top bool, and we don't have any knowledge we can add to the flow
// condition.
if (LHSNull == nullptr || RHSNull == nullptr) {
State.Env.setValue(*BinaryOp, A.makeTopValue());
return;
}
// Special case: Are we comparing against `nullptr`?
// We can avoid modifying the flow condition in this case and simply propagate
// the nullability of the other operand (potentially with a negation).
if (LHSNull == &A.makeLiteral(true)) {
if (BinaryOp->getOpcode() == BO_EQ)
State.Env.setValue(*BinaryOp, A.makeBoolValue(*RHSNull));
else
State.Env.setValue(*BinaryOp, A.makeBoolValue(A.makeNot(*RHSNull)));
return;
}
if (RHSNull == &A.makeLiteral(true)) {
if (BinaryOp->getOpcode() == BO_EQ)
State.Env.setValue(*BinaryOp, A.makeBoolValue(*LHSNull));
else
State.Env.setValue(*BinaryOp, A.makeBoolValue(A.makeNot(*LHSNull)));
return;
}
// Boolean representing the comparison between the two pointer values,
// automatically created by the dataflow framework.
auto &PointerComparison =
cast<BoolValue>(State.Env.getValue(*BinaryOp))->formula();
CHECK(BinaryOp->getOpcode() == BO_EQ || BinaryOp->getOpcode() == BO_NE);
auto &PointerEQ = BinaryOp->getOpcode() == BO_EQ
? PointerComparison
: A.makeNot(PointerComparison);
auto &PointerNE = BinaryOp->getOpcode() == BO_EQ
? A.makeNot(PointerComparison)
: PointerComparison;
// nullptr == nullptr
State.Env.assume(A.makeImplies(A.makeAnd(*LHSNull, *RHSNull), PointerEQ));
// nullptr != notnull
State.Env.assume(
A.makeImplies(A.makeAnd(*LHSNull, A.makeNot(*RHSNull)), PointerNE));
// notnull != nullptr
State.Env.assume(
A.makeImplies(A.makeAnd(A.makeNot(*LHSNull), *RHSNull), PointerNE));
}
void transferValue_NullCheckImplicitCastPtrToBool(
absl::Nonnull<const Expr *> CastExpr, const MatchFinder::MatchResult &,
TransferState<PointerNullabilityLattice> &State) {
auto &A = State.Env.arena();
auto *PointerVal =
getPointerValueFromExpr(CastExpr->IgnoreImplicit(), State.Env);
if (!PointerVal) return;
auto Nullability = getPointerNullState(*PointerVal);
if (Nullability.IsNull != nullptr)
State.Env.setValue(*CastExpr,
A.makeBoolValue(A.makeNot(*Nullability.IsNull)));
else
State.Env.setValue(*CastExpr, A.makeTopValue());
}
void initializeOutputParameter(absl::Nonnull<const Expr *> Arg,
dataflow::Environment &Env, QualType ParamTy) {
// When a function has an "output parameter" - a non-const pointer or
// reference to a pointer of unknown nullability - assume that the function
// may set the pointer to non-null.
//
// For example, in the following code sequence we assume that the function may
// modify the pointer in a way that makes a subsequent dereference safe:
//
// void maybeModify(int ** _Nonnull);
//
// int *p = nullptr;
// initializePointer(&p);
// *p; // safe
if (ParamTy.isNull()) return;
if (ParamTy->getPointeeType().isNull()) return;
if (!isSupportedRawPointerType(ParamTy->getPointeeType())) return;
if (ParamTy->getPointeeType().isConstQualified()) return;
// TODO(b/298200521): This should extend support to annotations that suggest
// different in/out state
TypeNullability InnerNullability =
getNullabilityAnnotationsFromType(ParamTy->getPointeeType());
if (InnerNullability.front().concrete() != NullabilityKind::Unspecified)
return;
StorageLocation *Loc = nullptr;
if (ParamTy->isPointerType()) {
if (PointerValue *OuterPointer = getPointerValueFromExpr(Arg, Env))
Loc = &OuterPointer->getPointeeLoc();
} else if (ParamTy->isReferenceType()) {
Loc = Env.getStorageLocation(*Arg);
}
if (Loc == nullptr) return;
auto *InnerPointer =
cast<PointerValue>(Env.createValue(ParamTy->getPointeeType()));
initPointerNullState(*InnerPointer, Env.getDataflowAnalysisContext(),
NullabilityKind::Unspecified);
Env.setValue(*Loc, *InnerPointer);
}
void transferValue_CallExpr(absl::Nonnull<const CallExpr *> CallExpr,
const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
// The dataflow framework itself does not create values for `CallExpr`s.
// However, we need these in some cases, so we produce them ourselves.
StorageLocation *Loc = nullptr;
if (CallExpr->isGLValue()) {
// The function returned a reference. Create a storage location for the
// expression so that if code creates a pointer from the reference, we will
// produce a `PointerValue`.
Loc = State.Env.getStorageLocation(*CallExpr);
if (!Loc) {
// This is subtle: We call `createStorageLocation(QualType)`, not
// `createStorageLocation(const Expr &)`, so that we create a new
// storage location every time.
Loc = &State.Env.createStorageLocation(CallExpr->getType());
State.Env.setStorageLocation(*CallExpr, *Loc);
}
}
if (isSupportedRawPointerType(CallExpr->getType())) {
// Create a pointer so that we can attach nullability to it and have the
// nullability propagate with the pointer.
auto *PointerVal = getPointerValueFromExpr(CallExpr, State.Env);
if (!PointerVal) {
PointerVal =
cast<PointerValue>(State.Env.createValue(CallExpr->getType()));
}
initPointerFromTypeNullability(*PointerVal, CallExpr, State);
if (Loc != nullptr)
State.Env.setValue(*Loc, *PointerVal);
else
// `Loc` is set iff `CallExpr` is a glvalue, so we know here that it must
// be a prvalue.
State.Env.setValue(*CallExpr, *PointerVal);
}
// Make output parameters (with unknown nullability) initialized to unknown.
const auto *FuncDecl = CallExpr->getDirectCallee();
if (!FuncDecl) return;
if (FuncDecl->getNumParams() != CallExpr->getNumArgs()) return;
if (auto *II = FuncDecl->getDeclName().getAsIdentifierInfo();
II && II->isStr("__assert_nullability")) {
return;
}
for (unsigned i = 0; i < CallExpr->getNumArgs(); ++i) {
const auto *Arg = CallExpr->getArg(i);
initializeOutputParameter(Arg, State.Env,
FuncDecl->getParamDecl(i)->getType());
}
}
void transferValue_AccessorCall(
absl::Nonnull<const CXXMemberCallExpr *> MCE,
const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
auto *member = Result.Nodes.getNodeAs<clang::ValueDecl>("member-decl");
PointerValue *PointerVal = nullptr;
if (dataflow::RecordStorageLocation *RecordLoc =
dataflow::getImplicitObjectLocation(*MCE, State.Env)) {
StorageLocation *Loc = RecordLoc->getChild(*member);
PointerVal = dyn_cast_or_null<PointerValue>(State.Env.getValue(*Loc));
}
if (!PointerVal) {
// Use value that may have been set by the builtin transfer function or by
// `ensurePointerHasValue()`.
PointerVal = getPointerValueFromExpr(MCE, State.Env);
}
if (PointerVal) {
State.Env.setValue(*MCE, *PointerVal);
initPointerFromTypeNullability(*PointerVal, MCE, State);
}
}
void transferValue_ConstMemberCall(
absl::Nonnull<const CXXMemberCallExpr *> MCE,
const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
if (!isSupportedRawPointerType(MCE->getType()) || !MCE->isPRValue()) {
// We can't handle it as a special case, but still need to handle it.
transferValue_CallExpr(MCE, Result, State);
return;
}
dataflow::RecordStorageLocation *RecordLoc =
dataflow::getImplicitObjectLocation(*MCE, State.Env);
if (RecordLoc == nullptr) {
// We can't handle it as a special case, but still need to handle it.
transferValue_CallExpr(MCE, Result, State);
return;
}
PointerValue *PointerVal =
State.Lattice.getConstMethodReturnValue(*RecordLoc, MCE, State.Env);
if (PointerVal) {
State.Env.setValue(*MCE, *PointerVal);
initPointerFromTypeNullability(*PointerVal, MCE, State);
}
}
void transferValue_NonConstMemberCall(
absl::Nonnull<const CXXMemberCallExpr *> MCE,
const MatchFinder::MatchResult &Result,
TransferState<PointerNullabilityLattice> &State) {
// When a non-const member function is called, reset all pointer-type fields
// of the implicit object.
if (dataflow::RecordStorageLocation *RecordLoc =
dataflow::getImplicitObjectLocation(*MCE, State.Env)) {
for (const auto [Field, FieldLoc] : RecordLoc->children()) {
if (!isSupportedRawPointerType(Field->getType())) continue;
Value *V = State.Env.createValue(Field->getType());
State.Env.setValue(*FieldLoc, *V);
}
State.Lattice.clearConstMethodReturnValues(*RecordLoc);
}
// The nullability of the Expr itself still needs to be handled.
transferValue_CallExpr(MCE, Result, State);
}
void transferType_DeclRefExpr(absl::Nonnull<const DeclRefExpr *> DRE,
const MatchFinder::MatchResult &MR,
TransferState<PointerNullabilityLattice> &State) {
computeNullability(DRE, State, [&] {
auto Nullability = getNullabilityAnnotationsFromType(DRE->getType());
State.Lattice.overrideNullabilityFromDecl(DRE->getDecl(), Nullability);
return Nullability;
});
}
void transferType_MemberExpr(absl::Nonnull<const MemberExpr *> ME,
const MatchFinder::MatchResult &MR,
TransferState<PointerNullabilityLattice> &State) {
computeNullability(ME, State, [&]() {
auto BaseNullability = getNullabilityForChild(ME->getBase(), State);
QualType MemberType = ME->getType();
// When a MemberExpr is a part of a member function call
// (a child of CXXMemberCallExpr), the MemberExpr models a
// partially-applied member function, which isn't a real C++ construct.
// The AST does not provide rich type information for such MemberExprs.
// Instead, the AST specifies a placeholder type, specifically
// BuiltinType::BoundMember. So we have to look at the type of the member
// function declaration.
if (ME->hasPlaceholderType(BuiltinType::BoundMember)) {
MemberType = ME->getMemberDecl()->getType();
}
auto Nullability = substituteNullabilityAnnotationsInClassTemplate(
MemberType, BaseNullability, ME->getBase()->getType());
State.Lattice.overrideNullabilityFromDecl(ME->getMemberDecl(), Nullability);
return Nullability;
});
}
void transferType_MemberCallExpr(
absl::Nonnull<const CXXMemberCallExpr *> MCE,
const MatchFinder::MatchResult &MR,
TransferState<PointerNullabilityLattice> &State) {
computeNullability(MCE, State, [&]() {
return ArrayRef(getNullabilityForChild(MCE->getCallee(), State))
.take_front(countPointersInType(MCE))
.vec();
});
}
void transferType_CastExpr(absl::Nonnull<const CastExpr *> CE,
const MatchFinder::MatchResult &MR,
TransferState<PointerNullabilityLattice> &State) {
computeNullability(CE, State, [&]() -> TypeNullability {
// Most casts that can convert ~unrelated types drop nullability in general.
// As a special case, preserve nullability of outer pointer types.
// For example, int* p; (void*)p; is a BitCast, but preserves nullability.
auto PreserveTopLevelPointers = [&](TypeNullability V) {
auto ArgNullability = getNullabilityForChild(CE->getSubExpr(), State);