-
Notifications
You must be signed in to change notification settings - Fork 48
/
Copy pathcollect_evidence.cc
1849 lines (1707 loc) · 77.6 KB
/
collect_evidence.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/inference/collect_evidence.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#include <memory>
#include <optional>
#include <string>
#include <string_view>
#include <utility>
#include <vector>
#include "absl/base/nullability.h"
#include "absl/container/flat_hash_map.h"
#include "absl/log/check.h"
#include "absl/strings/string_view.h"
#include "nullability/ast_helpers.h"
#include "nullability/inference/inferable.h"
#include "nullability/inference/inference.proto.h"
#include "nullability/inference/slot_fingerprint.h"
#include "nullability/loc_filter.h"
#include "nullability/macro_arg_capture.h"
#include "nullability/pointer_nullability.h"
#include "nullability/pointer_nullability_analysis.h"
#include "nullability/pointer_nullability_lattice.h"
#include "nullability/pragma.h"
#include "nullability/type_nullability.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Attrs.inc"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclBase.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclGroup.h"
#include "clang/AST/DeclTemplate.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprCXX.h"
#include "clang/AST/OperationKinds.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/Type.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Analysis/CFG.h"
#include "clang/Analysis/FlowSensitive/ASTOps.h"
#include "clang/Analysis/FlowSensitive/AdornedCFG.h"
#include "clang/Analysis/FlowSensitive/Arena.h"
#include "clang/Analysis/FlowSensitive/DataflowAnalysis.h"
#include "clang/Analysis/FlowSensitive/DataflowAnalysisContext.h"
#include "clang/Analysis/FlowSensitive/DataflowEnvironment.h"
#include "clang/Analysis/FlowSensitive/Formula.h"
#include "clang/Analysis/FlowSensitive/Solver.h"
#include "clang/Analysis/FlowSensitive/StorageLocation.h"
#include "clang/Analysis/FlowSensitive/Value.h"
#include "clang/Analysis/FlowSensitive/WatchedLiteralsSolver.h"
#include "clang/Basic/Builtins.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/OperatorKinds.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Index/USRGeneration.h"
#include "llvm/ADT/DenseSet.h"
#include "llvm/ADT/FunctionExtras.h"
#include "llvm/ADT/STLFunctionalExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
namespace clang::tidy::nullability {
using ::clang::dataflow::DataflowAnalysisContext;
using ::clang::dataflow::Environment;
using ::clang::dataflow::Formula;
using ::clang::dataflow::RecordInitListHelper;
using ::clang::dataflow::WatchedLiteralsSolver;
using ConcreteNullabilityCache =
absl::flat_hash_map<const Decl *,
std::optional<const PointerTypeNullability>>;
std::string_view getOrGenerateUSR(USRCache &Cache, const Decl &Decl) {
auto [It, Inserted] = Cache.try_emplace(&Decl);
if (Inserted) {
llvm::SmallString<128> USR;
if (!index::generateUSRForDecl(&Decl, USR)) It->second = USR.str();
}
return It->second;
}
static llvm::DenseSet<absl::Nonnull<const CXXMethodDecl *>> getOverridden(
absl::Nonnull<const CXXMethodDecl *> Derived) {
llvm::DenseSet<absl::Nonnull<const CXXMethodDecl *>> Overridden;
for (const CXXMethodDecl *Base : Derived->overridden_methods()) {
if (Base == nullptr) continue;
Overridden.insert(Base);
for (const CXXMethodDecl *BaseOverridden : getOverridden(Base)) {
if (BaseOverridden == nullptr) continue;
Overridden.insert(BaseOverridden);
}
}
return Overridden;
}
namespace {
/// Shared base class for visitors that walk the AST for evidence collection
/// purposes, to ensure they see the same nodes.
template <typename Derived>
struct EvidenceLocationsWalker : public RecursiveASTVisitor<Derived> {
// We do want to see concrete code, including function instantiations.
bool shouldVisitTemplateInstantiations() const { return true; }
// In order to collect from more default member initializers, we do want to
// see defaulted default constructors, which are implicitly-defined
// functions whether the declaration is implicit or explicit. We also want
// to see lambda bodies in the form of operator() definitions that are not
// themselves implicit but show up in an implicit context.
bool shouldVisitImplicitCode() const { return true; }
};
} // namespace
VirtualMethodOverridesMap getVirtualMethodOverrides(ASTContext &Ctx) {
struct Walker : public EvidenceLocationsWalker<Walker> {
VirtualMethodOverridesMap Out;
bool VisitCXXMethodDecl(const CXXMethodDecl *MD) {
if (MD && MD->isVirtual()) {
for (const auto *O : getOverridden(MD)) {
Out[O].insert(MD);
}
}
return true;
}
};
// Don't use a LocFilter here to restrict to the main file or header, because
// we want to propagate evidence from virtual methods to/from their overrides,
// no matter where they are each defined.
Walker W;
W.TraverseAST(Ctx);
return std::move(W.Out);
}
VirtualMethodEvidenceFlowDirection getFlowDirection(Evidence::Kind Kind,
bool ForReturnSlot) {
switch (Kind) {
case Evidence::ANNOTATED_NONNULL:
case Evidence::UNCHECKED_DEREFERENCE:
case Evidence::NONNULL_ARGUMENT:
case Evidence::NONNULL_RETURN:
case Evidence::ASSIGNED_TO_NONNULL:
case Evidence::ABORT_IF_NULL:
case Evidence::ARITHMETIC:
case Evidence::GCC_NONNULL_ATTRIBUTE:
case Evidence::ASSIGNED_TO_NONNULL_REFERENCE:
case Evidence::WELL_KNOWN_NONNULL:
// Evidence pointing toward Unknown is only used to prevent Nonnull
// inferences; it cannot override Nullable. So propagate it in the same
// direction we do for Nonnull-pointing evidence.
case Evidence::ANNOTATED_UNKNOWN:
case Evidence::UNKNOWN_ARGUMENT:
case Evidence::UNKNOWN_RETURN:
case Evidence::ASSIGNED_FROM_NONNULL:
case Evidence::ASSIGNED_FROM_UNKNOWN:
return ForReturnSlot
? VirtualMethodEvidenceFlowDirection::kFromBaseToDerived
: VirtualMethodEvidenceFlowDirection::kFromDerivedToBase;
case Evidence::ANNOTATED_NULLABLE:
case Evidence::NULLABLE_ARGUMENT:
case Evidence::NULLABLE_RETURN:
case Evidence::ASSIGNED_TO_MUTABLE_NULLABLE:
case Evidence::ASSIGNED_FROM_NULLABLE:
case Evidence::NULLPTR_DEFAULT_MEMBER_INITIALIZER:
case Evidence::WELL_KNOWN_NULLABLE:
return ForReturnSlot
? VirtualMethodEvidenceFlowDirection::kFromDerivedToBase
: VirtualMethodEvidenceFlowDirection::kFromBaseToDerived;
case Evidence::NULLABLE_REFERENCE_RETURN:
case Evidence::NONNULL_REFERENCE_RETURN:
case Evidence::NONNULL_REFERENCE_RETURN_AS_CONST:
case Evidence::UNKNOWN_REFERENCE_RETURN:
case Evidence::NULLABLE_REFERENCE_ARGUMENT:
case Evidence::NONNULL_REFERENCE_ARGUMENT:
case Evidence::NONNULL_REFERENCE_ARGUMENT_AS_CONST:
case Evidence::UNKNOWN_REFERENCE_ARGUMENT:
return VirtualMethodEvidenceFlowDirection::kBoth;
}
}
static llvm::DenseSet<const CXXMethodDecl *>
getAdditionalTargetsForVirtualMethod(
const CXXMethodDecl *MD, Evidence::Kind Kind, bool ForReturnSlot,
const VirtualMethodOverridesMap &OverridesMap) {
VirtualMethodEvidenceFlowDirection FlowDirection =
getFlowDirection(Kind, ForReturnSlot);
switch (FlowDirection) {
case VirtualMethodEvidenceFlowDirection::kFromBaseToDerived:
if (auto It = OverridesMap.find(MD); It != OverridesMap.end())
return It->second;
return {};
case VirtualMethodEvidenceFlowDirection::kFromDerivedToBase:
return getOverridden(MD);
case VirtualMethodEvidenceFlowDirection::kBoth:
llvm::DenseSet<const CXXMethodDecl *> Results = getOverridden(MD);
if (auto It = OverridesMap.find(MD); It != OverridesMap.end())
Results.insert(It->second.begin(), It->second.end());
return Results;
}
}
llvm::unique_function<EvidenceEmitter> evidenceEmitter(
llvm::unique_function<void(const Evidence &) const> Emit,
USRCache &USRCache, ASTContext &Ctx) {
return evidenceEmitter(std::move(Emit), USRCache, Ctx,
getVirtualMethodOverrides(Ctx));
}
llvm::unique_function<EvidenceEmitter> evidenceEmitter(
llvm::unique_function<void(const Evidence &) const> Emit,
USRCache &USRCache, ASTContext &Ctx,
const VirtualMethodOverridesMap &&OverridesMap) {
class EvidenceEmitterImpl {
public:
EvidenceEmitterImpl(
llvm::unique_function<void(const Evidence &) const> Emit,
nullability::USRCache &USRCache, ASTContext &Ctx,
const VirtualMethodOverridesMap &&OverridesMap)
: Emit(std::move(Emit)),
USRCache(USRCache),
OverridesMap(std::move(OverridesMap)) {}
void operator()(const Decl &Target, Slot S, Evidence::Kind Kind,
SourceLocation Loc) const {
CHECK(isInferenceTarget(Target))
<< "Evidence emitted for a Target which is not an inference target: "
<< (dyn_cast<NamedDecl>(&Target)
? dyn_cast<NamedDecl>(&Target)->getQualifiedNameAsString()
: "not a named decl");
Evidence E;
E.set_slot(S);
E.set_kind(Kind);
std::string_view USR = getOrGenerateUSR(USRCache, Target);
if (USR.empty()) return; // Can't emit without a USR
E.mutable_symbol()->set_usr(USR);
// TODO: make collecting and propagating location information optional?
auto &SM =
Target.getDeclContext()->getParentASTContext().getSourceManager();
// TODO: are macro locations actually useful enough for debugging?
// we could leave them out, and make room for non-macro samples.
if (Loc = SM.getFileLoc(Loc); Loc.isValid())
E.set_location(Loc.printToString(SM));
Emit(E);
// Virtual methods and their overrides constrain each other's
// nullabilities, so propagate evidence in the appropriate direction based
// on the evidence kind and whether the evidence is for the return type or
// a parameter type.
if (auto *MD = dyn_cast<CXXMethodDecl>(&Target); MD && MD->isVirtual()) {
for (const auto *O : getAdditionalTargetsForVirtualMethod(
MD, Kind, S == SLOT_RETURN_TYPE, OverridesMap)) {
USR = getOrGenerateUSR(USRCache, *O);
if (USR.empty()) return; // Can't emit without a USR
E.mutable_symbol()->set_usr(USR);
Emit(E);
}
}
}
private:
llvm::unique_function<void(const Evidence &) const> Emit;
// Must outlive the EvidenceEmitterImpl.
nullability::USRCache &USRCache;
const VirtualMethodOverridesMap OverridesMap;
};
return EvidenceEmitterImpl(std::move(Emit), USRCache, Ctx,
std::move(OverridesMap));
}
namespace {
class InferableSlot {
public:
InferableSlot(PointerTypeNullability Nullability, Slot Slot, const Decl &Decl)
: SymbolicNullability(Nullability),
TargetSlot(Slot),
InferenceTarget(Decl) {}
const PointerTypeNullability &getSymbolicNullability() const {
return SymbolicNullability;
}
Slot getTargetSlot() const { return TargetSlot; }
const Decl &getInferenceTarget() const { return InferenceTarget; }
private:
const PointerTypeNullability SymbolicNullability;
const Slot TargetSlot;
const Decl &InferenceTarget;
};
} // namespace
/// If Stmt is a dereference, returns its target and location.
static std::pair<const Expr *, SourceLocation> describeDereference(
const Stmt &Stmt) {
if (auto *Op = dyn_cast<UnaryOperator>(&Stmt);
Op && Op->getOpcode() == UO_Deref) {
return {Op->getSubExpr(), Op->getOperatorLoc()};
}
if (auto *ME = dyn_cast<MemberExpr>(&Stmt); ME && ME->isArrow()) {
return {ME->getBase(), ME->getOperatorLoc()};
}
// pointers to members; at the time of writing, they aren't a supported
// pointer type, so this is a no-op.
if (const auto *BO = dyn_cast<BinaryOperator>(&Stmt);
BO && (BO->getOpcode() == clang::BinaryOperatorKind::BO_PtrMemD ||
BO->getOpcode() == clang::BinaryOperatorKind::BO_PtrMemI)) {
return {BO->getRHS(), BO->getOperatorLoc()};
}
if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(&Stmt);
OCE && OCE->getOperator() == clang::OO_Star &&
isSupportedSmartPointerType(OCE->getArg(0)->getType())) {
return {OCE->getArg(0), OCE->getOperatorLoc()};
}
return {nullptr, SourceLocation()};
}
/// Inferable slots are nullability slots not explicitly annotated in source
/// code that we are currently capable of handling. This returns a boolean
/// constraint representing these slots having a) the nullability inferred from
/// the previous round for this slot or b) Unknown nullability if no inference
/// was made in the previous round or there was no previous round.
static const Formula &getInferableSlotsAsInferredOrUnknownConstraint(
const std::vector<InferableSlot> &InferableSlots, USRCache &USRCache,
const PreviousInferences &PreviousInferences, dataflow::Arena &A) {
const Formula *Constraint = &A.makeLiteral(true);
for (auto &IS : InferableSlots) {
std::string_view USR = getOrGenerateUSR(USRCache, IS.getInferenceTarget());
SlotFingerprint Fingerprint = fingerprint(USR, IS.getTargetSlot());
auto Nullability = IS.getSymbolicNullability();
const Formula &Nullable = PreviousInferences.Nullable->contains(Fingerprint)
? Nullability.isNullable(A)
: A.makeNot(Nullability.isNullable(A));
const Formula &Nonnull = PreviousInferences.Nonnull->contains(Fingerprint)
? Nullability.isNonnull(A)
: A.makeNot(Nullability.isNonnull(A));
Constraint = &A.makeAnd(*Constraint, A.makeAnd(Nullable, Nonnull));
}
return *Constraint;
}
static void overrideNullability(const ValueDecl &D,
const PointerNullabilityLattice &Lattice,
TypeNullability &N) {
if (N.empty()) {
// We expect this not to be the case, but not to a crash-worthy level, so
// just log if it is.
llvm::errs() << "Nullability for type " << D.getType().getAsString();
if (auto *ND = dyn_cast<clang::NamedDecl>(&D)) {
llvm::errs() << " for Decl named " << ND->getQualifiedNameAsString();
}
llvm::errs() << " requested with overrides, but is an empty vector.\n";
} else {
Lattice.overrideNullabilityFromDecl(&D, N);
}
}
static TypeNullability getNullabilityAnnotationsFromDeclAndOverrides(
const ValueDecl &D, const PointerNullabilityLattice &Lattice) {
TypeNullability N = getTypeNullability(D, Lattice.defaults());
overrideNullability(D, Lattice, N);
return N;
}
static TypeNullability getReturnTypeNullabilityAnnotations(
const FunctionDecl &D, const TypeNullabilityDefaults &Defaults) {
// Use the QualType, FileID overload of getTypeNullability for return types,
// because of complexity around the following cases:
//
// The return TypeLoc for `auto`-returning functions contains an undeduced
// `auto` type, even if the `auto` has been deduced. See
// https://github.com/llvm/llvm-project/issues/42259 for more.
//
// FunctionDecls with top-level TypeLocs that are not simple
// FunctionTypeLoc, such as those with attributes, would need excavation of
// the function's FunctionTypeLoc before being able to retrieve the return
// TypeLoc.
return getTypeNullability(D.getReturnType(), getGoverningFile(&D), Defaults);
}
static TypeNullability getReturnTypeNullabilityAnnotationsWithOverrides(
const FunctionDecl &D, const PointerNullabilityLattice &Lattice) {
TypeNullability N =
getReturnTypeNullabilityAnnotations(D, Lattice.defaults());
// The FunctionDecl is the key used for overrides for the return
// type. To look up overrides for parameters, we would pass a
// ParmVarDecl to `overrideNullability`.
overrideNullability(D, Lattice, N);
return N;
}
static Evidence::Kind getArgEvidenceKindFromNullability(
NullabilityKind Nullability, QualType ParamType) {
bool IsReference = ParamType->isReferenceType();
switch (Nullability) {
case NullabilityKind::Nullable:
return IsReference ? Evidence::NULLABLE_REFERENCE_ARGUMENT
: Evidence::NULLABLE_ARGUMENT;
case NullabilityKind::NonNull: {
bool IsNonReferenceConst =
ParamType.getNonReferenceType().isConstQualified();
return IsReference ? (IsNonReferenceConst
? Evidence::NONNULL_REFERENCE_ARGUMENT_AS_CONST
: Evidence::NONNULL_REFERENCE_ARGUMENT)
: Evidence::NONNULL_ARGUMENT;
}
default:
return IsReference ? Evidence::UNKNOWN_REFERENCE_ARGUMENT
: Evidence::UNKNOWN_ARGUMENT;
}
}
static std::optional<Evidence::Kind> evidenceKindFromDeclaredNullability(
const TypeNullability &Nullability) {
switch (Nullability.front().concrete()) {
default:
return std::nullopt;
case NullabilityKind::NonNull:
return Evidence::ANNOTATED_NONNULL;
case NullabilityKind::Nullable:
return Evidence::ANNOTATED_NULLABLE;
}
}
static std::optional<Evidence::Kind> evidenceKindFromDeclaredTypeLoc(
TypeLoc Loc, const TypeNullabilityDefaults &Defaults) {
if (!isSupportedPointerType(Loc.getType().getNonReferenceType()))
return std::nullopt;
auto Nullability = getTypeNullability(Loc, Defaults);
return evidenceKindFromDeclaredNullability(Nullability);
}
static std::optional<Evidence::Kind> evidenceKindFromDeclaredReturnType(
const FunctionDecl &D, const TypeNullabilityDefaults &Defaults) {
if (!isSupportedPointerType(D.getReturnType().getNonReferenceType()))
return std::nullopt;
return evidenceKindFromDeclaredNullability(
getReturnTypeNullabilityAnnotations(D, Defaults));
}
static bool isOrIsConstructedFromNullPointerConstant(
absl::Nonnull<const Expr *> E, ASTContext &Ctx) {
if (E->isNullPointerConstant(Ctx, Expr::NPC_ValueDependentIsNotNull) !=
Expr::NPCK_NotNull) {
return true;
}
if (auto *DefaultInit = dyn_cast<CXXDefaultInitExpr>(E)) {
E = DefaultInit->getExpr();
}
const Expr *SubExpr = &dataflow::ignoreCFGOmittedNodes(*E);
if (auto *MaterializeTempExpr = dyn_cast<MaterializeTemporaryExpr>(SubExpr)) {
SubExpr = MaterializeTempExpr->getSubExpr();
}
if (auto *BindTemp = dyn_cast<CXXBindTemporaryExpr>(SubExpr)) {
SubExpr = BindTemp->getSubExpr();
}
auto *CE = dyn_cast<CXXConstructExpr>(SubExpr->IgnoreImpCasts());
if (!CE) return false;
return CE != nullptr && CE->getNumArgs() == 1 &&
CE->getArg(0)->isNullPointerConstant(
Ctx, Expr::NPC_ValueDependentIsNotNull) != Expr::NPCK_NotNull;
}
namespace {
class DefinitionEvidenceCollector {
public:
// Instantiate the class only in this static function, to restrict the
// lifetime of the object, which holds reference parameters.
static void collect(std::vector<InferableSlot> &InferableSlots,
const Formula &InferableSlotsConstraint,
llvm::function_ref<EvidenceEmitter> Emit,
const CFGElement &CFGElem,
const PointerNullabilityLattice &Lattice,
const Environment &Env, const dataflow::Solver &Solver) {
DefinitionEvidenceCollector Collector(
InferableSlots, InferableSlotsConstraint, Emit, Lattice, Env, Solver);
if (auto CFGStmt = CFGElem.getAs<clang::CFGStmt>()) {
const Stmt *S = CFGStmt->getStmt();
if (!S) return;
Collector.fromDereference(*S);
Collector.fromCallExpr(*S);
Collector.fromConstructExpr(*S);
Collector.fromReturn(*S);
Collector.fromAssignment(*S);
Collector.fromArithmetic(*S);
Collector.fromAggregateInitialization(*S);
} else if (auto CFGInit = CFGElem.getAs<clang::CFGInitializer>()) {
Collector.fromCFGInitializer(*CFGInit);
}
}
private:
DefinitionEvidenceCollector(std::vector<InferableSlot> &InferableSlots,
const Formula &InferableSlotsConstraint,
llvm::function_ref<EvidenceEmitter> Emit,
const PointerNullabilityLattice &Lattice,
const Environment &Env,
const dataflow::Solver &Solver)
: InferableSlots(InferableSlots),
InferableSlotsConstraint(InferableSlotsConstraint),
Emit(Emit),
Lattice(Lattice),
Env(Env),
Solver(Solver) {}
/// Records evidence derived from the necessity that `Value` is nonnull.
/// It may be dereferenced, passed as a nonnull param, etc, per
/// `EvidenceKind`.
void mustBeNonnull(const dataflow::PointerValue &Value, SourceLocation Loc,
Evidence::Kind EvidenceKind) {
CHECK(hasPointerNullState(Value))
<< "Value should be the value of an expression. Cannot collect "
"evidence for nullability if there is no null state.";
auto *IsNull = getPointerNullState(Value).IsNull;
// If `IsNull` is top, we can't infer anything about it.
if (IsNull == nullptr) return;
auto &A = Env.arena();
mustBeTrueByMarkingNonnull(A.makeNot(*IsNull), Loc, EvidenceKind);
}
/// Records evidence for Nonnull-ness of one slot, derived from the necessity
/// that `MustBeTrue` must be true.
///
/// Used when we have reason to believe that `MustBeTrue` can be made true by
/// marking a slot Nonnull.
void mustBeTrueByMarkingNonnull(const Formula &MustBeTrue, SourceLocation Loc,
Evidence::Kind EvidenceKind) {
auto &A = Env.arena();
// If `MustBeTrue` is already proven true or false (or both, which indicates
// unsatisfiable flow conditions), collect no evidence.
if (Env.proves(MustBeTrue) || Env.proves(A.makeNot(MustBeTrue))) return;
for (auto &IS : InferableSlots) {
auto &SlotNonnull = IS.getSymbolicNullability().isNonnull(A);
auto &SlotNonnullImpliesFormulaTrue =
A.makeImplies(SlotNonnull, MustBeTrue);
// Don't collect evidence if the implication is true by virtue of
// `SlotNonnull` being false.
//
// In practice, `SlotNonnull` can be made false by a flow condition, and
// marking the slot Nonnull would make that conditioned block dead code.
// Technically, this does make a dereference, etc. "safe", but we'd prefer
// to mark a different slot Nonnull that has a more direct relationship
// with `MustBeTrue`.
//
// e.g. We'd prefer to mark `q` Nonnull rather than `p` in the following:
// ```
// void target(int* p, int* q) {
// if (!p) {
// *q;
// }
// }
// ```
if (Env.allows(SlotNonnull) &&
Env.proves(SlotNonnullImpliesFormulaTrue)) {
Emit(IS.getInferenceTarget(), IS.getTargetSlot(), EvidenceKind, Loc);
return;
}
}
}
void fromDereference(const Stmt &S) {
auto [Target, Loc] = describeDereference(S);
if (!Target || !isSupportedPointerType(Target->getType())) return;
// It is a dereference of a pointer. Now gather evidence from it.
dataflow::PointerValue *DereferencedValue = getPointerValue(Target, Env);
if (!DereferencedValue) return;
mustBeNonnull(*DereferencedValue, Loc, Evidence::UNCHECKED_DEREFERENCE);
}
/// Records evidence for Nullable-ness for potentially multiple slots, derived
/// from the necessity that `MustBeTrue` must be true.
///
/// Used when we have reason to believe that `MustBeTrue` can be made provably
/// true by marking a single slot Nullable, and that all such slots should be
/// marked Nullable.
void mustBeTrueByMarkingNullable(const Formula &MustBeTrue,
SourceLocation Loc,
Evidence::Kind EvidenceKind) {
auto &A = Env.arena();
// If `MustBeTrue` is already proven true or false (or both, which indicates
// unsatisfiable flow conditions), collect no evidence.
if (Env.proves(MustBeTrue) || Env.proves(A.makeNot(MustBeTrue))) return;
for (auto &IS : InferableSlots) {
auto &SlotNullable = IS.getSymbolicNullability().isNullable(A);
auto &SlotNullableImpliesFormulaTrue =
A.makeImplies(SlotNullable, MustBeTrue);
// Don't collect evidence if the implication is true by virtue of
// `SlotNullable` being false.
if (Env.allows(SlotNullable) &&
Env.proves(SlotNullableImpliesFormulaTrue)) {
Emit(IS.getInferenceTarget(), IS.getTargetSlot(), EvidenceKind, Loc);
// Continue the loop, emitting evidence for all such slots.
}
}
}
/// Collect evidence for each of `InferableSlots` if that slot being marked
/// Nullable would imply `Value`'s FromNullable property.
///
/// This function is called when we have reason to believe that `Value` must
/// be Nullable.
void mustBeMarkedNullable(const dataflow::PointerValue &Value,
SourceLocation Loc, Evidence::Kind EvidenceKind) {
CHECK(hasPointerNullState(Value))
<< "Value should be the value of an expression. Cannot collect "
"evidence for nullability if there is no null state.";
auto *FromNullable = getPointerNullState(Value).FromNullable;
// If `FromNullable` is top, we can't infer anything about it.
if (FromNullable == nullptr) return;
mustBeTrueByMarkingNullable(*FromNullable, Loc, EvidenceKind);
}
// Emit evidence based on the relationship between the nullability of the
// expression on the RHS of an assignment and the nullability of the
// declaration on the LHS.
// `LHSType` should be a pointer type or a reference to a pointer type.
void fromAssignmentToType(QualType LHSType,
const TypeNullability &LHSTypeNullability,
const Expr &RHSExpr, SourceLocation RHSLoc) {
// TODO: Account for variance and each layer of nullability when we handle
// more than top-level pointers.
if (LHSTypeNullability.empty()) return;
const dataflow::PointerValue *PointerValue = getPointerValue(&RHSExpr, Env);
if (!PointerValue) return;
const PointerTypeNullability &TopLevel = LHSTypeNullability[0];
dataflow::Arena &A = Env.arena();
bool SkipValueAssignedToNonnull = false;
if (/* LHSType is an lvalue reference to a pointer. */
LHSType->isLValueReferenceType()) {
// If the reference is either to a (mutable or const) Nonnull pointer or
// to a mutable Nullable pointer, emit evidence that makes the top level
// type nullability of `RHSExpr` match the top level of
// `LHSTypeNullability`. This is distinct from the value nullability of
// `RHSExpr` being constrained, which is handled below.
if (TopLevel.concrete() == NullabilityKind::NonNull ||
(TopLevel.isSymbolic() &&
Env.proves(A.makeImplies(InferableSlotsConstraint,
TopLevel.isNonnull(A))))) {
if (const TypeNullability *RHSTypeNullability =
Lattice.getTypeNullability(&RHSExpr)) {
CHECK_GT(RHSTypeNullability->size(), 0);
const PointerTypeNullability &RHSTopLevel = (*RHSTypeNullability)[0];
mustBeTrueByMarkingNonnull(RHSTopLevel.isNonnull(A), RHSLoc,
Evidence::ASSIGNED_TO_NONNULL_REFERENCE);
// It would be duplicative to emit both ASSIGNED_TO_NONNULL_REFERENCE
// and ASSIGNED_TO_NONNULL for the same assignment.
SkipValueAssignedToNonnull = true;
}
} else if (!LHSType.getNonReferenceType().isConstQualified() &&
(TopLevel.concrete() == NullabilityKind::Nullable ||
(TopLevel.isSymbolic() &&
Env.proves(A.makeImplies(InferableSlotsConstraint,
TopLevel.isNullable(A)))))) {
if (const TypeNullability *RHSTypeNullability =
Lattice.getTypeNullability(&RHSExpr)) {
CHECK_GT(RHSTypeNullability->size(), 0);
const PointerTypeNullability &RHSTopLevel = (*RHSTypeNullability)[0];
// The LHS can't be Nullable and also Nonnull, so we can skip the
// later checks for it being Nonnull.
SkipValueAssignedToNonnull = true;
mustBeTrueByMarkingNullable(RHSTopLevel.isNullable(A), RHSLoc,
Evidence::ASSIGNED_TO_MUTABLE_NULLABLE);
}
}
}
// If the left hand side is Nonnull, emit evidence that the PointerValue on
// the right hand side must also be Nonnull, unless we've already emitted
// evidence to that effect.
if (!SkipValueAssignedToNonnull &&
(TopLevel.concrete() == NullabilityKind::NonNull ||
(TopLevel.isSymbolic() &&
Env.proves(A.makeImplies(InferableSlotsConstraint,
TopLevel.isNonnull(A)))))) {
mustBeNonnull(*PointerValue, RHSLoc, Evidence::ASSIGNED_TO_NONNULL);
}
}
template <typename CallOrConstructExpr>
void fromArgsAndParams(const FunctionDecl &CalleeDecl,
const CallOrConstructExpr &Expr) {
bool CollectEvidenceForCallee = isInferenceTarget(CalleeDecl);
bool CollectEvidenceForCaller = !InferableSlots.empty();
for (ParamAndArgIterator<CallOrConstructExpr> Iter(CalleeDecl, Expr); Iter;
++Iter) {
if (!isSupportedPointerType(Iter.param().getType().getNonReferenceType()))
continue;
if (!isSupportedPointerType(Iter.arg().getType())) {
// These builtins are declared with pointer type parameters even when
// given a valid argument of type uintptr_t. In this case, there's
// nothing to infer, but also nothing unexpected to crash over.
auto BuiltinID = CalleeDecl.getBuiltinID();
if (BuiltinID == Builtin::BI__builtin_is_aligned ||
BuiltinID == Builtin::BI__builtin_align_up ||
BuiltinID == Builtin::BI__builtin_align_down) {
continue;
}
}
// the corresponding argument should also be a pointer.
CHECK(isSupportedPointerType(Iter.arg().getType()))
<< "Unsupported argument " << Iter.argIdx()
<< " type: " << Iter.arg().getType().getAsString();
if (isa<clang::CXXDefaultArgExpr>(Iter.arg())) {
// Evidence collection for the callee from default argument values is
// handled when collecting from declarations, and there's no useful
// evidence available to collect for the caller.
return;
}
SourceLocation ArgLoc = Iter.arg().getExprLoc();
if (CollectEvidenceForCaller) {
auto ParamNullability = getNullabilityAnnotationsFromDeclAndOverrides(
Iter.param(), Lattice);
// Collect evidence from constraints that the parameter's nullability
// places on the argument's nullability.
fromAssignmentToType(Iter.param().getType(), ParamNullability,
Iter.arg(), ArgLoc);
}
if (CollectEvidenceForCallee &&
// Don't collect evidence if the parameter is already annotated in
// source. This will still collect evidence if the parameter has only
// a previously-inferred nullability, in order to maintain that
// inference in this iteration.
!evidenceKindFromDeclaredNullability(
getTypeNullability(Iter.param(), Lattice.defaults()))) {
dataflow::PointerValue *PV = getPointerValue(&Iter.arg(), Env);
if (PV) {
// Calculate the parameter's nullability based on InferableSlots
// for the caller being assigned to Unknown or their
// previously-inferred value, to reflect the current annotations and
// not all possible annotations for them.
NullabilityKind ArgNullability =
getNullability(*PV, Env, &InferableSlotsConstraint);
Emit(CalleeDecl, paramSlot(Iter.paramIdx()),
getArgEvidenceKindFromNullability(ArgNullability,
Iter.param().getType()),
ArgLoc);
}
}
}
}
/// Collects evidence from the assignment of function arguments to the types
/// of the corresponding parameter, used when we have a FunctionProtoType but
/// no FunctionDecl.
/// TODO: When we collect evidence for more complex slots than just top-level
/// pointers, emit evidence of the function parameter's nullability as a slot
/// in the appropriate declaration.
void fromFunctionProtoTypeCall(const FunctionProtoType &CalleeType,
const CallExpr &Expr) {
// For each pointer parameter of the function, ...
for (unsigned I = 0; I < CalleeType.getNumParams(); ++I) {
const auto ParamType = CalleeType.getParamType(I);
if (!isSupportedPointerType(ParamType.getNonReferenceType())) continue;
// the corresponding argument should also be a pointer.
CHECK(isSupportedPointerType(Expr.getArg(I)->getType()))
<< "Unsupported argument " << I
<< " type: " << Expr.getArg(I)->getType().getAsString();
// TODO: when we infer function pointer/reference parameters'
// nullabilities, check for overrides from previous inference iterations.
auto ParamNullability = getNullabilityAnnotationsFromType(ParamType);
// Collect evidence from constraints that the parameter's nullability
// places on the argument's nullability.
fromAssignmentToType(ParamType, ParamNullability, *Expr.getArg(I),
Expr.getArg(I)->getExprLoc());
}
}
/// Collect evidence that the function pointer was dereferenced and from the
/// matching up of parameter/argument nullabilities.
void fromFunctionPointerCallExpr(const Type &CalleeFunctionType,
const CallExpr &Expr) {
if (InferableSlots.empty()) return;
if (const auto *Callee = Expr.getCallee()) {
// Function pointers are only ever raw pointers.
if (const auto *PV = getRawPointerValue(Callee, Env)) {
mustBeNonnull(*PV, Expr.getExprLoc(), Evidence::UNCHECKED_DEREFERENCE);
}
}
auto *CalleeFunctionProtoType =
CalleeFunctionType.getAs<FunctionProtoType>();
CHECK(CalleeFunctionProtoType);
fromFunctionProtoTypeCall(*CalleeFunctionProtoType, Expr);
}
/// Handles the case of a call to a function without a FunctionDecl, e.g. that
/// is provided as a parameter or another decl, e.g. a field or local
/// variable.
///
/// Example: We can collect evidence for the nullability of `p` and (when we
/// handle more than top-level pointer slots) `j` in the following, based on
/// the call to `callee`:
/// ```
/// void target(int* p, void (*callee)(Nonnull<int*> i, int* j)) {
/// callee(p, nullptr);
/// }
/// ```
///
/// With `CalleeDecl` in this case not being a FunctionDecl as in most
/// CallExpr cases, distinct handling is needed.
void fromCallExprWithoutFunctionCalleeDecl(const Decl &CalleeDecl,
const CallExpr &Expr) {
if (CalleeDecl.isFunctionPointerType()) {
if (auto *FuncType = CalleeDecl.getFunctionType()) {
fromFunctionPointerCallExpr(*FuncType, Expr);
} else {
llvm::errs() << "Unsupported case of a function pointer type, for "
"which we aren't retrieving a valid FunctionType. \n";
CalleeDecl.dump();
}
return;
}
// Ignore calls of pointers to members. The dereferencing of the pointer is
// handled as a dereference at the BinaryOperator node, which additionally
// captures pointers to fields.
// TODO(b/309625642) Consider collecting evidence for the arguments being
// passed as parameters to the pointed-to member.
if (const auto *BinaryOpCallee = dyn_cast_or_null<BinaryOperator>(
Expr.getCallee()->IgnoreParenImpCasts());
BinaryOpCallee &&
(BinaryOpCallee->getOpcode() == clang::BinaryOperatorKind::BO_PtrMemD ||
BinaryOpCallee->getOpcode() ==
clang::BinaryOperatorKind::BO_PtrMemI)) {
return;
}
// Function references are a rare case, but similar to function pointers, we
// can collect evidence from arguments assigned to parameter types.
if (auto *FuncType = CalleeDecl.getFunctionType()) {
if (auto *FuncProtoType = FuncType->getAs<FunctionProtoType>()) {
fromFunctionProtoTypeCall(*FuncProtoType, Expr);
return;
}
}
// A reference to a function pointer is another rare case, but we can
// collect the same evidence we would for a function pointer.
if (const auto *CalleeAsValueDecl =
dyn_cast<clang::ValueDecl>(&CalleeDecl)) {
if (QualType CalleeType = CalleeAsValueDecl->getType();
CalleeType.getNonReferenceType()->isFunctionPointerType()) {
fromFunctionPointerCallExpr(
*(CalleeType.getNonReferenceType()->getPointeeType()), Expr);
return;
}
}
// If we run into other cases meeting this criterion, skip them, but log
// first so we can potentially add support later.
llvm::errs() << "Unsupported case of a CallExpr without a FunctionDecl. "
"Not collecting any evidence from this CallExpr:\n";
Expr.getBeginLoc().dump(CalleeDecl.getASTContext().getSourceManager());
Expr.dump();
llvm::errs() << "Which is a call to:\n";
CalleeDecl.dump();
}
/// Given a `CallExpr` for a call to our special macro single-argument capture
/// function, collect evidence for a slot that can prevent the abort condition
/// from being true if it is annotated Nonnull.
///
/// e.g. From `CHECK(x)`, we collect evidence for a slot that can cause `x` to
/// not be null.
void fromAbortIfFalseMacroCall(const CallExpr &CallExpr) {
CHECK_EQ(CallExpr.getNumArgs(), 1);
const Expr *Arg = CallExpr.getArg(0);
if (!Arg) return;
QualType ArgType = Arg->getType();
if (isSupportedPointerType(ArgType)) {
const dataflow::PointerValue *PV = getPointerValue(Arg, Env);
if (!PV) return;
mustBeNonnull(*PV, Arg->getExprLoc(), Evidence::ABORT_IF_NULL);
} else if (ArgType->isBooleanType()) {
const dataflow::BoolValue *BV = Env.get<dataflow::BoolValue>(*Arg);
if (!BV || BV->getKind() == dataflow::BoolValue::Kind::TopBool) return;
mustBeTrueByMarkingNonnull(BV->formula(), Arg->getExprLoc(),
Evidence::ABORT_IF_NULL);
}
}
/// Given a `CallExpr` for a call to our special macro two-argument capture
/// function for not-equal checks, if one of the arguments is a nullptr
/// constant or provably null, collect evidence for a slot that can prevent
/// the other argument from being null.
///
/// e.g. From `CHECK_NE(x, nullptr)`, we collect evidence for a slot that can
/// cause `x` to not be null.
void fromAbortIfEqualMacroCall(const CallExpr &CallExpr) {
CHECK_EQ(CallExpr.getNumArgs(), 2);
const Expr *First = CallExpr.getArg(0);
const Expr *Second = CallExpr.getArg(1);
bool FirstSupported = isSupportedPointerType(First->getType());
bool SecondSupported = isSupportedPointerType(Second->getType());
if (!FirstSupported && !SecondSupported) return;
ASTContext &Context = CallExpr.getCalleeDecl()->getASTContext();
const dataflow::PointerValue *ValueComparedToNull = nullptr;
SourceLocation EvidenceLoc;
if (First->isNullPointerConstant(Context,
Expr::NPC_ValueDependentIsNotNull)) {
if (!isSupportedPointerType(Second->getType())) return;
ValueComparedToNull = getPointerValue(Second, Env);
if (!ValueComparedToNull) return;
EvidenceLoc = Second->getExprLoc();
} else if (Second->isNullPointerConstant(
Context, Expr::NPC_ValueDependentIsNotNull)) {
if (!isSupportedPointerType(First->getType())) return;
ValueComparedToNull = getPointerValue(First, Env);
if (!ValueComparedToNull) return;
EvidenceLoc = First->getExprLoc();
} else {
if (!FirstSupported || !SecondSupported) {
// If this happens outside of the nullptr literal case, we'd like to
// know about it.
llvm::errs() << "Value of a supported pointer type compared to a value "
"of a type that is not a supported pointer type.: \n";
CallExpr.dump();
CallExpr.getExprLoc().dump(
CallExpr.getCalleeDecl()->getASTContext().getSourceManager());
return;
}
const dataflow::PointerValue *FirstPV = getPointerValue(First, Env);
if (!FirstPV) return;
const dataflow::PointerValue *SecondPV = getPointerValue(Second, Env);
if (!SecondPV) return;
PointerNullState FirstNullState = getPointerNullState(*FirstPV);
if (!FirstNullState.IsNull) return;
PointerNullState SecondNullState = getPointerNullState(*SecondPV);
if (!SecondNullState.IsNull) return;
if (Env.proves(*FirstNullState.IsNull)) {
ValueComparedToNull = SecondPV;
EvidenceLoc = Second->getExprLoc();
} else if (Env.proves(*SecondNullState.IsNull)) {
ValueComparedToNull = FirstPV;
EvidenceLoc = First->getExprLoc();
} else {
return;
}
}
mustBeNonnull(*ValueComparedToNull, EvidenceLoc, Evidence::ABORT_IF_NULL);
}
void fromCallExpr(const Stmt &S) {
auto *CallExpr = dyn_cast<clang::CallExpr>(&S);
if (!CallExpr) return;
auto *CalleeDecl = CallExpr->getCalleeDecl();
if (!CalleeDecl) return;
if (auto *CalleeFunctionDecl = dyn_cast<clang::FunctionDecl>(CalleeDecl)) {
if (CalleeFunctionDecl->getDeclName().isIdentifier()) {
llvm::StringRef Name = CalleeFunctionDecl->getName();
if (Name == ArgCaptureAbortIfFalse) {
fromAbortIfFalseMacroCall(*CallExpr);
return;
}
if (Name == ArgCaptureAbortIfEqual) {
fromAbortIfEqualMacroCall(*CallExpr);
return;
}
}
fromArgsAndParams(*CalleeFunctionDecl, *CallExpr);
} else {
fromCallExprWithoutFunctionCalleeDecl(*CalleeDecl, *CallExpr);
}
}
void fromConstructExpr(const Stmt &S) {
auto *ConstructExpr = dyn_cast<clang::CXXConstructExpr>(&S);
if (!ConstructExpr) return;