41 #include "llvm/ADT/ArrayRef.h"
42 #include "llvm/ADT/BitVector.h"
43 #include "llvm/ADT/FoldingSet.h"
44 #include "llvm/ADT/ImmutableMap.h"
45 #include "llvm/ADT/MapVector.h"
46 #include "llvm/ADT/PostOrderIterator.h"
47 #include "llvm/ADT/SmallString.h"
48 #include "llvm/ADT/SmallVector.h"
49 #include "llvm/ADT/StringRef.h"
50 #include "llvm/Support/Casting.h"
56 using namespace clang;
66 UnreachableCodeHandler(
Sema &s) :
S(s) {}
73 unsigned diag = diag::warn_unreachable;
76 diag = diag::warn_unreachable_break;
79 diag = diag::warn_unreachable_return;
82 diag = diag::warn_unreachable_loop_increment;
88 S.
Diag(L, diag) << R1 << R2;
95 S.
Diag(Open, diag::note_unreachable_silence)
116 UnreachableCodeHandler UC(S);
128 static bool HasMacroID(
const Expr *E) {
133 for (
const Stmt *SubStmt : E->children())
134 if (
const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
135 if (HasMacroID(SubExpr))
141 void compareAlwaysTrue(
const BinaryOperator *B,
bool isAlwaysTrue)
override {
147 << DiagRange << isAlwaysTrue;
151 bool isAlwaysTrue)
override {
157 << DiagRange << isAlwaysTrue;
181 if (States[ID] >= State)
194 for (
const auto &B : Block) {
203 if (
const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
207 isa<TemplateSpecializationType>(NNS->getAsType())) {
214 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
215 !MCE->getMethodDecl()->isVirtual()) {
260 S.
Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
299 for (
const auto *B : *cfg) {
300 if (!live[B->getBlockID()]) {
301 if (B->pred_begin() == B->pred_end()) {
302 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
314 bool HasLiveReturn =
false;
315 bool HasFakeEdge =
false;
316 bool HasPlainEdge =
false;
317 bool HasAbnormalEdge =
false;
325 I = cfg->getExit().filtered_pred_start_end(FO); I.
hasMore(); ++I) {
334 HasAbnormalEdge =
true;
343 for ( ; ri != re ; ++ri)
350 HasAbnormalEdge =
true;
360 if (isa<ReturnStmt>(S)) {
361 HasLiveReturn =
true;
364 if (isa<ObjCAtThrowStmt>(S)) {
368 if (isa<CXXThrowExpr>(S)) {
372 if (isa<MSAsmStmt>(S)) {
375 HasLiveReturn =
true;
378 if (isa<CXXTryStmt>(S)) {
379 HasAbnormalEdge =
true;
384 HasAbnormalEdge =
true;
395 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
405 struct CheckFallThroughDiagnostics {
406 unsigned diag_MaybeFallThrough_HasNoReturn;
407 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
408 unsigned diag_AlwaysFallThrough_HasNoReturn;
409 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
410 unsigned diag_NeverFallThroughOrReturn;
411 enum { Function, Block, Lambda } funMode;
414 static CheckFallThroughDiagnostics MakeForFunction(
const Decl *Func) {
415 CheckFallThroughDiagnostics D;
417 D.diag_MaybeFallThrough_HasNoReturn =
418 diag::warn_falloff_noreturn_function;
419 D.diag_MaybeFallThrough_ReturnsNonVoid =
420 diag::warn_maybe_falloff_nonvoid_function;
421 D.diag_AlwaysFallThrough_HasNoReturn =
422 diag::warn_falloff_noreturn_function;
423 D.diag_AlwaysFallThrough_ReturnsNonVoid =
424 diag::warn_falloff_nonvoid_function;
428 bool isVirtualMethod =
false;
429 if (
const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
430 isVirtualMethod = Method->isVirtual();
434 if (
const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
435 isTemplateInstantiation = Function->isTemplateInstantiation();
437 if (!isVirtualMethod && !isTemplateInstantiation)
438 D.diag_NeverFallThroughOrReturn =
439 diag::warn_suggest_noreturn_function;
441 D.diag_NeverFallThroughOrReturn = 0;
443 D.funMode = Function;
447 static CheckFallThroughDiagnostics MakeForBlock() {
448 CheckFallThroughDiagnostics D;
449 D.diag_MaybeFallThrough_HasNoReturn =
450 diag::err_noreturn_block_has_return_expr;
451 D.diag_MaybeFallThrough_ReturnsNonVoid =
452 diag::err_maybe_falloff_nonvoid_block;
453 D.diag_AlwaysFallThrough_HasNoReturn =
454 diag::err_noreturn_block_has_return_expr;
455 D.diag_AlwaysFallThrough_ReturnsNonVoid =
456 diag::err_falloff_nonvoid_block;
457 D.diag_NeverFallThroughOrReturn = 0;
462 static CheckFallThroughDiagnostics MakeForLambda() {
463 CheckFallThroughDiagnostics D;
464 D.diag_MaybeFallThrough_HasNoReturn =
465 diag::err_noreturn_lambda_has_return_expr;
466 D.diag_MaybeFallThrough_ReturnsNonVoid =
467 diag::warn_maybe_falloff_nonvoid_lambda;
468 D.diag_AlwaysFallThrough_HasNoReturn =
469 diag::err_noreturn_lambda_has_return_expr;
470 D.diag_AlwaysFallThrough_ReturnsNonVoid =
471 diag::warn_falloff_nonvoid_lambda;
472 D.diag_NeverFallThroughOrReturn = 0;
478 bool HasNoReturn)
const {
479 if (funMode == Function) {
480 return (ReturnsVoid ||
481 D.
isIgnored(diag::warn_maybe_falloff_nonvoid_function,
484 D.
isIgnored(diag::warn_noreturn_function_has_return_expr,
487 D.
isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
491 return ReturnsVoid && !HasNoReturn;
503 const CheckFallThroughDiagnostics& CD,
506 bool ReturnsVoid =
false;
507 bool HasNoReturn =
false;
509 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
510 ReturnsVoid = FD->getReturnType()->isVoidType();
511 HasNoReturn = FD->isNoReturn();
513 else if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
514 ReturnsVoid = MD->getReturnType()->isVoidType();
515 HasNoReturn = MD->hasAttr<NoReturnAttr>();
517 else if (isa<BlockDecl>(D)) {
521 if (FT->getReturnType()->isVoidType())
523 if (FT->getNoReturnAttr())
531 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
534 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
542 S.
Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
543 else if (!ReturnsVoid)
544 S.
Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
548 S.
Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
549 else if (!ReturnsVoid)
550 S.
Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
553 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
554 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
555 S.
Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
556 }
else if (
const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
557 S.
Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
559 S.
Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
584 : Inherited(Context), FoundReference(
false), Needle(Needle) {}
586 void VisitExpr(
const Expr *E) {
591 Inherited::VisitExpr(E);
596 FoundReference =
true;
598 Inherited::VisitDeclRefExpr(E);
601 bool doesContainReference()
const {
return FoundReference; }
609 S.
Diag(VD->
getLocation(), diag::note_block_var_fixit_add_initialization)
630 S.
Diag(Loc, diag::note_var_fixit_add_initialization) << VD->
getDeclName()
638 const Stmt *Else,
bool CondVal,
644 Then->getLocStart()));
656 Else->getLocStart()));
665 bool IsCapturedByBlock) {
666 bool Diagnosed =
false;
670 S.
Diag(Use.
getUser()->getLocStart(), diag::warn_uninit_var)
672 << Use.
getUser()->getSourceRange();
682 S.
Diag(Use.
getUser()->getLocStart(), diag::note_uninit_var_use)
683 << IsCapturedByBlock << Use.
getUser()->getSourceRange();
699 const Stmt *Term = I->Terminator;
709 int RemoveDiagKind = -1;
710 const char *FixitStr =
711 S.
getLangOpts().CPlusPlus ? (I->Output ?
"true" :
"false")
712 : (I->Output ?
"1" :
"0");
715 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
722 case Stmt::IfStmtClass: {
723 const IfStmt *IS = cast<IfStmt>(Term);
726 Range = IS->
getCond()->getSourceRange();
729 I->Output, Fixit1, Fixit2);
732 case Stmt::ConditionalOperatorClass: {
736 Range = CO->
getCond()->getSourceRange();
739 I->Output, Fixit1, Fixit2);
742 case Stmt::BinaryOperatorClass: {
748 Range = BO->
getLHS()->getSourceRange();
762 case Stmt::WhileStmtClass:
765 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
769 case Stmt::ForStmtClass:
772 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
779 case Stmt::CXXForRangeStmtClass:
780 if (I->Output == 1) {
788 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
792 case Stmt::DoStmtClass:
795 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
801 case Stmt::CaseStmtClass:
804 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
806 case Stmt::DefaultStmtClass:
809 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
813 S.
Diag(Range.
getBegin(), diag::warn_sometimes_uninit_var)
814 << VD->
getDeclName() << IsCapturedByBlock << DiagKind
815 << Str << I->Output << Range;
816 S.
Diag(User->getLocStart(), diag::note_uninit_var_use)
817 << IsCapturedByBlock << User->getSourceRange();
818 if (RemoveDiagKind != -1)
820 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
826 S.
Diag(Use.
getUser()->getLocStart(), diag::warn_maybe_uninit_var)
828 << Use.
getUser()->getSourceRange();
838 bool alwaysReportSelfInit =
false) {
853 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
856 ContainsReference CR(S.
Context, DRE);
857 CR.Visit(Initializer);
858 if (CR.doesContainReference()) {
859 S.
Diag(DRE->getLocStart(),
860 diag::warn_uninit_self_reference_in_init)
871 diag::warn_uninit_byref_blockvar_captured_by_block)
890 FallthroughMapper(
Sema &
S)
891 : FoundSwitchStatements(
false),
895 bool foundSwitchStatements()
const {
return FoundSwitchStatements; }
898 bool Found = FallthroughStmts.erase(Stmt);
903 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
905 const AttrStmts &getFallthroughStmts()
const {
906 return FallthroughStmts;
909 void fillReachableBlocks(
CFG *Cfg) {
910 assert(ReachableBlocks.empty() &&
"ReachableBlocks already filled");
911 std::deque<const CFGBlock *> BlockQueue;
913 ReachableBlocks.insert(&Cfg->
getEntry());
914 BlockQueue.push_back(&Cfg->
getEntry());
919 for (
const auto *B : *Cfg) {
920 const Stmt *L = B->getLabel();
921 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
922 BlockQueue.push_back(B);
925 while (!BlockQueue.empty()) {
927 BlockQueue.pop_front();
931 if (*I && ReachableBlocks.insert(*I).second)
932 BlockQueue.push_back(*I);
937 bool checkFallThroughIntoBlock(
const CFGBlock &B,
int &AnnotatedCnt) {
938 assert(!ReachableBlocks.empty() &&
"ReachableBlocks empty");
940 int UnannotatedCnt = 0;
944 while (!BlockQueue.empty()) {
946 BlockQueue.pop_front();
950 if (Term && isa<SwitchStmt>(Term))
961 if (!ReachableBlocks.count(P)) {
964 ElemIt != ElemEnd; ++ElemIt) {
966 if (
const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
967 S.
Diag(AS->getLocStart(),
968 diag::warn_fallthrough_attr_unreachable);
969 markFallthroughVisited(AS);
989 markFallthroughVisited(AS);
997 std::back_inserter(BlockQueue));
1003 return !!UnannotatedCnt;
1007 bool shouldWalkTypesOfTypeLocs()
const {
return false; }
1010 if (asFallThroughAttr(S))
1011 FallthroughStmts.insert(S);
1016 FoundSwitchStatements =
true;
1022 bool TraverseDecl(
Decl *D) {
return true; }
1025 bool TraverseLambdaBody(
LambdaExpr *LE) {
return true; }
1030 if (
const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1031 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1042 ElemIt != ElemEnd; ++ElemIt) {
1044 return CS->getStmt();
1056 bool FoundSwitchStatements;
1057 AttrStmts FallthroughStmts;
1059 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
1077 FallthroughMapper FM(S);
1078 FM.TraverseStmt(AC.
getBody());
1080 if (!FM.foundSwitchStatements())
1083 if (PerFunction && FM.getFallthroughStmts().empty())
1091 FM.fillReachableBlocks(Cfg);
1097 if (!Label || !isa<SwitchCase>(Label))
1102 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
1105 S.
Diag(Label->getLocStart(),
1106 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1107 : diag::warn_unannotated_fallthrough);
1109 if (!AnnotatedCnt) {
1120 if (!(B->
empty() && Term && isa<BreakStmt>(Term))) {
1125 tok::r_square, tok::r_square
1127 StringRef AnnotationSpelling =
"[[clang::fallthrough]]";
1129 if (!MacroName.empty())
1130 AnnotationSpelling = MacroName;
1132 TextToInsert +=
"; ";
1133 S.
Diag(L, diag::note_insert_fallthrough_fixit) <<
1134 AnnotationSpelling <<
1138 S.
Diag(L, diag::note_insert_break_fixit) <<
1143 for (
const auto *F : FM.getFallthroughStmts())
1144 S.
Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1152 switch (S->getStmtClass()) {
1153 case Stmt::ForStmtClass:
1154 case Stmt::WhileStmtClass:
1155 case Stmt::CXXForRangeStmtClass:
1156 case Stmt::ObjCForCollectionStmtClass:
1158 case Stmt::DoStmtClass: {
1159 const Expr *Cond = cast<DoStmt>(
S)->getCond();
1163 return Val.getBoolValue();
1181 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1190 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1192 const WeakUseVector &Uses = I->second;
1195 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1196 for ( ; UI != UE; ++UI) {
1209 if (UI == Uses.begin()) {
1210 WeakUseVector::const_iterator UI2 = UI;
1211 for (++UI2; UI2 != UE; ++UI2)
1212 if (UI2->isUnsafe())
1216 if (!
isInLoop(Ctx, PM, UI->getUseExpr()))
1219 const WeakObjectProfileTy &Profile = I->first;
1220 if (!Profile.isExactProfile())
1225 Base = Profile.getProperty();
1226 assert(Base &&
"A profile always has a base or property.");
1228 if (
const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1229 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1234 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1237 if (UsesByStmt.empty())
1242 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
1243 [&
SM](
const StmtUsesPair &LHS,
const StmtUsesPair &RHS) {
1245 RHS.first->getLocStart());
1260 if (isa<sema::BlockScopeInfo>(CurFn))
1261 FunctionKind = Block;
1262 else if (isa<sema::LambdaScopeInfo>(CurFn))
1263 FunctionKind = Lambda;
1264 else if (isa<ObjCMethodDecl>(D))
1265 FunctionKind = Method;
1267 FunctionKind = Function;
1270 for (
const auto &P : UsesByStmt) {
1271 const Stmt *FirstRead = P.first;
1272 const WeakObjectProfileTy &Key = P.second->first;
1273 const WeakUseVector &Uses = P.second->second;
1281 if (Key.isExactProfile())
1282 DiagKind = diag::warn_arc_repeated_use_of_weak;
1284 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1297 if (isa<VarDecl>(D))
1298 ObjectKind = Variable;
1299 else if (isa<ObjCPropertyDecl>(D))
1301 else if (isa<ObjCMethodDecl>(D))
1302 ObjectKind = ImplicitProperty;
1303 else if (isa<ObjCIvarDecl>(D))
1306 llvm_unreachable(
"Unexpected weak object kind!");
1309 S.
Diag(FirstRead->getLocStart(), DiagKind)
1310 <<
int(ObjectKind) << D << int(FunctionKind)
1311 << FirstRead->getSourceRange();
1314 for (
const auto &Use : Uses) {
1315 if (Use.getUseExpr() == FirstRead)
1317 S.
Diag(Use.getUseExpr()->getLocStart(),
1318 diag::note_arc_weak_also_accessed_here)
1319 << Use.getUseExpr()->getSourceRange();
1328 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
1332 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
1336 UninitValsDiagReporter(
Sema &S) : S(S), uses(nullptr) {}
1339 MappedType &getUses(
const VarDecl *vd) {
1341 uses =
new UsesMap();
1343 MappedType &V = (*uses)[vd];
1344 if (!V.getPointer())
1345 V.setPointer(
new UsesVec());
1350 void handleUseOfUninitVariable(
const VarDecl *vd,
1352 getUses(vd).getPointer()->push_back(use);
1355 void handleSelfInit(
const VarDecl *vd)
override {
1356 getUses(vd).setInt(
true);
1363 for (
const auto &P : *uses) {
1365 const MappedType &V = P.second;
1367 UsesVec *vec = V.getPointer();
1368 bool hasSelfInit = V.getInt();
1373 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
1382 std::sort(vec->begin(), vec->end(),
1385 if (a.
getKind() != b.getKind())
1386 return a.
getKind() > b.getKind();
1387 return a.
getUser()->getLocStart() < b.getUser()->getLocStart();
1390 for (
const auto &U : *vec) {
1408 static bool hasAlwaysUninitializedUse(
const UsesVec* vec) {
1409 return std::any_of(vec->begin(), vec->end(), [](
const UninitUse &U) {
1421 typedef std::pair<PartialDiagnosticAt, OptionalNotes>
DelayedDiag;
1422 typedef std::list<DelayedDiag>
DiagList;
1424 struct SortDiagBySourceLocation {
1428 bool operator()(
const DelayedDiag &left,
const DelayedDiag &right) {
1440 namespace threadSafety {
1453 S.PDiag(diag::note_thread_warning_in_fun)
1464 S.PDiag(diag::note_thread_warning_in_fun)
1466 ONS.push_back(std::move(FNote));
1474 ONS.push_back(Note1);
1475 ONS.push_back(Note2);
1478 S.PDiag(diag::note_thread_warning_in_fun)
1480 ONS.push_back(std::move(FNote));
1486 void warnLockMismatch(
unsigned DiagID, StringRef
Kind, Name LockName,
1493 Warnings.emplace_back(std::move(Warning), getNotes());
1501 void setVerbose(
bool b) {
Verbose = b; }
1507 void emitDiagnostics() {
1508 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1510 S.Diag(
Diag.first.first,
Diag.first.second);
1511 for (
const auto &Note :
Diag.second)
1512 S.Diag(Note.first, Note.second);
1516 void handleInvalidLockExp(StringRef Kind,
SourceLocation Loc)
override {
1519 Warnings.emplace_back(std::move(Warning), getNotes());
1522 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1524 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
1527 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1533 << Kind << LockName << Received
1535 Warnings.emplace_back(std::move(Warning), getNotes());
1538 void handleDoubleLock(StringRef Kind, Name LockName,
SourceLocation Loc)
override {
1539 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
1542 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1546 unsigned DiagID = 0;
1549 DiagID = diag::warn_lock_some_predecessors;
1552 DiagID = diag::warn_expecting_lock_held_on_loop;
1555 DiagID = diag::warn_no_unlock;
1558 DiagID = diag::warn_expecting_locked;
1569 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1572 Warnings.emplace_back(std::move(Warning), getNotes());
1575 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1579 S.PDiag(diag::warn_lock_exclusive_and_shared)
1580 << Kind << LockName);
1582 << Kind << LockName);
1583 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1586 void handleNoMutexHeld(StringRef Kind,
const NamedDecl *D,
1590 "Only works for variables");
1592 diag::warn_variable_requires_any_lock:
1593 diag::warn_var_deref_requires_any_lock;
1596 Warnings.emplace_back(std::move(Warning), getNotes());
1599 void handleMutexNotHeld(StringRef Kind,
const NamedDecl *D,
1602 Name *PossibleMatch)
override {
1603 unsigned DiagID = 0;
1604 if (PossibleMatch) {
1607 DiagID = diag::warn_variable_requires_lock_precise;
1610 DiagID = diag::warn_var_deref_requires_lock_precise;
1613 DiagID = diag::warn_fun_requires_lock_precise;
1616 DiagID = diag::warn_guarded_pass_by_reference;
1619 DiagID = diag::warn_pt_guarded_pass_by_reference;
1629 S.PDiag(diag::note_guarded_by_declared_here)
1631 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
1633 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1637 DiagID = diag::warn_variable_requires_lock;
1640 DiagID = diag::warn_var_deref_requires_lock;
1643 DiagID = diag::warn_fun_requires_lock;
1646 DiagID = diag::warn_guarded_pass_by_reference;
1649 DiagID = diag::warn_pt_guarded_pass_by_reference;
1657 S.PDiag(diag::note_guarded_by_declared_here)
1659 Warnings.emplace_back(std::move(Warning), getNotes(Note));
1661 Warnings.emplace_back(std::move(Warning), getNotes());
1665 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1668 S.PDiag(diag::warn_acquire_requires_negative_cap)
1669 << Kind << LockName << Neg);
1670 Warnings.emplace_back(std::move(Warning), getNotes());
1674 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
1677 << Kind << FunName << LockName);
1678 Warnings.emplace_back(std::move(Warning), getNotes());
1681 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1684 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
1685 Warnings.emplace_back(std::move(Warning), getNotes());
1688 void handleBeforeAfterCycle(Name L1Name,
SourceLocation Loc)
override {
1690 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
1691 Warnings.emplace_back(std::move(Warning), getNotes());
1711 namespace consumed {
1713 class ConsumedWarningsHandler :
public ConsumedWarningsHandlerBase {
1720 ConsumedWarningsHandler(
Sema &S) : S(S) {}
1722 void emitDiagnostics()
override {
1723 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1724 for (
const auto &
Diag : Warnings) {
1725 S.Diag(
Diag.first.first,
Diag.first.second);
1726 for (
const auto &Note :
Diag.second)
1727 S.Diag(Note.first, Note.second);
1732 StringRef VariableName)
override {
1740 StringRef VariableName,
1741 StringRef ExpectedState,
1742 StringRef ObservedState)
override {
1745 diag::warn_param_return_typestate_mismatch) << VariableName <<
1746 ExpectedState << ObservedState);
1751 void warnParamTypestateMismatch(
SourceLocation Loc, StringRef ExpectedState,
1752 StringRef ObservedState)
override {
1755 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1761 StringRef TypeName)
override {
1763 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1768 void warnReturnTypestateMismatch(
SourceLocation Loc, StringRef ExpectedState,
1769 StringRef ObservedState)
override {
1772 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1777 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef
State,
1781 diag::warn_use_of_temp_in_invalid_state) << MethodName <<
State);
1786 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
1790 MethodName << VariableName <<
State);
1803 enableCheckFallThrough = 1;
1804 enableCheckUnreachable = 0;
1805 enableThreadSafetyAnalysis = 0;
1806 enableConsumedAnalysis = 0;
1815 NumFunctionsAnalyzed(0),
1816 NumFunctionsWithBadCFGs(0),
1818 MaxCFGBlocksPerFunction(0),
1819 NumUninitAnalysisFunctions(0),
1820 NumUninitAnalysisVariables(0),
1821 MaxUninitAnalysisVariablesPerFunction(0),
1822 NumUninitAnalysisBlockVisits(0),
1823 MaxUninitAnalysisBlockVisitsPerFunction(0) {
1825 using namespace diag;
1828 DefaultPolicy.enableCheckUnreachable =
1831 isEnabled(D, warn_unreachable_return) ||
1832 isEnabled(D, warn_unreachable_loop_increment);
1834 DefaultPolicy.enableThreadSafetyAnalysis =
1837 DefaultPolicy.enableConsumedAnalysis =
1838 isEnabled(D, warn_use_in_invalid_state);
1843 S.
Diag(D.Loc, D.PD);
1866 if (cast<DeclContext>(D)->isDependentContext())
1875 const Stmt *Body = D->
getBody();
1897 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1898 P.enableConsumedAnalysis) {
1915 std::unique_ptr<LogicalErrorHandler> LEH;
1916 if (!Diags.
isIgnored(diag::warn_tautological_overlap_comparison,
1918 LEH.reset(
new LogicalErrorHandler(S));
1924 bool analyzed =
false;
1935 bool processed =
false;
1946 S.Diag(D.Loc, D.PD);
1952 S.Diag(D.Loc, D.PD);
1963 if (P.enableCheckFallThrough) {
1964 const CheckFallThroughDiagnostics &CD =
1965 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
1966 : (isa<CXXMethodDecl>(D) &&
1967 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1968 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1969 ? CheckFallThroughDiagnostics::MakeForLambda()
1970 : CheckFallThroughDiagnostics::MakeForFunction(D));
1975 if (P.enableCheckUnreachable) {
1980 bool isTemplateInstantiation =
false;
1981 if (
const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1982 isTemplateInstantiation = Function->isTemplateInstantiation();
1983 if (!isTemplateInstantiation)
1988 if (P.enableThreadSafetyAnalysis) {
1991 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
1993 Reporter.setIssueBetaWarnings(
true);
1995 Reporter.setVerbose(
true);
1998 &S.ThreadSafetyDeclCache);
1999 Reporter.emitDiagnostics();
2003 if (P.enableConsumedAnalysis) {
2004 consumed::ConsumedWarningsHandler WarningHandler(S);
2013 UninitValsDiagReporter reporter(S);
2020 ++NumUninitAnalysisFunctions;
2023 MaxUninitAnalysisVariablesPerFunction =
2024 std::max(MaxUninitAnalysisVariablesPerFunction,
2026 MaxUninitAnalysisBlockVisitsPerFunction =
2027 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2033 bool FallThroughDiagFull =
2035 bool FallThroughDiagPerFunction = !Diags.
isIgnored(
2036 diag::warn_unannotated_fallthrough_per_function, D->
getLocStart());
2037 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
2041 if (S.getLangOpts().ObjCARCWeak &&
2047 if (!Diags.
isIgnored(diag::warn_infinite_recursive_function,
2049 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2056 if (!Diags.
isIgnored(diag::warn_tautological_overlap_comparison,
2063 ++NumFunctionsAnalyzed;
2067 NumCFGBlocks += cfg->getNumBlockIDs();
2068 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
2069 cfg->getNumBlockIDs());
2071 ++NumFunctionsWithBadCFGs;
2077 llvm::errs() <<
"\n*** Analysis Based Warnings Stats:\n";
2079 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2080 unsigned AvgCFGBlocksPerFunction =
2081 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2082 llvm::errs() << NumFunctionsAnalyzed <<
" functions analyzed ("
2083 << NumFunctionsWithBadCFGs <<
" w/o CFGs).\n"
2084 <<
" " << NumCFGBlocks <<
" CFG blocks built.\n"
2085 <<
" " << AvgCFGBlocksPerFunction
2086 <<
" average CFG blocks per function.\n"
2087 <<
" " << MaxCFGBlocksPerFunction
2088 <<
" max CFG blocks per function.\n";
2090 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2091 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2092 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2093 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2094 llvm::errs() << NumUninitAnalysisFunctions
2095 <<
" functions analyzed for uninitialiazed variables\n"
2096 <<
" " << NumUninitAnalysisVariables <<
" variables analyzed.\n"
2097 <<
" " << AvgUninitVariablesPerFunction
2098 <<
" average variables per function.\n"
2099 <<
" " << MaxUninitAnalysisVariablesPerFunction
2100 <<
" max variables per function.\n"
2101 <<
" " << NumUninitAnalysisBlockVisits <<
" block visits.\n"
2102 <<
" " << AvgUninitBlockVisitsPerFunction
2103 <<
" average block visits per function.\n"
2104 <<
" " << MaxUninitAnalysisBlockVisitsPerFunction
2105 <<
" max block visits per function.\n";
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens. If there are multiple macro...
static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use, bool IsCapturedByBlock)
SourceLocation getEnd() const
Passing a guarded variable by reference.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
ASTContext & getASTContext() const
SourceLocation getBegin() const
succ_iterator succ_begin()
const LangOptions & getLangOpts() const
Defines the SourceManager interface.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
static void diagnoseRepeatedUseOfWeak(Sema &S, const sema::FunctionScopeInfo *CurFn, const Decl *D, const ParentMap &PM)
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Represents an attribute applied to a statement.
The use is uninitialized whenever a certain branch is taken.
const Expr * getInit() const
AnalysisBasedWarnings(Sema &s)
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
void run(AnalysisDeclContext &AC)
Check a function's CFG for consumed violations.
const Stmt * getElse() const
SourceLocation getOperatorLoc() const
bool isBlockPointerType() const
LockKind getLockKindFromAccessKind(AccessKind AK)
Helper function that returns a LockKind required for the given level of access.
SourceLocation getLocEnd() const LLVM_READONLY
unsigned IgnoreDefaultsWithCoveredEnums
static std::pair< const Stmt *, const CFGBlock * > getLastStmt(const ExplodedNode *Node)
branch_iterator branch_begin() const
Branches which inevitably result in the variable being used uninitialized.
Retains information about a function, method, or block that is currently being parsed.
const Expr * getCallee() const
unsigned succ_size() const
The use might be uninitialized.
Defines the Objective-C statement AST node classes.
AdjacentBlocks::iterator succ_iterator
Defines the clang::Expr interface and subclasses for C++ expressions.
SourceLocation getLocStart() const LLVM_READONLY
TextDiagnosticBuffer::DiagList DiagList
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
std::pair< PartialDiagnosticAt, OptionalNotes > DelayedDiag
static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC, bool PerFunction)
T castAs() const
Convert to the specified CFGElement type, asserting that this CFGElement is of the desired type...
bool getAddEHEdges() const
SmallVectorImpl< Branch >::const_iterator branch_iterator
const LangOptions & getLangOpts() const
bool AddCXXDefaultInitExprInCtors
CFGReverseBlockReachabilityAnalysis * getCFGReachablityAnalysis()
Concrete class used by the front-end to report problems and issues.
A builtin binary operation expression such as "x + y" or "x <= y".
void IssueWarnings(Policy P, FunctionScopeInfo *fscope, const Decl *D, const BlockExpr *blkExpr)
std::string getNameAsString() const
Expr * IgnoreParenCasts() LLVM_READONLY
static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC)
CheckUnreachable - Check for unreachable code.
DeclContext * getLexicalDeclContext()
const Decl * getDecl() const
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
A class that does preorder depth-first traversal on the entire Clang AST and visits each node...
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD)
const Expr * getUser() const
Get the expression containing the uninitialized use.
Passing a pt-guarded variable by reference.
Sema - This implements semantic analysis and AST building for C.
Expr * getFalseExpr() const
static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD, const UninitUse &Use, bool alwaysReportSelfInit=false)
Handler class for thread safety warnings.
static StringRef getOpcodeStr(Opcode Op)
static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM, const Stmt *S)
Stmt * getBody() const
Get the body of the Declaration.
ID
Defines the set of possible language-specific address spaces.
QualType getPointeeType() const
Dereferencing a variable (e.g. p in *p = 5;)
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
bool hasFatalErrorOccurred() const
bool isBeforeInTranslationUnit(SourceLocation LHS, SourceLocation RHS) const
Determines the order of 2 source locations in the translation unit.
Defines the clang::Preprocessor interface.
Stores token information for comparing actual tokens with predefined values. Only handles simple toke...
void runUninitializedVariablesAnalysis(const DeclContext &dc, const CFG &cfg, AnalysisDeclContext &ac, UninitVariablesHandler &handler, UninitVariablesAnalysisStats &stats)
void FindUnreachableCode(AnalysisDeclContext &AC, Preprocessor &PP, Callback &CB)
unsigned ScanReachableFromBlock(const CFGBlock *Start, llvm::BitVector &Reachable)
const CFGBlock * getBlockForRegisteredExpression(const Stmt *stmt)
bool EvaluateAsInt(llvm::APSInt &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects) const
unsigned getBlockID() const
Making a function call (e.g. fool())
DeclarationName getDeclName() const
DiagnosticsEngine & getDiagnostics() const
A use of a variable, which might be uninitialized.
A type, stored as a Type*.
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Expr * getTrueExpr() const
reverse_iterator rbegin()
static CharSourceRange getCharRange(SourceRange R)
bool getSuppressSystemWarnings() const
CharSourceRange RemoveRange
Code that should be replaced to correct the error. Empty for an insertion hint.
Stmt * getBody(const FunctionDecl *&Definition) const
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
SourceLocation getLocStart() const LLVM_READONLY
bool hasNoReturnElement() const
CFGTerminator getTerminator()
Reading or writing a variable (e.g. x in x = 5;)
Stmt * getParent(Stmt *) const
Encodes a location in the source. The SourceManager can decode this to get at the full include stack...
BuildOptions & setAlwaysAdd(Stmt::StmtClass stmtClass, bool val=true)
reverse_iterator rbegin()
bool isValid() const
Return true if this is a valid SourceLocation object.
bool isReachable(const CFGBlock *Src, const CFGBlock *Dst)
Returns true if the block 'Dst' can be reached from block 'Src'.
SourceLocation getLocStart() const LLVM_READONLY
ASTContext & getASTContext() const
bool PruneTriviallyFalseEdges
Represents a static or instance method of a struct/union/class.
bool isCFGBuilt() const
Returns true if we have built a CFG for this analysis context. Note that this doesn't correspond to w...
const Stmt * getStmt() const
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
virtual Stmt * getBody() const
SourceLocation FunLocation
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs. ...
SourceLocation getBegin() const
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
static bool isLogicalOp(Opcode Opc)
BuildOptions & setAllAlwaysAdd()
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
AdjacentBlocks::const_iterator const_succ_iterator
static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag)
SourceLocation getExprLoc() const LLVM_READONLY
static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body, const BlockExpr *blkExpr, const CheckFallThroughDiagnostics &CD, AnalysisDeclContext &AC)
pred_iterator pred_begin()
CFG::BuildOptions & getCFGBuildOptions()
Return the build options used to construct the CFG.
SourceLocation FunEndLocation
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
void runThreadSafetyAnalysis(AnalysisDeclContext &AC, ThreadSafetyHandler &Handler, BeforeSet **Bset)
Check a function's CFG for thread-safety violations.
static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then, const Stmt *Else, bool CondVal, FixItHint &Fixit1, FixItHint &Fixit2)
llvm::SmallDenseMap< WeakObjectProfileTy, WeakUseVector, 8, WeakObjectProfileTy::DenseMapInfo > WeakObjectUseMap
std::string getFixItZeroInitializerForType(QualType T, SourceLocation Loc) const
Get a string to suggest for zero-initialization of a type.
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
SmallVector< PartialDiagnosticAt, 1 > OptionalNotes
const WeakObjectUseMap & getWeakObjectUses() const
SourceLocation getLocStart() const LLVM_READONLY
A class that handles the analysis of uniqueness violations.
ConstEvaluatedExprVisitor - This class visits 'const Expr *'s.
Expr * IgnoreParenImpCasts() LLVM_READONLY
const Stmt * getThen() const
Kind getKind() const
Get the kind of uninitialized use.
UnreachableKind
Classifications of unreachable code.
SourceManager & getSourceManager() const
QualType getCanonicalType() const
The use is always uninitialized.
static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD, const Stmt *Body, AnalysisDeclContext &AC)
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
SourceLocation getExprLoc() const LLVM_READONLY
static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope)
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate.h) and friends (in DeclFriend.h).
Defines the clang::SourceLocation class and associated facilities.
SmallVector< PossiblyUnreachableDiag, 4 > PossiblyUnreachableDiags
A list of PartialDiagnostics created but delayed within the current function scope. These diagnostics are vetted for reachability prior to being emitted.
CFGCallback defines methods that should be called when a logical operator error is found when buildin...
const Expr * getCond() const
CFGElement - Represents a top-level expression in a basic block.
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC)
void registerForcedBlockExpression(const Stmt *stmt)
A reference to a declared variable, function, enum, etc. [C99 6.5.1p2].
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
const FunctionDecl * CurrentFunction
unsigned NumVariablesAnalyzed
ParentMap & getParentMap()
A trivial tuple used to represent a source range.
SourceLocation getLocation() const
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
static void checkForFunctionCall(Sema &S, const FunctionDecl *FD, CFGBlock &Block, unsigned ExitID, llvm::SmallVectorImpl< RecursiveState > &States, RecursiveState State)
bool hasUncompilableErrorOccurred() const
Errors that actually prevent compilation, not those that are upgraded from a warning by -Werror...
unsigned getNumBlockIDs() const
std::reverse_iterator< iterator > reverse_iterator
branch_iterator branch_end() const
This class handles loading and caching of source files into memory.
Preprocessor & getPreprocessor() const
Optional< T > getAs() const
Convert to the specified CFGElement type, returning None if this CFGElement is not of the desired typ...
Engages in a tight little dance with the lexer to efficiently preprocess tokens.