;
45static constexpr unsignedEXPECTED_MAX_NUMBER_OF_PARAMS = 2;
48static constexpr unsignedEXPECTED_NUMBER_OF_BASIC_BLOCKS = 8;
51constexprllvm::StringLiteral CONVENTIONAL_NAMES[] = {
52 "completionHandler",
"completion",
"withCompletionHandler",
53 "withCompletion",
"completionBlock",
"withCompletionBlock",
54 "replyTo",
"reply",
"withReplyTo"};
55constexprllvm::StringLiteral CONVENTIONAL_SUFFIXES[] = {
56 "WithCompletionHandler",
"WithCompletion",
"WithCompletionBlock",
57 "WithReplyTo",
"WithReply"};
58constexprllvm::StringLiteral CONVENTIONAL_CONDITIONS[] = {
59 "error",
"cancel",
"shouldCall",
"done",
"OK",
"success"};
61structKnownCalledOnceParameter {
62llvm::StringLiteral FunctionName;
65constexprKnownCalledOnceParameter KNOWN_CALLED_ONCE_PARAMETERS[] = {
66{llvm::StringLiteral{
"dispatch_async"}, 1},
67{llvm::StringLiteral{
"dispatch_async_and_wait"}, 1},
68{llvm::StringLiteral{
"dispatch_after"}, 2},
69{llvm::StringLiteral{
"dispatch_sync"}, 1},
70{llvm::StringLiteral{
"dispatch_once"}, 1},
71{llvm::StringLiteral{
"dispatch_barrier_async"}, 1},
72{llvm::StringLiteral{
"dispatch_barrier_async_and_wait"}, 1},
73{llvm::StringLiteral{
"dispatch_barrier_sync"}, 1}};
75classParameterStatus {
154DefinitelyCalled = 0x3,
156NON_ERROR_STATUS = DefinitelyCalled,
170 constexprParameterStatus() =
default;
171ParameterStatus(Kind K) : StatusKind(K) {
172assert(!seenAnyCalls(K) &&
"Can't initialize status without a call");
174ParameterStatus(Kind K,
const Expr*Call) : StatusKind(K),
Call(
Call) {
175assert(seenAnyCalls(K) &&
"This kind is not supposed to have a call");
178 const Expr&getCall()
const{
179assert(seenAnyCalls(
getKind()) &&
"ParameterStatus doesn't have a call");
182 static boolseenAnyCalls(Kind K) {
183 return(K & DefinitelyCalled) == DefinitelyCalled && K != Reported;
185 boolseenAnyCalls()
const{
returnseenAnyCalls(
getKind()); }
187 static boolisErrorStatus(Kind K) {
returnK > NON_ERROR_STATUS; }
188 boolisErrorStatus()
const{
returnisErrorStatus(
getKind()); }
192 voidjoin(
constParameterStatus &
Other) {
202StatusKind |=
Other.getKind();
214 KindStatusKind = NotVisited;
221State(
unsignedSize, ParameterStatus::Kind K = ParameterStatus::NotVisited)
222: ParamData(
Size, K) {}
226ParameterStatus &getStatusFor(
unsignedIndex) {
returnParamData[Index]; }
227 constParameterStatus &getStatusFor(
unsignedIndex)
const{
228 returnParamData[Index];
233 boolseenAnyCalls(
unsignedIndex)
const{
234 returngetStatusFor(Index).seenAnyCalls();
239 const Expr&getCallFor(
unsignedIndex)
const{
240 returngetStatusFor(Index).getCall();
243ParameterStatus::Kind getKindFor(
unsignedIndex)
const{
244 returngetStatusFor(Index).getKind();
247 boolisVisited()
const{
248 returnllvm::all_of(ParamData, [](
constParameterStatus &S) {
249 returnS.getKind() != ParameterStatus::NotVisited;
254 voidjoin(
constState &
Other) {
255assert(ParamData.size() ==
Other.ParamData.size() &&
256 "Couldn't join statuses with different sizes");
257 for(
autoPair : llvm::zip(ParamData,
Other.ParamData)) {
258std::get<0>(Pair).join(std::get<1>(Pair));
262 usingiterator = ParamSizedVector<ParameterStatus>::iterator;
263 usingconst_iterator = ParamSizedVector<ParameterStatus>::const_iterator;
265iterator begin() {
returnParamData.begin(); }
266iterator end() {
returnParamData.end(); }
268const_iterator begin()
const{
returnParamData.begin(); }
269const_iterator end()
const{
returnParamData.end(); }
272 returnParamData ==
Other.ParamData;
276ParamSizedVector<ParameterStatus> ParamData;
310 boolShouldRetrieveFromComparisons =
false) {
311 returnDeclRefFinder(ShouldRetrieveFromComparisons).Visit(
E);
320 if(!ShouldRetrieveFromComparisons)
334 if(!ShouldRetrieveFromComparisons)
353 if(!ShouldRetrieveFromComparisons)
359 caseBuiltin::BI__builtin_expect:
360 caseBuiltin::BI__builtin_expect_with_probability: {
364 returnCandidate !=
nullptr? Candidate :
Visit(CE->
getArg(1));
367 caseBuiltin::BI__builtin_unpredictable:
382 return E!= DeclutteredExpr ?
Visit(DeclutteredExpr) : nullptr;
386DeclRefFinder(
boolShouldRetrieveFromComparisons)
387: ShouldRetrieveFromComparisons(ShouldRetrieveFromComparisons) {}
389 boolShouldRetrieveFromComparisons;
393 boolShouldRetrieveFromComparisons =
false) {
394 returnDeclRefFinder::find(In, ShouldRetrieveFromComparisons);
398findReferencedParmVarDecl(
const Expr*In,
399 boolShouldRetrieveFromComparisons =
false) {
401findDeclRefExpr(In, ShouldRetrieveFromComparisons)) {
402 returndyn_cast<ParmVarDecl>(DR->getDecl());
409const Expr*getCondition(
const Stmt*S) {
414 if(
const auto*
If= dyn_cast<IfStmt>(S)) {
415 return If->getCond();
417 if(
const auto*Ternary = dyn_cast<AbstractConditionalOperator>(S)) {
418 returnTernary->getCond();
431 static constexpr unsignedEXPECTED_NUMBER_OF_NAMES = 5;
432 usingNameCollection =
435 staticNameCollection collect(
const Expr*From) {
437Impl.TraverseStmt(
const_cast<Expr*
>(From));
442Result.push_back(
E->getDecl()->getName());
447llvm::StringRef Name;
449 if(
E->isImplicitProperty()) {
451 if(
E->isMessagingGetter()) {
452PropertyMethodDecl =
E->getImplicitPropertyGetter();
454PropertyMethodDecl =
E->getImplicitPropertySetter();
456assert(PropertyMethodDecl &&
457 "Implicit property must have associated declaration");
460assert(
E->isExplicitProperty());
461Name =
E->getExplicitProperty()->getName();
464Result.push_back(Name);
469NamesCollector() =
default;
470NameCollection Result;
474boolmentionsAnyOfConventionalNames(
const Expr*
E) {
477 returnllvm::any_of(MentionedNames, [](llvm::StringRef ConditionName) {
479CONVENTIONAL_CONDITIONS,
480[ConditionName](
constllvm::StringLiteral &Conventional) {
481 returnConditionName.contains_insensitive(Conventional);
488structClarification {
490 const Stmt*Location;
495classNotCalledClarifier
497std::optional<Clarification>> {
511 staticstd::optional<Clarification> clarify(
const CFGBlock*Conditional,
514 returnNotCalledClarifier{
Conditional, SuccWithoutCall}.Visit(Terminator);
519std::optional<Clarification> VisitIfStmt(
const IfStmt*
If) {
520 returnVisitBranchingBlock(
If, NeverCalledReason::IfThen);
523std::optional<Clarification>
525 returnVisitBranchingBlock(Ternary, NeverCalledReason::IfThen);
529 const Stmt*CaseToBlame = SuccInQuestion->getLabel();
537Case = Case->getNextSwitchCase()) {
538 if(Case == CaseToBlame) {
543llvm_unreachable(
"Found unexpected switch structure");
546std::optional<Clarification> VisitForStmt(
const ForStmt*For) {
547 returnVisitBranchingBlock(For, NeverCalledReason::LoopEntered);
550std::optional<Clarification> VisitWhileStmt(
const WhileStmt*While) {
551 returnVisitBranchingBlock(While, NeverCalledReason::LoopEntered);
554std::optional<Clarification>
556assert(
Parent->succ_size() == 2 &&
557 "Branching block should have exactly two successors");
558 unsignedSuccessorIndex = getSuccessorIndex(Parent, SuccInQuestion);
560updateForSuccessor(DefaultReason, SuccessorIndex);
561 returnClarification{ActualReason, Terminator};
564std::optional<Clarification> VisitBinaryOperator(
const BinaryOperator*) {
569std::optional<Clarification> VisitStmt(
const Stmt*Terminator) {
578 static unsignedgetSuccessorIndex(
const CFGBlock*Parent,
581assert(It !=
Parent->succ_end() &&
582 "Given blocks should be in parent-child relationship");
583 returnIt -
Parent->succ_begin();
588 unsignedSuccessorIndex) {
589assert(SuccessorIndex <= 1);
591 static_cast<unsigned>(ReasonForTrueBranch) + SuccessorIndex;
593 static_cast<unsigned>(NeverCalledReason::LARGEST_VALUE));
607 boolCheckConventionalParameters) {
608CalledOnceChecker(AC, Handler, CheckConventionalParameters).check();
613 boolCheckConventionalParameters)
614: FunctionCFG(*AC.getCFG()), AC(AC), Handler(Handler),
615CheckConventionalParameters(CheckConventionalParameters),
617initDataStructures();
618assert((size() == 0 || !States.empty()) &&
619 "Data structures are inconsistent");
626 voidinitDataStructures() {
627 const Decl*AnalyzedDecl = AC.getDecl();
629 if(
const auto*Function = dyn_cast<FunctionDecl>(AnalyzedDecl)) {
630findParamsToTrack(Function);
631}
else if(
const auto*Method = dyn_cast<ObjCMethodDecl>(AnalyzedDecl)) {
632findParamsToTrack(Method);
633}
else if(
const auto*
Block= dyn_cast<BlockDecl>(AnalyzedDecl)) {
634findCapturesToTrack(
Block);
635findParamsToTrack(
Block);
641CFGSizedVector<State>(FunctionCFG.getNumBlockIDs(), State(size()));
650 if(shouldBeCalledOnce(ParamContext,
P)) {
651TrackedParams.push_back(
P);
657 template<
classFunctionLikeDecl>
658 voidfindParamsToTrack(
constFunctionLikeDecl *Function) {
659 for(
unsignedIndex : llvm::seq<unsigned>(0u,
Function->param_size())) {
660 if(shouldBeCalledOnce(Function, Index)) {
661TrackedParams.push_back(
Function->getParamDecl(Index));
672 if(size() == 0 || isPossiblyEmptyImpl())
676llvm::none_of(States, [](
constState &S) {
returnS.isVisited(); }) &&
677 "None of the blocks should be 'visited' before the analysis");
716 const CFGBlock*Exit = &FunctionCFG.getExit();
717assignState(Exit, State(size(), ParameterStatus::NotCalled));
718Worklist.enqueuePredecessors(Exit);
720 while(
const CFGBlock*BB = Worklist.dequeue()) {
721assert(BB &&
"Worklist should filter out null blocks");
723assert(CurrentState.isVisited() &&
724 "After the check, basic block should be visited");
728 if(assignState(BB, CurrentState)) {
729Worklist.enqueuePredecessors(BB);
736checkEntry(&FunctionCFG.getEntry());
741CurrentState = joinSuccessors(BB);
742assert(CurrentState.isVisited() &&
743 "Shouldn't start with a 'not visited' state");
755 for(
const CFGElement&Element : llvm::reverse(*BB)) {
756 if(std::optional<CFGStmt> S = Element.
getAs<
CFGStmt>()) {
761 voidcheck(
const Stmt*S) {
Visit(S); }
763 voidcheckEntry(
const CFGBlock*Entry) {
769 constState &EntryStatus = getState(Entry);
770llvm::BitVector NotCalledOnEveryPath(size(),
false);
771llvm::BitVector NotUsedOnEveryPath(size(),
false);
774 for(
const auto&IndexedStatus : llvm::enumerate(EntryStatus)) {
777 switch(IndexedStatus.value().getKind()) {
778 caseParameterStatus::NotCalled:
782 if(!hasEverEscaped(IndexedStatus.index())) {
796NotUsedOnEveryPath[IndexedStatus.index()] =
true;
800 caseParameterStatus::MaybeCalled:
808NotCalledOnEveryPath[IndexedStatus.index()] =
true;
816 if(NotCalledOnEveryPath.none() && NotUsedOnEveryPath.none() &&
820!FunctionHasCleanupVars)
841 for(
const CFGBlock*BB : FunctionCFG) {
845 constState &BlockState = getState(BB);
847 for(
unsignedIndex : llvm::seq(0u, size())) {
857 if(NotCalledOnEveryPath[Index] &&
858BlockState.getKindFor(Index) == ParameterStatus::MaybeCalled) {
860findAndReportNotCalledBranches(BB, Index);
861}
else if(NotUsedOnEveryPath[Index] &&
862isLosingEscape(BlockState, BB, Index)) {
864findAndReportNotCalledBranches(BB, Index,
true);
872 if(
autoIndex = getIndexOfCallee(
Call)) {
873processCallFor(*Index,
Call);
880 template<
classCallLikeExpr>
881 voidcheckIndirectCall(
constCallLikeExpr *CallOrMessage) {
884 llvm::ArrayRef(CallOrMessage->getArgs(), CallOrMessage->getNumArgs());
887 for(
const auto&Argument : llvm::enumerate(Arguments)) {
888 if(
autoIndex = getIndexOfExpression(Argument.value())) {
889 if(shouldBeCalledOnce(CallOrMessage, Argument.index())) {
892processCallFor(*Index, CallOrMessage);
896processEscapeFor(*Index);
904 voidprocessCallFor(
unsignedIndex,
const Expr*
Call) {
905ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(Index);
907 if(CurrentParamStatus.seenAnyCalls()) {
916CurrentParamStatus.getKind() == ParameterStatus::DefinitelyCalled);
920CurrentParamStatus = ParameterStatus::Reported;
922}
else if(CurrentParamStatus.getKind() != ParameterStatus::Reported) {
925ParameterStatus Called(ParameterStatus::DefinitelyCalled,
Call);
926CurrentParamStatus = Called;
931 voidprocessEscapeFor(
unsignedIndex) {
932ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(Index);
935 if(CurrentParamStatus.isErrorStatus() &&
936CurrentParamStatus.getKind() != ParameterStatus::Kind::Reported) {
937CurrentParamStatus = ParameterStatus::Escaped;
941 voidfindAndReportNotCalledBranches(
const CFGBlock*
Parent,
unsignedIndex,
942 boolIsEscape =
false) {
947 if(getState(Succ).getKindFor(Index) == ParameterStatus::NotCalled) {
948assert(
Parent->succ_size() >= 2 &&
949 "Block should have at least two successors at this point");
950 if(
autoClarification = NotCalledClarifier::clarify(
Parent, Succ)) {
953 Parameter, AC.getDecl(), Clarification->Location,
954Clarification->Reason, !IsEscape, !isExplicitlyMarked(
Parameter));
966 return Parameter->hasAttr<CalledOnceAttr>();
970 static boolisConventional(llvm::StringRef Name) {
971 returnllvm::count(CONVENTIONAL_NAMES, Name) != 0;
975 static boolhasConventionalSuffix(llvm::StringRef Name) {
976 returnllvm::any_of(CONVENTIONAL_SUFFIXES, [Name](llvm::StringRef Suffix) {
977 returnName.ends_with(Suffix);
982 static boolisConventional(
QualTypeTy) {
993 static boolisOnlyParameterConventional(
const FunctionDecl*Function) {
995 return Function->getNumParams() == 1 && II &&
996hasConventionalSuffix(II->
getName());
1003 staticstd::optional<bool> isConventionalSwiftAsync(
const Decl*
D,
1004 unsignedParamIndex) {
1005 if(
constSwiftAsyncAttr *A =
D->
getAttr<SwiftAsyncAttr>()) {
1006 if(A->getKind() == SwiftAsyncAttr::None) {
1010 returnA->getCompletionHandlerIndex().getASTIndex() == ParamIndex;
1012 returnstd::nullopt;
1016 static boolisInitMethod(
SelectorMethodSelector) {
1021 static boolisConventionalSelectorPiece(
SelectorMethodSelector,
1022 unsignedPieceIndex,
1024 if(!isConventional(PieceType) || isInitMethod(MethodSelector)) {
1029assert(PieceIndex == 0);
1030 returnhasConventionalSuffix(MethodSelector.
getNameForSlot(0));
1033llvm::StringRef PieceName = MethodSelector.
getNameForSlot(PieceIndex);
1034 returnisConventional(PieceName) || hasConventionalSuffix(PieceName);
1038 returnisExplicitlyMarked(
Parameter) ||
1039(CheckConventionalParameters &&
1040(isConventional(
Parameter->getName()) ||
1041hasConventionalSuffix(
Parameter->getName())) &&
1042isConventional(
Parameter->getType()));
1045 boolshouldBeCalledOnce(
const DeclContext*ParamContext,
1048 if(
const auto*Function = dyn_cast<FunctionDecl>(ParamContext)) {
1049 returnshouldBeCalledOnce(Function, ParamIndex);
1051 if(
const auto*Method = dyn_cast<ObjCMethodDecl>(ParamContext)) {
1052 returnshouldBeCalledOnce(Method, ParamIndex);
1054 returnshouldBeCalledOnce(Param);
1057 boolshouldBeCalledOnce(
const BlockDecl*
Block,
unsignedParamIndex)
const{
1058 returnshouldBeCalledOnce(
Block->getParamDecl(ParamIndex));
1062 unsignedParamIndex)
const{
1063 if(ParamIndex >=
Function->getNumParams()) {
1067 if(
autoConventionalAsync =
1068isConventionalSwiftAsync(Function, ParamIndex)) {
1069 return*ConventionalAsync;
1072 returnshouldBeCalledOnce(
Function->getParamDecl(ParamIndex)) ||
1073(CheckConventionalParameters &&
1074isOnlyParameterConventional(Function));
1078 unsignedParamIndex)
const{
1080 if(ParamIndex >= MethodSelector.
getNumArgs()) {
1085 if(
autoConventionalAsync = isConventionalSwiftAsync(Method, ParamIndex)) {
1086 return*ConventionalAsync;
1090 returnshouldBeCalledOnce(
Parameter) ||
1091(CheckConventionalParameters &&
1092isConventionalSelectorPiece(MethodSelector, ParamIndex,
1096 boolshouldBeCalledOnce(
const CallExpr*
Call,
unsignedParamIndex)
const{
1098 return Function&& shouldBeCalledOnce(Function, ParamIndex);
1102 unsignedParamIndex)
const{
1104 returnMethod && ParamIndex < Method->
param_size() &&
1105shouldBeCalledOnce(Method, ParamIndex);
1113 if(
const BlockDecl*
Block= dyn_cast<BlockDecl>(AC.getDecl())) {
1131Current !=
nullptr; Prev = Current, Current = PM.
getParent(Current)) {
1133 if(isa<CastExpr>(Current) || isa<ParenExpr>(Current))
1138 if(
const auto*
Call= dyn_cast<CallExpr>(Current)) {
1140 if(
Call->getCallee() == Prev)
1144 returnshouldBlockArgumentBeCalledOnce(
Call, Prev) ?
Call:
nullptr;
1146 if(
const auto*Message = dyn_cast<ObjCMessageExpr>(Current)) {
1147 returnshouldBlockArgumentBeCalledOnce(Message, Prev) ? Message
1157 template<
classCallLikeExpr>
1158 boolshouldBlockArgumentBeCalledOnce(
constCallLikeExpr *CallOrMessage,
1159 const Stmt*BlockArgument)
const{
1162 llvm::ArrayRef(CallOrMessage->getArgs(), CallOrMessage->getNumArgs());
1164 for(
const auto&Argument : llvm::enumerate(Arguments)) {
1165 if(Argument.value() == BlockArgument) {
1166 returnshouldBlockArgumentBeCalledOnce(CallOrMessage, Argument.index());
1173 boolshouldBlockArgumentBeCalledOnce(
const CallExpr*
Call,
1174 unsignedParamIndex)
const{
1176 returnshouldBlockArgumentBeCalledOnce(Function, ParamIndex) ||
1177shouldBeCalledOnce(
Call, ParamIndex);
1181 unsignedParamIndex)
const{
1184 returnshouldBeCalledOnce(Message, ParamIndex);
1187 static boolshouldBlockArgumentBeCalledOnce(
const FunctionDecl*Function,
1188 unsignedParamIndex) {
1195llvm::any_of(KNOWN_CALLED_ONCE_PARAMETERS,
1196[Function, ParamIndex](
1197 constKnownCalledOnceParameter &
Reference) {
1214 boolisPossiblyEmptyImpl()
const{
1215 if(!isa<ObjCMethodDecl>(AC.getDecl())) {
1222 if(FunctionCFG.size() == 2) {
1229 if(FunctionCFG.size() == 3) {
1230 const CFGBlock&Entry = FunctionCFG.getEntry();
1253 returnllvm::all_of(FunctionCFG, [](
const CFGBlock*BB) {
1263std::unique_ptr<ParentMap> ReturnChildren;
1265 returnllvm::all_of(
1268[&ReturnChildren](
const CFGElement&Element) {
1269 if(std::optional<CFGStmt> S = Element.
getAs<
CFGStmt>()) {
1270const Stmt *SuspiciousStmt = S->getStmt();
1272if (isa<ReturnStmt>(SuspiciousStmt)) {
1275ReturnChildren = std::make_unique<ParentMap>(
1276const_cast<Stmt *>(SuspiciousStmt));
1281 returnSuspiciousStmt->getBeginLoc().isMacroID() ||
1283ReturnChildren->hasParent(SuspiciousStmt));
1291 boolhasEverEscaped(
unsignedIndex)
const{
1292 returnllvm::any_of(States, [Index](
constState &StateForOneBB) {
1293 returnStateForOneBB.getKindFor(Index) == ParameterStatus::Escaped;
1299State &getState(
const CFGBlock*BB) {
1303 constState &getState(
const CFGBlock*BB)
const{
1312 boolassignState(
const CFGBlock*BB,
constState &ToAssign) {
1313State &Current = getState(BB);
1314 if(Current == ToAssign) {
1323State joinSuccessors(
const CFGBlock*BB)
const{
1325llvm::make_filter_range(BB->
succs(), [
this](
const CFGBlock*Succ) {
1326return Succ && this->getState(Succ).isVisited();
1329assert(!Succs.empty() &&
1330 "Basic block should have at least one visited successor");
1332State Result = getState(*Succs.begin());
1334 for(
const CFGBlock*Succ : llvm::drop_begin(Succs, 1)) {
1335Result.join(getState(Succ));
1339handleConditional(BB,
Condition, Result);
1346State &ToAlter)
const{
1347handleParameterCheck(BB,
Condition, ToAlter);
1348 if(SuppressOnConventionalErrorPaths) {
1349handleConventionalCheck(BB,
Condition, ToAlter);
1354State &ToAlter)
const{
1369ParameterStatus &CurrentStatus = ToAlter.getStatusFor(*Index);
1381 constParameterStatus &StatusInSucc =
1382getState(Succ).getStatusFor(*Index);
1384 if(StatusInSucc.isErrorStatus()) {
1389CurrentStatus = StatusInSucc;
1391 if(StatusInSucc.getKind() == ParameterStatus::DefinitelyCalled) {
1404State &ToAlter)
const{
1408 if(!mentionsAnyOfConventionalNames(
Condition)) {
1412 for(
const auto&IndexedStatus : llvm::enumerate(ToAlter)) {
1419ParameterStatus &CurrentStatus = IndexedStatus.value();
1428 if(isLosingCall(ToAlter, BB, IndexedStatus.index()) ||
1429isLosingEscape(ToAlter, BB, IndexedStatus.index())) {
1430CurrentStatus = ParameterStatus::Escaped;
1435 boolisLosingCall(
constState &StateAfterJoin,
const CFGBlock*JoinBlock,
1436 unsignedParameterIndex)
const{
1439 returnisLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex,
1440ParameterStatus::MaybeCalled,
1441ParameterStatus::DefinitelyCalled);
1444 boolisLosingEscape(
constState &StateAfterJoin,
const CFGBlock*JoinBlock,
1445 unsignedParameterIndex)
const{
1447 returnisLosingJoin(StateAfterJoin, JoinBlock, ParameterIndex,
1448ParameterStatus::NotCalled, ParameterStatus::Escaped);
1451 boolisLosingJoin(
constState &StateAfterJoin,
const CFGBlock*JoinBlock,
1452 unsignedParameterIndex, ParameterStatus::Kind AfterJoin,
1453ParameterStatus::Kind BeforeJoin)
const{
1454assert(!ParameterStatus::isErrorStatus(BeforeJoin) &&
1455ParameterStatus::isErrorStatus(AfterJoin) &&
1456 "It's not a losing join if statuses do not represent " 1457 "correct-to-error transition");
1459 constParameterStatus &CurrentStatus =
1460StateAfterJoin.getStatusFor(ParameterIndex);
1462 returnCurrentStatus.getKind() == AfterJoin &&
1463anySuccessorHasStatus(JoinBlock, ParameterIndex, BeforeJoin);
1468 boolanySuccessorHasStatus(
const CFGBlock*
Parent,
unsignedParameterIndex,
1469ParameterStatus::Kind ToFind)
const{
1470 returnllvm::any_of(
1471 Parent->succs(), [
this, ParameterIndex, ToFind](
const CFGBlock*Succ) {
1472return Succ && getState(Succ).getKindFor(ParameterIndex) == ToFind;
1477 voidcheckEscapee(
const Expr*
E) {
1486processEscapeFor(*Index);
1491 voidmarkNoReturn() {
1492 for(ParameterStatus &PS : CurrentState) {
1493PS = ParameterStatus::NoReturn;
1502 if(
autoIndex = getIndexOfExpression(
Assignment->getLHS())) {
1506 if(
autoConstant =
1507 Assignment->getRHS()->IgnoreParenCasts()->getIntegerConstantExpr(
1508AC.getASTContext())) {
1510ParameterStatus &CurrentParamStatus = CurrentState.getStatusFor(*Index);
1512 if(0 == *Constant && CurrentParamStatus.seenAnyCalls()) {
1521CurrentParamStatus = ParameterStatus::Reported;
1534checkDirectCall(
Call);
1536checkIndirectCall(
Call);
1542 if(
const Expr*Receiver = Message->getInstanceReceiver()) {
1543checkEscapee(Receiver);
1546checkIndirectCall(Message);
1563 const Expr*CalledOnceCallSite = getBlockGuaraneedCallSite(
Block);
1568 if(CalledOnceCallSite) {
1574 for(
const auto&
Capture:
Block->getBlockDecl()->captures()) {
1576 if(
autoIndex =
getIndex(*Param)) {
1577 if(CalledOnceCallSite) {
1580processCallFor(*Index, CalledOnceCallSite);
1585processEscapeFor(*Index);
1593 if(Op->
getOpcode() == clang::BO_Assign) {
1597checkEscapee(Op->
getRHS());
1600checkSuppression(Op);
1604 voidVisitDeclStmt(
const DeclStmt*DS) {
1610 if(
const auto*Var = dyn_cast<VarDecl>(
Declaration)) {
1611 if(Var->getInit()) {
1612checkEscapee(Var->getInit());
1615 if(Var->hasAttr<CleanupAttr>()) {
1616FunctionHasCleanupVars =
true;
1626 if(
Cast->getType().getCanonicalType()->isVoidType()) {
1627checkEscapee(
Cast->getSubExpr());
1637 unsignedsize()
const{
returnTrackedParams.size(); }
1639std::optional<unsigned> getIndexOfCallee(
const CallExpr*
Call)
const{
1640 returngetIndexOfExpression(
Call->getCallee());
1643std::optional<unsigned> getIndexOfExpression(
const Expr*
E)
const{
1648 returnstd::nullopt;
1659ParamSizedVector<const ParmVarDecl *>::const_iterator It =
1660llvm::find(TrackedParams, &
Parameter);
1662 if(It != TrackedParams.end()) {
1663 returnIt - TrackedParams.begin();
1666 returnstd::nullopt;
1669 const ParmVarDecl*getParameter(
unsignedIndex)
const{
1670assert(Index < TrackedParams.size());
1671 returnTrackedParams[Index];
1674 const CFG&FunctionCFG;
1677 boolCheckConventionalParameters;
1684 boolSuppressOnConventionalErrorPaths =
false;
1691 boolFunctionHasCleanupVars =
false;
1694ParamSizedVector<const ParmVarDecl *> TrackedParams;
1695CFGSizedVector<State> States;
1703 boolCheckConventionalParameters) {
1704CalledOnceChecker::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.
unsigned param_size() const
Selector getSelector() const
ParmVarDecl * getParamDecl(unsigned Idx)
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.
@ 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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4