29#include "llvm/ADT/BitVector.h"
30#include "llvm/ADT/BitmaskEnum.h"
31#include "llvm/ADT/STLExtras.h"
32#include "llvm/ADT/Sequence.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/ErrorHandling.h"
43static constexpr unsigned EXPECTED_MAX_NUMBER_OF_PARAMS = 2;
46static constexpr unsigned EXPECTED_NUMBER_OF_BASIC_BLOCKS = 8;
49constexpr llvm::StringLiteral CONVENTIONAL_NAMES[] = {
50 "completionHandler",
"completion",
"withCompletionHandler",
51 "withCompletion",
"completionBlock",
"withCompletionBlock",
52 "replyTo",
"reply",
"withReplyTo"};
53constexpr llvm::StringLiteral CONVENTIONAL_SUFFIXES[] = {
54 "WithCompletionHandler",
"WithCompletion",
"WithCompletionBlock",
55 "WithReplyTo",
"WithReply"};
56constexpr llvm::StringLiteral CONVENTIONAL_CONDITIONS[] = {
57 "error",
"cancel",
"shouldCall",
"done",
"OK",
"success"};
59struct KnownCalledOnceParameter {
60 llvm::StringLiteral FunctionName;
63constexpr KnownCalledOnceParameter KNOWN_CALLED_ONCE_PARAMETERS[] = {
64 {llvm::StringLiteral{
"dispatch_async"}, 1},
65 {llvm::StringLiteral{
"dispatch_async_and_wait"}, 1},
66 {llvm::StringLiteral{
"dispatch_after"}, 2},
67 {llvm::StringLiteral{
"dispatch_sync"}, 1},
68 {llvm::StringLiteral{
"dispatch_once"}, 1},
69 {llvm::StringLiteral{
"dispatch_barrier_async"}, 1},
70 {llvm::StringLiteral{
"dispatch_barrier_async_and_wait"}, 1},
71 {llvm::StringLiteral{
"dispatch_barrier_sync"}, 1}};
73class ParameterStatus {
152 DefinitelyCalled = 0x3,
154 NON_ERROR_STATUS = DefinitelyCalled,
168 constexpr ParameterStatus() =
default;
169 ParameterStatus(Kind K) : StatusKind(K) {
170 assert(!seenAnyCalls(K) &&
"Can't initialize status without a call");
172 ParameterStatus(Kind K,
const Expr *Call) : StatusKind(K),
Call(
Call) {
173 assert(seenAnyCalls(K) &&
"This kind is not supposed to have a call");
176 const Expr &getCall()
const {
177 assert(seenAnyCalls(
getKind()) &&
"ParameterStatus doesn't have a call");
180 static bool seenAnyCalls(Kind K) {
181 return (K & DefinitelyCalled) == DefinitelyCalled && K != Reported;
183 bool seenAnyCalls()
const {
return seenAnyCalls(
getKind()); }
185 static bool isErrorStatus(Kind K) {
return K > NON_ERROR_STATUS; }
186 bool isErrorStatus()
const {
return isErrorStatus(
getKind()); }
190 void join(
const ParameterStatus &
Other) {
200 StatusKind |=
Other.getKind();
212 Kind StatusKind = NotVisited;
219 State(
unsigned Size, ParameterStatus::Kind K = ParameterStatus::NotVisited)
220 : ParamData(
Size, K) {}
224 ParameterStatus &getStatusFor(
unsigned Index) {
return ParamData[Index]; }
225 const ParameterStatus &getStatusFor(
unsigned Index)
const {
226 return ParamData[Index];
231 bool seenAnyCalls(
unsigned Index)
const {
232 return getStatusFor(Index).seenAnyCalls();
237 const Expr &getCallFor(
unsigned Index)
const {
238 return getStatusFor(Index).getCall();
241 ParameterStatus::Kind getKindFor(
unsigned Index)
const {
242 return getStatusFor(Index).getKind();
245 bool isVisited()
const {
246 return llvm::all_of(ParamData, [](
const ParameterStatus &S) {
247 return S.getKind() != ParameterStatus::NotVisited;
252 void join(
const State &
Other) {
253 assert(ParamData.size() ==
Other.ParamData.size() &&
254 "Couldn't join statuses with different sizes");
255 for (
auto Pair : llvm::zip(ParamData,
Other.ParamData)) {
256 std::get<0>(Pair).join(std::get<1>(Pair));
260 using iterator = ParamSizedVector<ParameterStatus>::iterator;
261 using const_iterator = ParamSizedVector<ParameterStatus>::const_iterator;
263 iterator begin() {
return ParamData.begin(); }
264 iterator end() {
return ParamData.end(); }
266 const_iterator begin()
const {
return ParamData.begin(); }
267 const_iterator end()
const {
return ParamData.end(); }
270 return ParamData ==
Other.ParamData;
274 ParamSizedVector<ParameterStatus> ParamData;
308 bool ShouldRetrieveFromComparisons =
false) {
309 return DeclRefFinder(ShouldRetrieveFromComparisons).Visit(
E);
318 if (!ShouldRetrieveFromComparisons)
332 if (!ShouldRetrieveFromComparisons)
351 if (!ShouldRetrieveFromComparisons)
357 case Builtin::BI__builtin_expect:
358 case Builtin::BI__builtin_expect_with_probability: {
362 return Candidate !=
nullptr ? Candidate :
Visit(CE->
getArg(1));
365 case Builtin::BI__builtin_unpredictable:
380 return E != DeclutteredExpr ?
Visit(DeclutteredExpr) : nullptr;
384 DeclRefFinder(
bool ShouldRetrieveFromComparisons)
385 : ShouldRetrieveFromComparisons(ShouldRetrieveFromComparisons) {}
387 bool ShouldRetrieveFromComparisons;
391 bool ShouldRetrieveFromComparisons =
false) {
392 return DeclRefFinder::find(In, ShouldRetrieveFromComparisons);
396findReferencedParmVarDecl(
const Expr *In,
397 bool ShouldRetrieveFromComparisons =
false) {
399 findDeclRefExpr(In, ShouldRetrieveFromComparisons)) {
400 return dyn_cast<ParmVarDecl>(DR->getDecl());
407const Expr *getCondition(
const Stmt *S) {
412 if (
const auto *
If = dyn_cast<IfStmt>(S)) {
413 return If->getCond();
415 if (
const auto *Ternary = dyn_cast<AbstractConditionalOperator>(S)) {
416 return Ternary->getCond();
429 static constexpr unsigned EXPECTED_NUMBER_OF_NAMES = 5;
430 using NameCollection =
433 static NameCollection collect(
const Expr *From) {
435 Impl.TraverseStmt(
const_cast<Expr *
>(From));
440 Result.push_back(
E->getDecl()->getName());
445 llvm::StringRef Name;
447 if (
E->isImplicitProperty()) {
449 if (
E->isMessagingGetter()) {
450 PropertyMethodDecl =
E->getImplicitPropertyGetter();
452 PropertyMethodDecl =
E->getImplicitPropertySetter();
454 assert(PropertyMethodDecl &&
455 "Implicit property must have associated declaration");
458 assert(
E->isExplicitProperty());
459 Name =
E->getExplicitProperty()->getName();
462 Result.push_back(Name);
467 NamesCollector() =
default;
468 NameCollection Result;
472bool mentionsAnyOfConventionalNames(
const Expr *
E) {
475 return llvm::any_of(MentionedNames, [](llvm::StringRef ConditionName) {
477 CONVENTIONAL_CONDITIONS,
478 [ConditionName](
const llvm::StringLiteral &Conventional) {
479 return ConditionName.contains_insensitive(Conventional);
486struct Clarification {
488 const Stmt *Location;
493class NotCalledClarifier
495 std::optional<Clarification>> {
512 return NotCalledClarifier{
Conditional, SuccWithoutCall}.Visit(Terminator);
517 std::optional<Clarification> VisitIfStmt(
const IfStmt *
If) {
518 return VisitBranchingBlock(
If, NeverCalledReason::IfThen);
521 std::optional<Clarification>
523 return VisitBranchingBlock(Ternary, NeverCalledReason::IfThen);
527 const Stmt *CaseToBlame = SuccInQuestion->getLabel();
535 Case = Case->getNextSwitchCase()) {
536 if (Case == CaseToBlame) {
541 llvm_unreachable(
"Found unexpected switch structure");
544 std::optional<Clarification> VisitForStmt(
const ForStmt *For) {
545 return VisitBranchingBlock(For, NeverCalledReason::LoopEntered);
548 std::optional<Clarification> VisitWhileStmt(
const WhileStmt *While) {
549 return VisitBranchingBlock(While, NeverCalledReason::LoopEntered);
552 std::optional<Clarification>
554 assert(
Parent->succ_size() == 2 &&
555 "Branching block should have exactly two successors");
556 unsigned SuccessorIndex = getSuccessorIndex(Parent, SuccInQuestion);
558 updateForSuccessor(DefaultReason, SuccessorIndex);
559 return Clarification{ActualReason, Terminator};
562 std::optional<Clarification> VisitBinaryOperator(
const BinaryOperator *) {
567 std::optional<Clarification> VisitStmt(
const Stmt *Terminator) {
576 static unsigned getSuccessorIndex(
const CFGBlock *Parent,
579 assert(It !=
Parent->succ_end() &&
580 "Given blocks should be in parent-child relationship");
581 return It -
Parent->succ_begin();
586 unsigned SuccessorIndex) {
587 assert(SuccessorIndex <= 1);
589 static_cast<unsigned>(ReasonForTrueBranch) + SuccessorIndex;
591 static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE));
605 bool CheckConventionalParameters) {
606 CalledOnceChecker(AC, Handler, CheckConventionalParameters).check();
611 bool CheckConventionalParameters)
612 : FunctionCFG(*AC.getCFG()), AC(AC), Handler(Handler),
613 CheckConventionalParameters(CheckConventionalParameters),
615 initDataStructures();
616 assert((size() == 0 || !States.empty()) &&
617 "Data structures are inconsistent");
624 void initDataStructures() {
625 const Decl *AnalyzedDecl = AC.getDecl();
627 if (
const auto *Function = dyn_cast<FunctionDecl>(AnalyzedDecl)) {
628 findParamsToTrack(Function);
629 }
else if (
const auto *Method = dyn_cast<ObjCMethodDecl>(AnalyzedDecl)) {
630 findParamsToTrack(Method);
631 }
else if (
const auto *
Block = dyn_cast<BlockDecl>(AnalyzedDecl)) {
632 findCapturesToTrack(
Block);
633 findParamsToTrack(
Block);
639 CFGSizedVector<State>(FunctionCFG.getNumBlockIDs(), State(size()));
648 if (shouldBeCalledOnce(ParamContext,
P)) {
649 TrackedParams.push_back(
P);
655 template <
class FunctionLikeDecl>
656 void findParamsToTrack(
const FunctionLikeDecl *Function) {
657 for (
unsigned Index : llvm::seq<unsigned>(0u,
Function->param_size())) {
658 if (shouldBeCalledOnce(Function, Index)) {
659 TrackedParams.push_back(
Function->getParamDecl(Index));
670 if (size() == 0 || isPossiblyEmptyImpl())
674 llvm::none_of(States, [](
const State &S) {
return S.isVisited(); }) &&
675 "None of the blocks should be 'visited' before the analysis");
714 const CFGBlock *Exit = &FunctionCFG.getExit();
715 assignState(Exit, State(size(), ParameterStatus::NotCalled));
716 Worklist.enqueuePredecessors(Exit);
718 while (
const CFGBlock *BB = Worklist.dequeue()) {
719 assert(BB &&
"Worklist should filter out null blocks");
721 assert(CurrentState.isVisited() &&
722 "After the check, basic block should be visited");
726 if (assignState(BB, CurrentState)) {
727 Worklist.enqueuePredecessors(BB);
734 checkEntry(&FunctionCFG.getEntry());
739 CurrentState = joinSuccessors(BB);
740 assert(CurrentState.isVisited() &&
741 "Shouldn't start with a 'not visited' state");
753 for (
const CFGElement &Element : llvm::reverse(*BB)) {
754 if (std::optional<CFGStmt> S = Element.
getAs<
CFGStmt>()) {
761 void checkEntry(
const CFGBlock *Entry) {
767 const State &EntryStatus = getState(Entry);
768 llvm::BitVector NotCalledOnEveryPath(size(),
false);
769 llvm::BitVector NotUsedOnEveryPath(size(),
false);
772 for (
const auto &IndexedStatus : llvm::enumerate(EntryStatus)) {
775 switch (IndexedStatus.value().getKind()) {
776 case ParameterStatus::NotCalled:
780 if (!hasEverEscaped(IndexedStatus.index())) {
794 NotUsedOnEveryPath[IndexedStatus.index()] =
true;
798 case ParameterStatus::MaybeCalled:
806 NotCalledOnEveryPath[IndexedStatus.index()] =
true;
814 if (NotCalledOnEveryPath.none() && NotUsedOnEveryPath.none() &&
818 !FunctionHasCleanupVars)
839 for (
const CFGBlock *BB : FunctionCFG) {
843 const State &BlockState = getState(BB);
845 for (
unsigned Index : llvm::seq(0u, size())) {
855 if (NotCalledOnEveryPath[Index] &&
856 BlockState.getKindFor(Index) == ParameterStatus::MaybeCalled) {
858 findAndReportNotCalledBranches(BB, Index);
859 }
else if (NotUsedOnEveryPath[Index] &&
860 isLosingEscape(BlockState, BB, Index)) {
862 findAndReportNotCalledBranches(BB, Index,
true);
870 if (
auto Index = getIndexOfCallee(
Call)) {
871 processCallFor(*Index,
Call);
878 template <
class CallLikeExpr>
879 void checkIndirectCall(
const CallLikeExpr *CallOrMessage) {
882 llvm::ArrayRef(CallOrMessage->getArgs(), CallOrMessage->getNumArgs());
885 for (
const auto &Argument : llvm::enumerate(Arguments)) {
886 if (
auto Index = getIndexOfExpression(Argument.value())) {
887 if (shouldBeCalledOnce(CallOrMessage, Argument.index())) {
890 processCallFor(*Index, CallOrMessage);
894 processEscapeFor(*Index);
902 void processCallFor(
unsigned Index,
const Expr *
Call) {
903 ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(Index);
905 if (CurrentParamStatus.seenAnyCalls()) {
914 CurrentParamStatus.getKind() == ParameterStatus::DefinitelyCalled);
918 CurrentParamStatus = ParameterStatus::Reported;
920 }
else if (CurrentParamStatus.getKind() != ParameterStatus::Reported) {
923 ParameterStatus Called(ParameterStatus::DefinitelyCalled,
Call);
924 CurrentParamStatus = Called;
929 void processEscapeFor(
unsigned Index) {
930 ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(Index);
933 if (CurrentParamStatus.isErrorStatus() &&
934 CurrentParamStatus.getKind() != ParameterStatus::Kind::Reported) {
935 CurrentParamStatus = ParameterStatus::Escaped;
939 void findAndReportNotCalledBranches(
const CFGBlock *
Parent,
unsigned Index,
940 bool IsEscape =
false) {
945 if (getState(Succ).getKindFor(Index) == ParameterStatus::NotCalled) {
946 assert(
Parent->succ_size() >= 2 &&
947 "Block should have at least two successors at this point");
948 if (
auto Clarification = NotCalledClarifier::clarify(
Parent, Succ)) {
951 Parameter, AC.getDecl(), Clarification->Location,
952 Clarification->Reason, !IsEscape, !isExplicitlyMarked(
Parameter));
964 return Parameter->hasAttr<CalledOnceAttr>();
968 static bool isConventional(llvm::StringRef Name) {
969 return llvm::count(CONVENTIONAL_NAMES, Name) != 0;
973 static bool hasConventionalSuffix(llvm::StringRef Name) {
974 return llvm::any_of(CONVENTIONAL_SUFFIXES, [Name](llvm::StringRef Suffix) {
975 return Name.ends_with(Suffix);
980 static bool isConventional(
QualType Ty) {
991 static bool isOnlyParameterConventional(
const FunctionDecl *Function) {
993 return Function->getNumParams() == 1 && II &&
994 hasConventionalSuffix(II->
getName());
1001 static std::optional<bool> isConventionalSwiftAsync(
const Decl *
D,
1002 unsigned ParamIndex) {
1003 if (
const SwiftAsyncAttr *A =
D->
getAttr<SwiftAsyncAttr>()) {
1004 if (A->getKind() == SwiftAsyncAttr::None) {
1008 return A->getCompletionHandlerIndex().getASTIndex() == ParamIndex;
1010 return std::nullopt;
1014 static bool isInitMethod(
Selector MethodSelector) {
1019 static bool isConventionalSelectorPiece(
Selector MethodSelector,
1020 unsigned PieceIndex,
1022 if (!isConventional(PieceType) || isInitMethod(MethodSelector)) {
1027 assert(PieceIndex == 0);
1031 llvm::StringRef PieceName = MethodSelector.
getNameForSlot(PieceIndex);
1032 return isConventional(PieceName) || hasConventionalSuffix(PieceName);
1037 (CheckConventionalParameters &&
1038 (isConventional(
Parameter->getName()) ||
1039 hasConventionalSuffix(
Parameter->getName())) &&
1043 bool shouldBeCalledOnce(
const DeclContext *ParamContext,
1046 if (
const auto *Function = dyn_cast<FunctionDecl>(ParamContext)) {
1047 return shouldBeCalledOnce(Function, ParamIndex);
1049 if (
const auto *Method = dyn_cast<ObjCMethodDecl>(ParamContext)) {
1050 return shouldBeCalledOnce(Method, ParamIndex);
1052 return shouldBeCalledOnce(Param);
1055 bool shouldBeCalledOnce(
const BlockDecl *
Block,
unsigned ParamIndex)
const {
1056 return shouldBeCalledOnce(
Block->getParamDecl(ParamIndex));
1060 unsigned ParamIndex)
const {
1061 if (ParamIndex >=
Function->getNumParams()) {
1065 if (
auto ConventionalAsync =
1066 isConventionalSwiftAsync(Function, ParamIndex)) {
1067 return *ConventionalAsync;
1070 return shouldBeCalledOnce(
Function->getParamDecl(ParamIndex)) ||
1071 (CheckConventionalParameters &&
1072 isOnlyParameterConventional(Function));
1076 unsigned ParamIndex)
const {
1078 if (ParamIndex >= MethodSelector.
getNumArgs()) {
1083 if (
auto ConventionalAsync = isConventionalSwiftAsync(Method, ParamIndex)) {
1084 return *ConventionalAsync;
1089 (CheckConventionalParameters &&
1090 isConventionalSelectorPiece(MethodSelector, ParamIndex,
1094 bool shouldBeCalledOnce(
const CallExpr *
Call,
unsigned ParamIndex)
const {
1096 return Function && shouldBeCalledOnce(Function, ParamIndex);
1100 unsigned ParamIndex)
const {
1103 shouldBeCalledOnce(Method, ParamIndex);
1111 if (
const BlockDecl *
Block = dyn_cast<BlockDecl>(AC.getDecl())) {
1129 Current !=
nullptr; Prev = Current, Current = PM.
getParent(Current)) {
1131 if (isa<CastExpr>(Current) || isa<ParenExpr>(Current))
1136 if (
const auto *
Call = dyn_cast<CallExpr>(Current)) {
1138 if (
Call->getCallee() == Prev)
1142 return shouldBlockArgumentBeCalledOnce(
Call, Prev) ?
Call :
nullptr;
1144 if (
const auto *Message = dyn_cast<ObjCMessageExpr>(Current)) {
1145 return shouldBlockArgumentBeCalledOnce(Message, Prev) ? Message
1155 template <
class CallLikeExpr>
1156 bool shouldBlockArgumentBeCalledOnce(
const CallLikeExpr *CallOrMessage,
1157 const Stmt *BlockArgument)
const {
1160 llvm::ArrayRef(CallOrMessage->getArgs(), CallOrMessage->getNumArgs());
1162 for (
const auto &Argument : llvm::enumerate(Arguments)) {
1163 if (Argument.value() == BlockArgument) {
1164 return shouldBlockArgumentBeCalledOnce(CallOrMessage, Argument.index());
1171 bool shouldBlockArgumentBeCalledOnce(
const CallExpr *
Call,
1172 unsigned ParamIndex)
const {
1174 return shouldBlockArgumentBeCalledOnce(Function, ParamIndex) ||
1175 shouldBeCalledOnce(
Call, ParamIndex);
1179 unsigned ParamIndex)
const {
1182 return shouldBeCalledOnce(Message, ParamIndex);
1185 static bool shouldBlockArgumentBeCalledOnce(
const FunctionDecl *Function,
1186 unsigned ParamIndex) {
1193 llvm::any_of(KNOWN_CALLED_ONCE_PARAMETERS,
1194 [Function, ParamIndex](
1195 const KnownCalledOnceParameter &
Reference) {
1212 bool isPossiblyEmptyImpl()
const {
1213 if (!isa<ObjCMethodDecl>(AC.getDecl())) {
1220 if (FunctionCFG.size() == 2) {
1227 if (FunctionCFG.size() == 3) {
1228 const CFGBlock &Entry = FunctionCFG.getEntry();
1251 return llvm::all_of(FunctionCFG, [](
const CFGBlock *BB) {
1261 std::unique_ptr<ParentMap> ReturnChildren;
1263 return llvm::all_of(
1266 [&ReturnChildren](
const CFGElement &Element) {
1267 if (std::optional<CFGStmt> S = Element.
getAs<
CFGStmt>()) {
1268 const Stmt *SuspiciousStmt = S->getStmt();
1270 if (isa<ReturnStmt>(SuspiciousStmt)) {
1273 ReturnChildren = std::make_unique<ParentMap>(
1274 const_cast<Stmt *>(SuspiciousStmt));
1279 return SuspiciousStmt->getBeginLoc().isMacroID() ||
1281 ReturnChildren->hasParent(SuspiciousStmt));
1289 bool hasEverEscaped(
unsigned Index)
const {
1290 return llvm::any_of(States, [Index](
const State &StateForOneBB) {
1291 return StateForOneBB.getKindFor(Index) == ParameterStatus::Escaped;
1297 State &getState(
const CFGBlock *BB) {
1301 const State &getState(
const CFGBlock *BB)
const {
1310 bool assignState(
const CFGBlock *BB,
const State &ToAssign) {
1311 State &Current = getState(BB);
1312 if (Current == ToAssign) {
1321 State joinSuccessors(
const CFGBlock *BB)
const {
1323 llvm::make_filter_range(BB->
succs(), [
this](
const CFGBlock *Succ) {
1324 return Succ && this->getState(Succ).isVisited();
1327 assert(!Succs.empty() &&
1328 "Basic block should have at least one visited successor");
1330 State Result = getState(*Succs.begin());
1332 for (
const CFGBlock *Succ : llvm::drop_begin(Succs, 1)) {
1333 Result.join(getState(Succ));
1337 handleConditional(BB,
Condition, Result);
1344 State &ToAlter)
const {
1345 handleParameterCheck(BB,
Condition, ToAlter);
1346 if (SuppressOnConventionalErrorPaths) {
1347 handleConventionalCheck(BB,
Condition, ToAlter);
1352 State &ToAlter)
const {
1367 ParameterStatus &CurrentStatus = ToAlter.getStatusFor(*Index);
1379 const ParameterStatus &StatusInSucc =
1380 getState(Succ).getStatusFor(*Index);
1382 if (StatusInSucc.isErrorStatus()) {
1387 CurrentStatus = StatusInSucc;
1389 if (StatusInSucc.getKind() == ParameterStatus::DefinitelyCalled) {
1402 State &ToAlter)
const {
1406 if (!mentionsAnyOfConventionalNames(
Condition)) {
1410 for (
const auto &IndexedStatus : llvm::enumerate(ToAlter)) {
1417 ParameterStatus &CurrentStatus = IndexedStatus.value();
1426 if (isLosingCall(ToAlter, BB, IndexedStatus.index()) ||
1427 isLosingEscape(ToAlter, BB, IndexedStatus.index())) {
1428 CurrentStatus = ParameterStatus::Escaped;
1433 bool isLosingCall(
const State &StateAfterJoin,
const CFGBlock *JoinBlock,
1434 unsigned ParameterIndex)
const {
1437 return isLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex,
1438 ParameterStatus::MaybeCalled,
1439 ParameterStatus::DefinitelyCalled);
1442 bool isLosingEscape(
const State &StateAfterJoin,
const CFGBlock *JoinBlock,
1443 unsigned ParameterIndex)
const {
1445 return isLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex,
1446 ParameterStatus::NotCalled, ParameterStatus::Escaped);
1449 bool isLosingJoin(
const State &StateAfterJoin,
const CFGBlock *JoinBlock,
1450 unsigned ParameterIndex, ParameterStatus::Kind AfterJoin,
1451 ParameterStatus::Kind BeforeJoin)
const {
1452 assert(!ParameterStatus::isErrorStatus(BeforeJoin) &&
1453 ParameterStatus::isErrorStatus(AfterJoin) &&
1454 "It's not a losing join if statuses do not represent "
1455 "correct-to-error transition");
1457 const ParameterStatus &CurrentStatus =
1458 StateAfterJoin.getStatusFor(ParameterIndex);
1460 return CurrentStatus.getKind() == AfterJoin &&
1461 anySuccessorHasStatus(JoinBlock, ParameterIndex, BeforeJoin);
1466 bool anySuccessorHasStatus(
const CFGBlock *
Parent,
unsigned ParameterIndex,
1467 ParameterStatus::Kind ToFind)
const {
1468 return llvm::any_of(
1469 Parent->succs(), [
this, ParameterIndex, ToFind](
const CFGBlock *Succ) {
1470 return Succ && getState(Succ).getKindFor(ParameterIndex) == ToFind;
1475 void checkEscapee(
const Expr *
E) {
1484 processEscapeFor(*Index);
1489 void markNoReturn() {
1490 for (ParameterStatus &PS : CurrentState) {
1491 PS = ParameterStatus::NoReturn;
1500 if (
auto Index = getIndexOfExpression(
Assignment->getLHS())) {
1505 Assignment->getRHS()->IgnoreParenCasts()->getIntegerConstantExpr(
1506 AC.getASTContext())) {
1508 ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(*Index);
1510 if (0 == *Constant && CurrentParamStatus.seenAnyCalls()) {
1519 CurrentParamStatus = ParameterStatus::Reported;
1532 checkDirectCall(
Call);
1534 checkIndirectCall(
Call);
1540 if (
const Expr *Receiver = Message->getInstanceReceiver()) {
1541 checkEscapee(Receiver);
1544 checkIndirectCall(Message);
1561 const Expr *CalledOnceCallSite = getBlockGuaraneedCallSite(
Block);
1566 if (CalledOnceCallSite) {
1572 for (
const auto &
Capture :
Block->getBlockDecl()->captures()) {
1574 if (
auto Index =
getIndex(*Param)) {
1575 if (CalledOnceCallSite) {
1578 processCallFor(*Index, CalledOnceCallSite);
1583 processEscapeFor(*Index);
1591 if (Op->
getOpcode() == clang::BO_Assign) {
1595 checkEscapee(Op->
getRHS());
1598 checkSuppression(Op);
1602 void VisitDeclStmt(
const DeclStmt *DS) {
1608 if (
const auto *Var = dyn_cast<VarDecl>(
Declaration)) {
1609 if (Var->getInit()) {
1610 checkEscapee(Var->getInit());
1613 if (Var->hasAttr<CleanupAttr>()) {
1614 FunctionHasCleanupVars =
true;
1624 if (
Cast->getType().getCanonicalType()->isVoidType()) {
1625 checkEscapee(
Cast->getSubExpr());
1635 unsigned size()
const {
return TrackedParams.size(); }
1637 std::optional<unsigned> getIndexOfCallee(
const CallExpr *
Call)
const {
1638 return getIndexOfExpression(
Call->getCallee());
1641 std::optional<unsigned> getIndexOfExpression(
const Expr *
E)
const {
1646 return std::nullopt;
1657 ParamSizedVector<const ParmVarDecl *>::const_iterator It =
1660 if (It != TrackedParams.end()) {
1661 return It - TrackedParams.begin();
1664 return std::nullopt;
1667 const ParmVarDecl *getParameter(
unsigned Index)
const {
1668 assert(Index < TrackedParams.size());
1669 return TrackedParams[Index];
1672 const CFG &FunctionCFG;
1675 bool CheckConventionalParameters;
1682 bool SuppressOnConventionalErrorPaths =
false;
1689 bool FunctionHasCleanupVars =
false;
1692 ParamSizedVector<const ParmVarDecl *> TrackedParams;
1693 CFGSizedVector<State> States;
1701 bool CheckConventionalParameters) {
1702 CalledOnceChecker::check(AC, Handler, CheckConventionalParameters);
Defines the clang::ASTContext interface.
This file defines AnalysisDeclContext, a class that manages the analysis context data for context sen...
Defines enum values for all the target-independent builtin functions.
static std::optional< NonLoc > getIndex(ProgramStateRef State, const ElementRegion *ER, CharKind CK)
@ LLVM_MARK_AS_BITMASK_ENUM
static Decl::Kind getKind(const Decl *D)
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the Objective-C statement AST node classes.
static QualType getPointeeType(const MemRegion *R)
C Language Family Type Representation.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
AnalysisDeclContext contains the context data for the function, method or block under analysis.
A builtin binary operation expression such as "x + y" or "x <= y".
Represents a block literal declaration, which is like an unnamed FunctionDecl.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Represents a single basic block in a source-level CFG.
bool hasNoReturnElement() const
succ_iterator succ_begin()
Stmt * getTerminatorStmt()
unsigned getBlockID() const
AdjacentBlocks::const_iterator const_succ_iterator
Represents a top-level expression in a basic block.
std::optional< T > getAs() const
Convert to the specified CFGElement type, returning std::nullopt if this CFGElement is not of the des...
Represents a source-level, intra-procedural CFG that represents the control-flow of a Stmt.
CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style cast in C++ (C++ [expr....
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
unsigned getBuiltinCallee() const
getBuiltinCallee - If this is a call to a builtin, return the builtin ID of the callee.
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
virtual void handleBlockThatIsGuaranteedToBeCalledOnce(const BlockDecl *Block)
Called when the block is guaranteed to be called exactly once.
virtual void handleBlockWithNoGuarantees(const BlockDecl *Block)
Called when the block has no guarantees about how many times it can get called.
virtual void handleDoubleCall(const ParmVarDecl *Parameter, const Expr *Call, const Expr *PrevCall, bool IsCompletionHandler, bool Poised)
Called when parameter is called twice.
virtual void handleNeverCalled(const ParmVarDecl *Parameter, bool IsCompletionHandler)
Called when parameter is not called at all.
virtual void handleCapturedNeverCalled(const ParmVarDecl *Parameter, const Decl *Where, bool IsCompletionHandler)
Called when captured parameter is not called at all.
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
A reference to a declared variable, function, enum, etc.
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
const DeclGroupRef getDeclGroup() const
Decl - This represents one declaration (or definition), e.g.
Recursive AST visitor that supports extension via dynamic dispatch.
This represents one expression.
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Represents a function declaration or definition.
FunctionType - C99 6.7.5.3 - Function Declarators.
One of these records is kept for each identifier that is lexed.
StringRef getName() const
Return the actual identifier string.
IfStmt - This represents an if/then/else.
Represents Objective-C's @throw statement.
An expression that sends a message to the given Objective-C object or class.
ObjCMethodDecl - Represents an instance or class method declaration.
Selector getSelector() const
ObjCPropertyRefExpr - A dot-syntax expression to access an ObjC property.
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Stmt * getParent(Stmt *) const
Represents a parameter to a function.
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
A (possibly-)qualified type.
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
ObjCMethodFamily getMethodFamily() const
Derive the conventional family of this method.
unsigned getNumArgs() const
RetTy Visit(PTR(Stmt) S, ParamTys... P)
Stmt - This represents one statement.
SwitchStmt - This represents a 'switch' stmt.
bool isBlockPointerType() const
const T * castAs() const
Member-template castAs<specific type>.
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Expr * getSubExpr() const
WhileStmt - This represents a 'while' stmt.
ValueDecl * getVariable() const
bool Call(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
bool Cast(InterpState &S, CodePtr OpPC)
The JSON file list parser is used to communicate input to InstallAPI.
@ Conditional
A conditional (?:) operator.
@ If
'if' clause, allowed on all the Compute Constructs, Data Constructs, Executable Constructs,...
bool operator==(const CallGraphNode::CallRecord &LHS, const CallGraphNode::CallRecord &RHS)
@ Parameter
The parameter type of a method or function.
void checkCalledOnceParameters(AnalysisDeclContext &AC, CalledOnceCheckHandler &Handler, bool CheckConventionalParameters)
Check given CFG for 'called once' parameter violations.
@ Other
Other implicit parameter.
A worklist implementation for backward dataflow analysis.