blob: 0b48838474aed83a687d544592af46a0909246cb [file] [log] [blame]
Ted Kremenek918fe842010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Rose76831c62012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smith84837d52012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
DeLesley Hutchins48a31762013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/ReachableCode.h"
30#include "clang/Analysis/Analyses/ThreadSafety.h"
31#include "clang/Analysis/Analyses/UninitializedValues.h"
George Karpenkov50657f62017-09-06 21:45:03 +000032#include "clang/Analysis/AnalysisDeclContext.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000033#include "clang/Analysis/CFG.h"
Ted Kremenek3427fac2011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Lex/Preprocessor.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000040#include "llvm/ADT/BitVector.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000041#include "llvm/ADT/MapVector.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000042#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000044#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000045#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000047#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000048#include <iterator>
Ted Kremenek918fe842010-03-20 21:06:02 +000049
50using namespace clang;
51
52//===----------------------------------------------------------------------===//
53// Unreachable code analysis.
54//===----------------------------------------------------------------------===//
55
56namespace {
57 class UnreachableCodeHandler : public reachable_code::Callback {
58 Sema &S;
Alex Lorenz569ad732017-01-12 10:48:03 +000059 SourceRange PreviousSilenceableCondVal;
60
Ted Kremenek918fe842010-03-20 21:06:02 +000061 public:
62 UnreachableCodeHandler(Sema &s) : S(s) {}
63
Ted Kremenek1a8641c2014-03-15 01:26:32 +000064 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000065 SourceLocation L,
66 SourceRange SilenceableCondVal,
67 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000068 SourceRange R2) override {
Alex Lorenz569ad732017-01-12 10:48:03 +000069 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
74 return;
75 PreviousSilenceableCondVal = SilenceableCondVal;
76
Ted Kremenek1a8641c2014-03-15 01:26:32 +000077 unsigned diag = diag::warn_unreachable;
78 switch (UK) {
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
81 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000082 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000083 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 break;
Ted Kremenek14210372014-03-21 06:02:36 +000085 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
87 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000088 case reachable_code::UK_Other:
89 break;
90 }
91
92 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000093
94 SourceLocation Open = SilenceableCondVal.getBegin();
95 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000096 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000098 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
102 }
103 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000104 }
105 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000106} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +0000107
108/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000109static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
114 //
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
118 return;
119
Ted Kremenek918fe842010-03-20 21:06:02 +0000120 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000122}
123
Benjamin Kramer3a002252015-02-16 16:53:12 +0000124namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000125/// \brief Warn on logical operator errors in CFGBuilder
126class LogicalErrorHandler : public CFGCallback {
127 Sema &S;
128
129public:
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
131
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
134 return true;
135
136 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000137 for (const Stmt *SubStmt : E->children())
138 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
139 if (HasMacroID(SubExpr))
140 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000141
142 return false;
143 }
144
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000146 if (HasMacroID(B))
147 return;
148
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
152 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000153
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000156 if (HasMacroID(B))
157 return;
158
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
162 }
Richard Trieuf935b562014-04-05 05:17:01 +0000163};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000164} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000165
Ted Kremenek918fe842010-03-20 21:06:02 +0000166//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000167// Check for infinite self-recursion in functions
168//===----------------------------------------------------------------------===//
169
Richard Trieu6995de92015-08-21 03:43:09 +0000170// Returns true if the function is called anywhere within the CFGBlock.
171// For member functions, the additional condition of being call from the
172// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000173static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000174 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000175 for (const auto &B : Block) {
176 if (B.getKind() != CFGElement::Statement)
177 continue;
178
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
182 continue;
183
184 // Skip function calls which are qualified with a templated class.
185 if (const DeclRefExpr *DRE =
186 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
187 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
188 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
189 isa<TemplateSpecializationType>(NNS->getAsType())) {
190 continue;
191 }
192 }
193 }
194
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
198 return true;
199 }
200 return false;
201}
202
Richard Trieu6995de92015-08-21 03:43:09 +0000203// All blocks are in one of three states. States are ordered so that blocks
204// can only move to higher states.
205enum RecursiveState {
206 FoundNoPath,
207 FoundPath,
208 FoundPathWithNoRecursiveCall
209};
210
211// Returns true if there exists a path to the exit block and every path
212// to the exit block passes through a call to FD.
213static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
214
215 const unsigned ExitID = cfg->getExit().getBlockID();
216
217 // Mark all nodes as FoundNoPath, then set the status of the entry block.
218 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
219 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
220
221 // Make the processing stack and seed it with the entry block.
222 SmallVector<CFGBlock *, 16> Stack;
223 Stack.push_back(&cfg->getEntry());
Richard Trieu2f024f42013-12-21 02:33:43 +0000224
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000225 while (!Stack.empty()) {
Richard Trieu6995de92015-08-21 03:43:09 +0000226 CFGBlock *CurBlock = Stack.back();
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000227 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000228
Richard Trieu6995de92015-08-21 03:43:09 +0000229 unsigned ID = CurBlock->getBlockID();
230 RecursiveState CurState = States[ID];
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000231
232 if (CurState == FoundPathWithNoRecursiveCall) {
233 // Found a path to the exit node without a recursive call.
234 if (ExitID == ID)
Richard Trieu6995de92015-08-21 03:43:09 +0000235 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000236
Richard Trieu6995de92015-08-21 03:43:09 +0000237 // Only change state if the block has a recursive call.
238 if (hasRecursiveCallInPath(FD, *CurBlock))
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000239 CurState = FoundPath;
240 }
241
Richard Trieu6995de92015-08-21 03:43:09 +0000242 // Loop over successor blocks and add them to the Stack if their state
243 // changes.
244 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
245 if (*I) {
246 unsigned next_ID = (*I)->getBlockID();
247 if (States[next_ID] < CurState) {
248 States[next_ID] = CurState;
249 Stack.push_back(*I);
250 }
251 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000252 }
Richard Trieu6995de92015-08-21 03:43:09 +0000253
254 // Return true if the exit node is reachable, and only reachable through
255 // a recursive call.
256 return States[ExitID] == FoundPath;
Richard Trieu2f024f42013-12-21 02:33:43 +0000257}
258
259static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000260 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000261 FD = FD->getCanonicalDecl();
262
263 // Only run on non-templated functions and non-templated members of
264 // templated classes.
265 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
266 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
267 return;
268
269 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000270 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000271
272 // If the exit block is unreachable, skip processing the function.
273 if (cfg->getExit().pred_empty())
274 return;
275
Richard Trieu6995de92015-08-21 03:43:09 +0000276 // Emit diagnostic if a recursive function call is detected for all paths.
277 if (checkForRecursiveFunctionCall(FD, cfg))
Richard Trieu2f024f42013-12-21 02:33:43 +0000278 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
279}
280
281//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000282// Check for throw in a non-throwing function.
283//===----------------------------------------------------------------------===//
284enum ThrowState {
285 FoundNoPathForThrow,
286 FoundPathForThrow,
287 FoundPathWithNoThrowOutFunction,
288};
289
290static bool isThrowCaught(const CXXThrowExpr *Throw,
291 const CXXCatchStmt *Catch) {
292 const Type *ThrowType = nullptr;
293 if (Throw->getSubExpr())
294 ThrowType = Throw->getSubExpr()->getType().getTypePtrOrNull();
295 if (!ThrowType)
296 return false;
297 const Type *CaughtType = Catch->getCaughtType().getTypePtrOrNull();
298 if (!CaughtType)
299 return true;
300 if (ThrowType->isReferenceType())
301 ThrowType = ThrowType->castAs<ReferenceType>()
302 ->getPointeeType()
303 ->getUnqualifiedDesugaredType();
304 if (CaughtType->isReferenceType())
305 CaughtType = CaughtType->castAs<ReferenceType>()
306 ->getPointeeType()
307 ->getUnqualifiedDesugaredType();
Stephan Bergmann743de462017-06-29 17:58:59 +0000308 if (ThrowType->isPointerType() && CaughtType->isPointerType()) {
309 ThrowType = ThrowType->getPointeeType()->getUnqualifiedDesugaredType();
310 CaughtType = CaughtType->getPointeeType()->getUnqualifiedDesugaredType();
311 }
Erich Keane89fe9c22017-06-23 20:22:19 +0000312 if (CaughtType == ThrowType)
313 return true;
314 const CXXRecordDecl *CaughtAsRecordType =
Stephan Bergmann743de462017-06-29 17:58:59 +0000315 CaughtType->getAsCXXRecordDecl();
Erich Keane89fe9c22017-06-23 20:22:19 +0000316 const CXXRecordDecl *ThrowTypeAsRecordType = ThrowType->getAsCXXRecordDecl();
317 if (CaughtAsRecordType && ThrowTypeAsRecordType)
318 return ThrowTypeAsRecordType->isDerivedFrom(CaughtAsRecordType);
319 return false;
320}
321
322static bool isThrowCaughtByHandlers(const CXXThrowExpr *CE,
323 const CXXTryStmt *TryStmt) {
324 for (unsigned H = 0, E = TryStmt->getNumHandlers(); H < E; ++H) {
325 if (isThrowCaught(CE, TryStmt->getHandler(H)))
326 return true;
327 }
328 return false;
329}
330
331static bool doesThrowEscapePath(CFGBlock Block, SourceLocation &OpLoc) {
332 for (const auto &B : Block) {
333 if (B.getKind() != CFGElement::Statement)
334 continue;
335 const auto *CE = dyn_cast<CXXThrowExpr>(B.getAs<CFGStmt>()->getStmt());
336 if (!CE)
337 continue;
338
339 OpLoc = CE->getThrowLoc();
340 for (const auto &I : Block.succs()) {
341 if (!I.isReachable())
342 continue;
343 if (const auto *Terminator =
344 dyn_cast_or_null<CXXTryStmt>(I->getTerminator()))
345 if (isThrowCaughtByHandlers(CE, Terminator))
346 return false;
347 }
348 return true;
349 }
350 return false;
351}
352
353static bool hasThrowOutNonThrowingFunc(SourceLocation &OpLoc, CFG *BodyCFG) {
354
355 unsigned ExitID = BodyCFG->getExit().getBlockID();
356
357 SmallVector<ThrowState, 16> States(BodyCFG->getNumBlockIDs(),
358 FoundNoPathForThrow);
359 States[BodyCFG->getEntry().getBlockID()] = FoundPathWithNoThrowOutFunction;
360
361 SmallVector<CFGBlock *, 16> Stack;
362 Stack.push_back(&BodyCFG->getEntry());
363 while (!Stack.empty()) {
364 CFGBlock *CurBlock = Stack.back();
365 Stack.pop_back();
366
367 unsigned ID = CurBlock->getBlockID();
368 ThrowState CurState = States[ID];
369 if (CurState == FoundPathWithNoThrowOutFunction) {
370 if (ExitID == ID)
371 continue;
372
373 if (doesThrowEscapePath(*CurBlock, OpLoc))
374 CurState = FoundPathForThrow;
375 }
376
377 // Loop over successor blocks and add them to the Stack if their state
378 // changes.
379 for (const auto &I : CurBlock->succs())
380 if (I.isReachable()) {
381 unsigned NextID = I->getBlockID();
382 if (NextID == ExitID && CurState == FoundPathForThrow) {
383 States[NextID] = CurState;
384 } else if (States[NextID] < CurState) {
385 States[NextID] = CurState;
386 Stack.push_back(I);
387 }
388 }
389 }
390 // Return true if the exit node is reachable, and only reachable through
391 // a throw expression.
392 return States[ExitID] == FoundPathForThrow;
393}
394
395static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
396 const FunctionDecl *FD) {
Erich Keane7538b352017-07-05 16:43:45 +0000397 if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
398 FD->getTypeSourceInfo()) {
Erich Keane89fe9c22017-06-23 20:22:19 +0000399 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
400 if (S.getLangOpts().CPlusPlus11 &&
401 (isa<CXXDestructorDecl>(FD) ||
402 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
Erich Keane7538b352017-07-05 16:43:45 +0000403 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
404 if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
405 getAs<FunctionProtoType>())
406 S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
407 << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
408 << FD->getExceptionSpecSourceRange();
409 } else
410 S.Diag(FD->getLocation(), diag::note_throw_in_function)
411 << FD->getExceptionSpecSourceRange();
Erich Keane89fe9c22017-06-23 20:22:19 +0000412 }
413}
414
415static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
416 AnalysisDeclContext &AC) {
417 CFG *BodyCFG = AC.getCFG();
418 if (!BodyCFG)
419 return;
420 if (BodyCFG->getExit().pred_empty())
421 return;
422 SourceLocation OpLoc;
423 if (hasThrowOutNonThrowingFunc(OpLoc, BodyCFG))
424 EmitDiagForCXXThrowInNonThrowingFunc(S, OpLoc, FD);
425}
426
427static bool isNoexcept(const FunctionDecl *FD) {
428 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
Erich Keane7538b352017-07-05 16:43:45 +0000429 if (FPT->isNothrow(FD->getASTContext()))
Erich Keane89fe9c22017-06-23 20:22:19 +0000430 return true;
431 return false;
432}
433
434//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000435// Check for missing return value.
436//===----------------------------------------------------------------------===//
437
John McCall5c6ec8c2010-05-16 09:34:11 +0000438enum ControlFlowKind {
439 UnknownFallThrough,
440 NeverFallThrough,
441 MaybeFallThrough,
442 AlwaysFallThrough,
443 NeverFallThroughOrReturn
444};
Ted Kremenek918fe842010-03-20 21:06:02 +0000445
446/// CheckFallThrough - Check that we don't fall off the end of a
447/// Statement that should return a value.
448///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000449/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
450/// MaybeFallThrough iff we might or might not fall off the end,
451/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
452/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000453/// statement but we may return. We assume that functions not marked noreturn
454/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000455static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000456 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000457 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000458
459 // The CFG leaves in dead things, and we don't want the dead code paths to
460 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000461 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000462 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000463 live);
464
465 bool AddEHEdges = AC.getAddEHEdges();
466 if (!AddEHEdges && count != cfg->getNumBlockIDs())
467 // When there are things remaining dead, and we didn't add EH edges
468 // from CallExprs to the catch clauses, we have to go back and
469 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000470 for (const auto *B : *cfg) {
471 if (!live[B->getBlockID()]) {
472 if (B->pred_begin() == B->pred_end()) {
473 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000474 // When not adding EH edges from calls, catch clauses
475 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000476 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000477 continue;
478 }
479 }
480 }
481
482 // Now we know what is live, we check the live precessors of the exit block
483 // and look for fall through paths, being careful to ignore normal returns,
484 // and exceptional paths.
485 bool HasLiveReturn = false;
486 bool HasFakeEdge = false;
487 bool HasPlainEdge = false;
488 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000489
490 // Ignore default cases that aren't likely to be reachable because all
491 // enums in a switch(X) have explicit case statements.
492 CFGBlock::FilterOptions FO;
493 FO.IgnoreDefaultsWithCoveredEnums = 1;
494
495 for (CFGBlock::filtered_pred_iterator
496 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
497 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000498 if (!live[B.getBlockID()])
499 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000500
Chandler Carruth03faf782011-09-13 09:53:58 +0000501 // Skip blocks which contain an element marked as no-return. They don't
502 // represent actually viable edges into the exit block, so mark them as
503 // abnormal.
504 if (B.hasNoReturnElement()) {
505 HasAbnormalEdge = true;
506 continue;
507 }
508
Ted Kremenek5d068492011-01-26 04:49:52 +0000509 // Destructors can appear after the 'return' in the CFG. This is
510 // normal. We need to look pass the destructors for the return
511 // statement (if it exists).
512 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000513
Chandler Carruth03faf782011-09-13 09:53:58 +0000514 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000515 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000516 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000517
Ted Kremenek5d068492011-01-26 04:49:52 +0000518 // No more CFGElements in the block?
519 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000520 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
521 HasAbnormalEdge = true;
522 continue;
523 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000524 // A labeled empty statement, or the entry block...
525 HasPlainEdge = true;
526 continue;
527 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000528
David Blaikie2a01f5d2013-02-21 20:58:29 +0000529 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000530 const Stmt *S = CS.getStmt();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000531 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000532 HasLiveReturn = true;
533 continue;
534 }
535 if (isa<ObjCAtThrowStmt>(S)) {
536 HasFakeEdge = true;
537 continue;
538 }
539 if (isa<CXXThrowExpr>(S)) {
540 HasFakeEdge = true;
541 continue;
542 }
Chad Rosier32503022012-06-11 20:47:18 +0000543 if (isa<MSAsmStmt>(S)) {
544 // TODO: Verify this is correct.
545 HasFakeEdge = true;
546 HasLiveReturn = true;
547 continue;
548 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000549 if (isa<CXXTryStmt>(S)) {
550 HasAbnormalEdge = true;
551 continue;
552 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000553 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
554 == B.succ_end()) {
555 HasAbnormalEdge = true;
556 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000557 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000558
559 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000560 }
561 if (!HasPlainEdge) {
562 if (HasLiveReturn)
563 return NeverFallThrough;
564 return NeverFallThroughOrReturn;
565 }
566 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
567 return MaybeFallThrough;
568 // This says AlwaysFallThrough for calls to functions that are not marked
569 // noreturn, that don't return. If people would like this warning to be more
570 // accurate, such functions should be marked as noreturn.
571 return AlwaysFallThrough;
572}
573
Dan Gohman28ade552010-07-26 21:25:24 +0000574namespace {
575
Ted Kremenek918fe842010-03-20 21:06:02 +0000576struct CheckFallThroughDiagnostics {
577 unsigned diag_MaybeFallThrough_HasNoReturn;
578 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
579 unsigned diag_AlwaysFallThrough_HasNoReturn;
580 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
581 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000582 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000583 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000584
Douglas Gregor24f27692010-04-16 23:28:44 +0000585 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000586 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000587 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000588 D.diag_MaybeFallThrough_HasNoReturn =
589 diag::warn_falloff_noreturn_function;
590 D.diag_MaybeFallThrough_ReturnsNonVoid =
591 diag::warn_maybe_falloff_nonvoid_function;
592 D.diag_AlwaysFallThrough_HasNoReturn =
593 diag::warn_falloff_noreturn_function;
594 D.diag_AlwaysFallThrough_ReturnsNonVoid =
595 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000596
597 // Don't suggest that virtual functions be marked "noreturn", since they
598 // might be overridden by non-noreturn functions.
599 bool isVirtualMethod = false;
600 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
601 isVirtualMethod = Method->isVirtual();
602
Douglas Gregor0de57202011-10-10 18:15:57 +0000603 // Don't suggest that template instantiations be marked "noreturn"
604 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000605 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
606 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000607
608 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000609 D.diag_NeverFallThroughOrReturn =
610 diag::warn_suggest_noreturn_function;
611 else
612 D.diag_NeverFallThroughOrReturn = 0;
613
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000614 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000615 return D;
616 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000617
Eric Fiselier709d1b32016-10-27 07:30:31 +0000618 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
619 CheckFallThroughDiagnostics D;
620 D.FuncLoc = Func->getLocation();
621 D.diag_MaybeFallThrough_HasNoReturn = 0;
622 D.diag_MaybeFallThrough_ReturnsNonVoid =
623 diag::warn_maybe_falloff_nonvoid_coroutine;
624 D.diag_AlwaysFallThrough_HasNoReturn = 0;
625 D.diag_AlwaysFallThrough_ReturnsNonVoid =
626 diag::warn_falloff_nonvoid_coroutine;
627 D.funMode = Coroutine;
628 return D;
629 }
630
Ted Kremenek918fe842010-03-20 21:06:02 +0000631 static CheckFallThroughDiagnostics MakeForBlock() {
632 CheckFallThroughDiagnostics D;
633 D.diag_MaybeFallThrough_HasNoReturn =
634 diag::err_noreturn_block_has_return_expr;
635 D.diag_MaybeFallThrough_ReturnsNonVoid =
636 diag::err_maybe_falloff_nonvoid_block;
637 D.diag_AlwaysFallThrough_HasNoReturn =
638 diag::err_noreturn_block_has_return_expr;
639 D.diag_AlwaysFallThrough_ReturnsNonVoid =
640 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000641 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000642 D.funMode = Block;
643 return D;
644 }
645
646 static CheckFallThroughDiagnostics MakeForLambda() {
647 CheckFallThroughDiagnostics D;
648 D.diag_MaybeFallThrough_HasNoReturn =
649 diag::err_noreturn_lambda_has_return_expr;
650 D.diag_MaybeFallThrough_ReturnsNonVoid =
651 diag::warn_maybe_falloff_nonvoid_lambda;
652 D.diag_AlwaysFallThrough_HasNoReturn =
653 diag::err_noreturn_lambda_has_return_expr;
654 D.diag_AlwaysFallThrough_ReturnsNonVoid =
655 diag::warn_falloff_nonvoid_lambda;
656 D.diag_NeverFallThroughOrReturn = 0;
657 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000658 return D;
659 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000660
David Blaikie9c902b52011-09-25 23:23:43 +0000661 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000662 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000663 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000664 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000665 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
666 FuncLoc)) &&
667 (!HasNoReturn ||
668 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
669 FuncLoc)) &&
670 (!ReturnsVoid ||
671 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000672 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000673 if (funMode == Coroutine) {
674 return (ReturnsVoid ||
675 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
676 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
677 FuncLoc)) &&
678 (!HasNoReturn);
679 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000680 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000681 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000682 }
683};
684
Hans Wennborgdcfba332015-10-06 23:40:43 +0000685} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000686
Ted Kremenek918fe842010-03-20 21:06:02 +0000687/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
688/// function that should return a value. Check that we don't fall off the end
689/// of a noreturn function. We assume that functions and blocks not marked
690/// noreturn will return.
691static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000692 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000693 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000694 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000695
696 bool ReturnsVoid = false;
697 bool HasNoReturn = false;
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000698 bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
Ted Kremenek918fe842010-03-20 21:06:02 +0000699
Eric Fiselier709d1b32016-10-27 07:30:31 +0000700 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
701 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
702 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
703 else
704 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000705 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000706 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000707 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000708 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000709 HasNoReturn = MD->hasAttr<NoReturnAttr>();
710 }
711 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000712 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000713 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000714 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000715 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000716 ReturnsVoid = true;
717 if (FT->getNoReturnAttr())
718 HasNoReturn = true;
719 }
720 }
721
David Blaikie9c902b52011-09-25 23:23:43 +0000722 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000723
724 // Short circuit for compilation speed.
725 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
726 return;
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000727 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000728 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
729 if (IsCoroutine)
730 S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
731 else
732 S.Diag(Loc, DiagID);
733 };
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000734 // Either in a function body compound statement, or a function-try-block.
735 switch (CheckFallThrough(AC)) {
736 case UnknownFallThrough:
737 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000738
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000739 case MaybeFallThrough:
740 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000741 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000742 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000743 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000744 break;
745 case AlwaysFallThrough:
746 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000747 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000748 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000749 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000750 break;
751 case NeverFallThroughOrReturn:
752 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
753 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
754 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
755 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
756 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
757 } else {
758 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000759 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000760 }
761 break;
762 case NeverFallThrough:
763 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000764 }
765}
766
767//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000768// -Wuninitialized
769//===----------------------------------------------------------------------===//
770
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000771namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000772/// ContainsReference - A visitor class to search for references to
773/// a particular declaration (the needle) within any evaluated component of an
774/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000775class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000776 bool FoundReference;
777 const DeclRefExpr *Needle;
778
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000779public:
Scott Douglass503fc392015-06-10 13:53:15 +0000780 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000781
Scott Douglass503fc392015-06-10 13:53:15 +0000782 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
783 : Inherited(Context), FoundReference(false), Needle(Needle) {}
784
785 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000786 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000787 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000788 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000789
Scott Douglass503fc392015-06-10 13:53:15 +0000790 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000791 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000792
Scott Douglass503fc392015-06-10 13:53:15 +0000793 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000794 if (E == Needle)
795 FoundReference = true;
796 else
Scott Douglass503fc392015-06-10 13:53:15 +0000797 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000798 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000799
800 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000801};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000802} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000803
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000804static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000805 QualType VariableTy = VD->getType().getCanonicalType();
806 if (VariableTy->isBlockPointerType() &&
807 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000808 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
809 << VD->getDeclName()
810 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000811 return true;
812 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000813
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000814 // Don't issue a fixit if there is already an initializer.
815 if (VD->getInit())
816 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000817
818 // Don't suggest a fixit inside macros.
819 if (VD->getLocEnd().isMacroID())
820 return false;
821
Alp Tokerb6cc5922014-05-03 03:45:55 +0000822 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000823
824 // Suggest possible initialization (if any).
825 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
826 if (Init.empty())
827 return false;
828
Richard Smith8d06f422012-01-12 23:53:29 +0000829 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
830 << FixItHint::CreateInsertion(Loc, Init);
831 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000832}
833
Richard Smith1bb8edb82012-05-26 06:20:46 +0000834/// Create a fixit to remove an if-like statement, on the assumption that its
835/// condition is CondVal.
836static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
837 const Stmt *Else, bool CondVal,
838 FixItHint &Fixit1, FixItHint &Fixit2) {
839 if (CondVal) {
840 // If condition is always true, remove all but the 'then'.
841 Fixit1 = FixItHint::CreateRemoval(
842 CharSourceRange::getCharRange(If->getLocStart(),
843 Then->getLocStart()));
844 if (Else) {
Craig Topper07fa1762015-11-15 02:31:46 +0000845 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000846 Fixit2 = FixItHint::CreateRemoval(
847 SourceRange(ElseKwLoc, Else->getLocEnd()));
848 }
849 } else {
850 // If condition is always false, remove all but the 'else'.
851 if (Else)
852 Fixit1 = FixItHint::CreateRemoval(
853 CharSourceRange::getCharRange(If->getLocStart(),
854 Else->getLocStart()));
855 else
856 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
857 }
858}
859
860/// DiagUninitUse -- Helper function to produce a diagnostic for an
861/// uninitialized use of a variable.
862static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
863 bool IsCapturedByBlock) {
864 bool Diagnosed = false;
865
Richard Smithba8071e2013-09-12 18:49:10 +0000866 switch (Use.getKind()) {
867 case UninitUse::Always:
868 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
869 << VD->getDeclName() << IsCapturedByBlock
870 << Use.getUser()->getSourceRange();
871 return;
872
873 case UninitUse::AfterDecl:
874 case UninitUse::AfterCall:
875 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
876 << VD->getDeclName() << IsCapturedByBlock
877 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
878 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
879 << VD->getSourceRange();
880 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
881 << IsCapturedByBlock << Use.getUser()->getSourceRange();
882 return;
883
884 case UninitUse::Maybe:
885 case UninitUse::Sometimes:
886 // Carry on to report sometimes-uninitialized branches, if possible,
887 // or a 'may be used uninitialized' diagnostic otherwise.
888 break;
889 }
890
Richard Smith1bb8edb82012-05-26 06:20:46 +0000891 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000892 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
893 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000894 assert(Use.getKind() == UninitUse::Sometimes);
895
896 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000897 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000898
899 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000900 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000901 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000902 SourceRange Range;
903
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000904 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000905 // For all binary terminators, branch 0 is taken if the condition is true,
906 // and branch 1 is taken if the condition is false.
907 int RemoveDiagKind = -1;
908 const char *FixitStr =
909 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
910 : (I->Output ? "1" : "0");
911 FixItHint Fixit1, Fixit2;
912
Richard Smithba8071e2013-09-12 18:49:10 +0000913 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000914 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000915 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000916 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000917 continue;
918
919 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000920 case Stmt::IfStmtClass: {
921 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000922 DiagKind = 0;
923 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000924 Range = IS->getCond()->getSourceRange();
925 RemoveDiagKind = 0;
926 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
927 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000928 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000929 }
930 case Stmt::ConditionalOperatorClass: {
931 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000932 DiagKind = 0;
933 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000934 Range = CO->getCond()->getSourceRange();
935 RemoveDiagKind = 0;
936 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
937 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000938 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000939 }
Richard Smith4323bf82012-05-25 02:17:09 +0000940 case Stmt::BinaryOperatorClass: {
941 const BinaryOperator *BO = cast<BinaryOperator>(Term);
942 if (!BO->isLogicalOp())
943 continue;
944 DiagKind = 0;
945 Str = BO->getOpcodeStr();
946 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000947 RemoveDiagKind = 0;
948 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
949 (BO->getOpcode() == BO_LOr && !I->Output))
950 // true && y -> y, false || y -> y.
951 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
952 BO->getOperatorLoc()));
953 else
954 // false && y -> false, true || y -> true.
955 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000956 break;
957 }
958
959 // "loop is entered / loop is exited".
960 case Stmt::WhileStmtClass:
961 DiagKind = 1;
962 Str = "while";
963 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000964 RemoveDiagKind = 1;
965 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000966 break;
967 case Stmt::ForStmtClass:
968 DiagKind = 1;
969 Str = "for";
970 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000971 RemoveDiagKind = 1;
972 if (I->Output)
973 Fixit1 = FixItHint::CreateRemoval(Range);
974 else
975 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000976 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000977 case Stmt::CXXForRangeStmtClass:
978 if (I->Output == 1) {
979 // The use occurs if a range-based for loop's body never executes.
980 // That may be impossible, and there's no syntactic fix for this,
981 // so treat it as a 'may be uninitialized' case.
982 continue;
983 }
984 DiagKind = 1;
985 Str = "for";
986 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
987 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000988
989 // "condition is true / loop is exited".
990 case Stmt::DoStmtClass:
991 DiagKind = 2;
992 Str = "do";
993 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000994 RemoveDiagKind = 1;
995 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000996 break;
997
998 // "switch case is taken".
999 case Stmt::CaseStmtClass:
1000 DiagKind = 3;
1001 Str = "case";
1002 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
1003 break;
1004 case Stmt::DefaultStmtClass:
1005 DiagKind = 3;
1006 Str = "default";
1007 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
1008 break;
1009 }
1010
Richard Smith1bb8edb82012-05-26 06:20:46 +00001011 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
1012 << VD->getDeclName() << IsCapturedByBlock << DiagKind
1013 << Str << I->Output << Range;
1014 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
1015 << IsCapturedByBlock << User->getSourceRange();
1016 if (RemoveDiagKind != -1)
1017 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
1018 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
1019
1020 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +00001021 }
Richard Smith1bb8edb82012-05-26 06:20:46 +00001022
1023 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +00001024 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +00001025 << VD->getDeclName() << IsCapturedByBlock
1026 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +00001027}
1028
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001029/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
1030/// uninitialized variable. This manages the different forms of diagnostic
1031/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +00001032/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001033/// false.
1034static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +00001035 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +00001036 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +00001037 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +00001038 // Inspect the initializer of the variable declaration which is
1039 // being referenced prior to its initialization. We emit
1040 // specialized diagnostics for self-initialization, and we
1041 // specifically avoid warning about self references which take the
1042 // form of:
1043 //
1044 // int x = x;
1045 //
1046 // This is used to indicate to GCC that 'x' is intentionally left
1047 // uninitialized. Proven code paths which access 'x' in
1048 // an uninitialized state after this will still warn.
1049 if (const Expr *Initializer = VD->getInit()) {
1050 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1051 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +00001052
Richard Trieu43a2fc72012-05-09 21:08:22 +00001053 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +00001054 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +00001055 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +00001056 S.Diag(DRE->getLocStart(),
1057 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +00001058 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1059 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +00001060 }
Chandler Carruth895904da2011-04-05 18:18:05 +00001061 }
Richard Trieu43a2fc72012-05-09 21:08:22 +00001062
Richard Smith1bb8edb82012-05-26 06:20:46 +00001063 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +00001064 } else {
Richard Smith4323bf82012-05-25 02:17:09 +00001065 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +00001066 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1067 S.Diag(BE->getLocStart(),
1068 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +00001069 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +00001070 else
1071 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +00001072 }
1073
1074 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +00001075 // the initializer of that declaration & we didn't already suggest
1076 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +00001077 if (!SuggestInitializationFixit(S, VD))
Reid Klecknerf463a8a2016-04-29 00:37:43 +00001078 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
Chandler Carruth895904da2011-04-05 18:18:05 +00001079 << VD->getDeclName();
1080
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001081 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +00001082}
1083
Richard Smith84837d52012-05-03 18:27:39 +00001084namespace {
1085 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1086 public:
1087 FallthroughMapper(Sema &S)
1088 : FoundSwitchStatements(false),
1089 S(S) {
1090 }
1091
1092 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1093
1094 void markFallthroughVisited(const AttributedStmt *Stmt) {
1095 bool Found = FallthroughStmts.erase(Stmt);
1096 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +00001097 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +00001098 }
1099
1100 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1101
1102 const AttrStmts &getFallthroughStmts() const {
1103 return FallthroughStmts;
1104 }
1105
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001106 void fillReachableBlocks(CFG *Cfg) {
1107 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1108 std::deque<const CFGBlock *> BlockQueue;
1109
1110 ReachableBlocks.insert(&Cfg->getEntry());
1111 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001112 // Mark all case blocks reachable to avoid problems with switching on
1113 // constants, covered enums, etc.
1114 // These blocks can contain fall-through annotations, and we don't want to
1115 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +00001116 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001117 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +00001118 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001119 BlockQueue.push_back(B);
1120 }
1121
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001122 while (!BlockQueue.empty()) {
1123 const CFGBlock *P = BlockQueue.front();
1124 BlockQueue.pop_front();
1125 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1126 E = P->succ_end();
1127 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001128 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001129 BlockQueue.push_back(*I);
1130 }
1131 }
1132 }
1133
Richard Smith7532d372017-03-22 01:49:19 +00001134 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1135 bool IsTemplateInstantiation) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001136 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1137
Richard Smith84837d52012-05-03 18:27:39 +00001138 int UnannotatedCnt = 0;
1139 AnnotatedCnt = 0;
1140
Aaron Ballmane5195222014-05-15 20:50:47 +00001141 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +00001142 while (!BlockQueue.empty()) {
1143 const CFGBlock *P = BlockQueue.front();
1144 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +00001145 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +00001146
1147 const Stmt *Term = P->getTerminator();
1148 if (Term && isa<SwitchStmt>(Term))
1149 continue; // Switch statement, good.
1150
1151 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1152 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1153 continue; // Previous case label has no statements, good.
1154
Alexander Kornienko09f15f32013-01-25 20:44:56 +00001155 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1156 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1157 continue; // Case label is preceded with a normal label, good.
1158
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001159 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001160 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1161 ElemEnd = P->rend();
1162 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001163 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1164 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith7532d372017-03-22 01:49:19 +00001165 // Don't issue a warning for an unreachable fallthrough
1166 // attribute in template instantiations as it may not be
1167 // unreachable in all instantiations of the template.
1168 if (!IsTemplateInstantiation)
1169 S.Diag(AS->getLocStart(),
1170 diag::warn_fallthrough_attr_unreachable);
Richard Smith84837d52012-05-03 18:27:39 +00001171 markFallthroughVisited(AS);
1172 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001173 break;
Richard Smith84837d52012-05-03 18:27:39 +00001174 }
1175 // Don't care about other unreachable statements.
1176 }
1177 }
1178 // If there are no unreachable statements, this may be a special
1179 // case in CFG:
1180 // case X: {
1181 // A a; // A has a destructor.
1182 // break;
1183 // }
1184 // // <<<< This place is represented by a 'hanging' CFG block.
1185 // case Y:
1186 continue;
1187 }
1188
1189 const Stmt *LastStmt = getLastStmt(*P);
1190 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1191 markFallthroughVisited(AS);
1192 ++AnnotatedCnt;
1193 continue; // Fallthrough annotation, good.
1194 }
1195
1196 if (!LastStmt) { // This block contains no executable statements.
1197 // Traverse its predecessors.
1198 std::copy(P->pred_begin(), P->pred_end(),
1199 std::back_inserter(BlockQueue));
1200 continue;
1201 }
1202
1203 ++UnannotatedCnt;
1204 }
1205 return !!UnannotatedCnt;
1206 }
1207
1208 // RecursiveASTVisitor setup.
1209 bool shouldWalkTypesOfTypeLocs() const { return false; }
1210
1211 bool VisitAttributedStmt(AttributedStmt *S) {
1212 if (asFallThroughAttr(S))
1213 FallthroughStmts.insert(S);
1214 return true;
1215 }
1216
1217 bool VisitSwitchStmt(SwitchStmt *S) {
1218 FoundSwitchStatements = true;
1219 return true;
1220 }
1221
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001222 // We don't want to traverse local type declarations. We analyze their
1223 // methods separately.
1224 bool TraverseDecl(Decl *D) { return true; }
1225
Alexander Kornienkobf911642014-06-24 15:28:21 +00001226 // We analyze lambda bodies separately. Skip them here.
1227 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1228
Richard Smith84837d52012-05-03 18:27:39 +00001229 private:
1230
1231 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1232 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1233 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1234 return AS;
1235 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001236 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001237 }
1238
1239 static const Stmt *getLastStmt(const CFGBlock &B) {
1240 if (const Stmt *Term = B.getTerminator())
1241 return Term;
1242 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1243 ElemEnd = B.rend();
1244 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001245 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1246 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001247 }
1248 // Workaround to detect a statement thrown out by CFGBuilder:
1249 // case X: {} case Y:
1250 // case X: ; case Y:
1251 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1252 if (!isa<SwitchCase>(SW->getSubStmt()))
1253 return SW->getSubStmt();
1254
Craig Topperc3ec1492014-05-26 06:22:03 +00001255 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001256 }
1257
1258 bool FoundSwitchStatements;
1259 AttrStmts FallthroughStmts;
1260 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001261 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001262 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001263} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001264
Richard Smith4f902c72016-03-08 00:32:55 +00001265static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1266 SourceLocation Loc) {
1267 TokenValue FallthroughTokens[] = {
1268 tok::l_square, tok::l_square,
1269 PP.getIdentifierInfo("fallthrough"),
1270 tok::r_square, tok::r_square
1271 };
1272
1273 TokenValue ClangFallthroughTokens[] = {
1274 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1275 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1276 tok::r_square, tok::r_square
1277 };
1278
1279 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1280
1281 StringRef MacroName;
1282 if (PreferClangAttr)
1283 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1284 if (MacroName.empty())
1285 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1286 if (MacroName.empty() && !PreferClangAttr)
1287 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1288 if (MacroName.empty())
1289 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1290 return MacroName;
1291}
1292
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001293static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001294 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001295 // Only perform this analysis when using C++11. There is no good workflow
1296 // for this warning when not using C++11. There is no good way to silence
1297 // the warning (no attribute is available) unless we are using C++11's support
1298 // for generalized attributes. Once could use pragmas to silence the warning,
1299 // but as a general solution that is gross and not in the spirit of this
1300 // warning.
1301 //
1302 // NOTE: This an intermediate solution. There are on-going discussions on
1303 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001304 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001305 return;
1306
Richard Smith84837d52012-05-03 18:27:39 +00001307 FallthroughMapper FM(S);
1308 FM.TraverseStmt(AC.getBody());
1309
1310 if (!FM.foundSwitchStatements())
1311 return;
1312
Alexis Hunt2178f142012-06-15 21:22:05 +00001313 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001314 return;
1315
Richard Smith84837d52012-05-03 18:27:39 +00001316 CFG *Cfg = AC.getCFG();
1317
1318 if (!Cfg)
1319 return;
1320
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001321 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001322
Pete Cooper57d3f142015-07-30 17:22:52 +00001323 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001324 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001325
1326 if (!Label || !isa<SwitchCase>(Label))
1327 continue;
1328
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001329 int AnnotatedCnt;
1330
Richard Smith7532d372017-03-22 01:49:19 +00001331 bool IsTemplateInstantiation = false;
1332 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1333 IsTemplateInstantiation = Function->isTemplateInstantiation();
1334 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1335 IsTemplateInstantiation))
Richard Smith84837d52012-05-03 18:27:39 +00001336 continue;
1337
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001338 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001339 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1340 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001341
1342 if (!AnnotatedCnt) {
1343 SourceLocation L = Label->getLocStart();
1344 if (L.isMacroID())
1345 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001346 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001347 const Stmt *Term = B->getTerminator();
1348 // Skip empty cases.
1349 while (B->empty() && !Term && B->succ_size() == 1) {
1350 B = *B->succ_begin();
1351 Term = B->getTerminator();
1352 }
1353 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001354 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001355 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001356 SmallString<64> TextToInsert(AnnotationSpelling);
1357 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001358 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001359 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001360 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001361 }
Richard Smith84837d52012-05-03 18:27:39 +00001362 }
1363 S.Diag(L, diag::note_insert_break_fixit) <<
1364 FixItHint::CreateInsertion(L, "break; ");
1365 }
1366 }
1367
Aaron Ballmane5195222014-05-15 20:50:47 +00001368 for (const auto *F : FM.getFallthroughStmts())
Richard Smith4f902c72016-03-08 00:32:55 +00001369 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001370}
1371
Jordan Rose25c0ea82012-10-29 17:46:47 +00001372static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1373 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001374 assert(S);
1375
1376 do {
1377 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001378 case Stmt::ForStmtClass:
1379 case Stmt::WhileStmtClass:
1380 case Stmt::CXXForRangeStmtClass:
1381 case Stmt::ObjCForCollectionStmtClass:
1382 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001383 case Stmt::DoStmtClass: {
1384 const Expr *Cond = cast<DoStmt>(S)->getCond();
1385 llvm::APSInt Val;
1386 if (!Cond->EvaluateAsInt(Val, Ctx))
1387 return true;
1388 return Val.getBoolValue();
1389 }
Jordan Rose76831c62012-10-11 16:10:19 +00001390 default:
1391 break;
1392 }
1393 } while ((S = PM.getParent(S)));
1394
1395 return false;
1396}
1397
Jordan Rosed3934582012-09-28 22:21:30 +00001398static void diagnoseRepeatedUseOfWeak(Sema &S,
1399 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001400 const Decl *D,
1401 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001402 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1403 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1404 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001405 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1406 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001407
Jordan Rose25c0ea82012-10-29 17:46:47 +00001408 ASTContext &Ctx = S.getASTContext();
1409
Jordan Rosed3934582012-09-28 22:21:30 +00001410 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1411
1412 // Extract all weak objects that are referenced more than once.
1413 SmallVector<StmtUsesPair, 8> UsesByStmt;
1414 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1415 I != E; ++I) {
1416 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001417
1418 // Find the first read of the weak object.
1419 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1420 for ( ; UI != UE; ++UI) {
1421 if (UI->isUnsafe())
1422 break;
1423 }
1424
1425 // If there were only writes to this object, don't warn.
1426 if (UI == UE)
1427 continue;
1428
Jordan Rose76831c62012-10-11 16:10:19 +00001429 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001430 // read is not within a loop, don't warn. Additionally, don't warn in a
1431 // loop if the base object is a local variable -- local variables are often
1432 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001433 if (UI == Uses.begin()) {
1434 WeakUseVector::const_iterator UI2 = UI;
1435 for (++UI2; UI2 != UE; ++UI2)
1436 if (UI2->isUnsafe())
1437 break;
1438
Jordan Rose25c0ea82012-10-29 17:46:47 +00001439 if (UI2 == UE) {
1440 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001441 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001442
1443 const WeakObjectProfileTy &Profile = I->first;
1444 if (!Profile.isExactProfile())
1445 continue;
1446
1447 const NamedDecl *Base = Profile.getBase();
1448 if (!Base)
1449 Base = Profile.getProperty();
1450 assert(Base && "A profile always has a base or property.");
1451
1452 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1453 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1454 continue;
1455 }
Jordan Rose76831c62012-10-11 16:10:19 +00001456 }
1457
Jordan Rosed3934582012-09-28 22:21:30 +00001458 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1459 }
1460
1461 if (UsesByStmt.empty())
1462 return;
1463
1464 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001465 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001466 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001467 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1468 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1469 RHS.first->getLocStart());
1470 });
Jordan Rosed3934582012-09-28 22:21:30 +00001471
1472 // Classify the current code body for better warning text.
1473 // This enum should stay in sync with the cases in
1474 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1475 // FIXME: Should we use a common classification enum and the same set of
1476 // possibilities all throughout Sema?
1477 enum {
1478 Function,
1479 Method,
1480 Block,
1481 Lambda
1482 } FunctionKind;
1483
1484 if (isa<sema::BlockScopeInfo>(CurFn))
1485 FunctionKind = Block;
1486 else if (isa<sema::LambdaScopeInfo>(CurFn))
1487 FunctionKind = Lambda;
1488 else if (isa<ObjCMethodDecl>(D))
1489 FunctionKind = Method;
1490 else
1491 FunctionKind = Function;
1492
1493 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001494 for (const auto &P : UsesByStmt) {
1495 const Stmt *FirstRead = P.first;
1496 const WeakObjectProfileTy &Key = P.second->first;
1497 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001498
Jordan Rose657b5f42012-09-28 22:21:35 +00001499 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1500 // may not contain enough information to determine that these are different
1501 // properties. We can only be 100% sure of a repeated use in certain cases,
1502 // and we adjust the diagnostic kind accordingly so that the less certain
1503 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001504 unsigned DiagKind;
1505 if (Key.isExactProfile())
1506 DiagKind = diag::warn_arc_repeated_use_of_weak;
1507 else
1508 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1509
Jordan Rose657b5f42012-09-28 22:21:35 +00001510 // Classify the weak object being accessed for better warning text.
1511 // This enum should stay in sync with the cases in
1512 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1513 enum {
1514 Variable,
1515 Property,
1516 ImplicitProperty,
1517 Ivar
1518 } ObjectKind;
1519
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001520 const NamedDecl *KeyProp = Key.getProperty();
1521 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001522 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001523 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001524 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001525 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001526 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001527 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001528 ObjectKind = Ivar;
1529 else
1530 llvm_unreachable("Unexpected weak object kind!");
1531
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001532 // Do not warn about IBOutlet weak property receivers being set to null
1533 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001534 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001535 if (Prop->hasAttr<IBOutletAttr>())
1536 continue;
1537
Jordan Rosed3934582012-09-28 22:21:30 +00001538 // Show the first time the object was read.
1539 S.Diag(FirstRead->getLocStart(), DiagKind)
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001540 << int(ObjectKind) << KeyProp << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001541 << FirstRead->getSourceRange();
1542
1543 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001544 for (const auto &Use : Uses) {
1545 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001546 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001547 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001548 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001549 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001550 }
1551 }
1552}
1553
Jordan Rosed3934582012-09-28 22:21:30 +00001554namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001555class UninitValsDiagReporter : public UninitVariablesHandler {
1556 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001557 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001558 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001559 // Prefer using MapVector to DenseMap, so that iteration order will be
1560 // the same as insertion order. This is needed to obtain a deterministic
1561 // order of diagnostics when calling flushDiagnostics().
1562 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001563 UsesMap uses;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001564
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001565public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001566 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001567 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001568
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001569 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001570 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001571 if (!V.getPointer())
1572 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001573 return V;
1574 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001575
1576 void handleUseOfUninitVariable(const VarDecl *vd,
1577 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001578 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001579 }
1580
Craig Toppere14c0f82014-03-12 04:55:44 +00001581 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001582 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001583 }
1584
1585 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001586 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001587 const VarDecl *vd = P.first;
1588 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001589
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001590 UsesVec *vec = V.getPointer();
1591 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001592
1593 // Specially handle the case where we have uses of an uninitialized
1594 // variable, but the root cause is an idiomatic self-init. We want
1595 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001596 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001597 DiagnoseUninitializedUse(S, vd,
1598 UninitUse(vd->getInit()->IgnoreParenCasts(),
1599 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001600 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001601 else {
1602 // Sort the uses by their SourceLocations. While not strictly
1603 // guaranteed to produce them in line/column order, this will provide
1604 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001605 std::sort(vec->begin(), vec->end(),
1606 [](const UninitUse &a, const UninitUse &b) {
1607 // Prefer a more confident report over a less confident one.
1608 if (a.getKind() != b.getKind())
1609 return a.getKind() > b.getKind();
1610 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1611 });
1612
Aaron Ballmane5195222014-05-15 20:50:47 +00001613 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001614 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001615 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001616
1617 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001618 // Skip further diagnostics for this variable. We try to warn only
1619 // on the first point at which a variable is used uninitialized.
1620 break;
1621 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001622 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001623
1624 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001625 delete vec;
1626 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001627
1628 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001629 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001630
1631private:
1632 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001633 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1634 return U.getKind() == UninitUse::Always ||
1635 U.getKind() == UninitUse::AfterCall ||
1636 U.getKind() == UninitUse::AfterDecl;
1637 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001638 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001639};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001640} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001641
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001642namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001643namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001644typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001645typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001646typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001647
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001648struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001649 SourceManager &SM;
1650 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001651
1652 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1653 // Although this call will be slow, this is only called when outputting
1654 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001655 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001656 }
1657};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001658} // anonymous namespace
1659} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001660
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001661//===----------------------------------------------------------------------===//
1662// -Wthread-safety
1663//===----------------------------------------------------------------------===//
1664namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001665namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001666namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001667class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001668 Sema &S;
1669 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001670 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001671
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001672 const FunctionDecl *CurrentFunction;
1673 bool Verbose;
1674
Aaron Ballman71291bc2014-08-15 12:38:17 +00001675 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001676 if (Verbose && CurrentFunction) {
1677 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001678 S.PDiag(diag::note_thread_warning_in_fun)
1679 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001680 return OptionalNotes(1, FNote);
1681 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001682 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001683 }
1684
Aaron Ballman71291bc2014-08-15 12:38:17 +00001685 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001686 OptionalNotes ONS(1, Note);
1687 if (Verbose && CurrentFunction) {
1688 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001689 S.PDiag(diag::note_thread_warning_in_fun)
1690 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001691 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001692 }
1693 return ONS;
1694 }
1695
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001696 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1697 const PartialDiagnosticAt &Note2) const {
1698 OptionalNotes ONS;
1699 ONS.push_back(Note1);
1700 ONS.push_back(Note2);
1701 if (Verbose && CurrentFunction) {
1702 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1703 S.PDiag(diag::note_thread_warning_in_fun)
1704 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001705 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001706 }
1707 return ONS;
1708 }
1709
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001710 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001711 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1712 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001713 // Gracefully handle rare cases when the analysis can't get a more
1714 // precise source location.
1715 if (!Loc.isValid())
1716 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001717 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001718 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001719 }
1720
1721 public:
Richard Smith92286672012-02-03 04:45:26 +00001722 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001723 : S(S), FunLocation(FL), FunEndLocation(FEL),
1724 CurrentFunction(nullptr), Verbose(false) {}
1725
1726 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001727
1728 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1729 /// We need to output diagnostics produced while iterating through
1730 /// the lockset in deterministic order, so this function orders diagnostics
1731 /// and outputs them.
1732 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001733 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001734 for (const auto &Diag : Warnings) {
1735 S.Diag(Diag.first.first, Diag.first.second);
1736 for (const auto &Note : Diag.second)
1737 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001738 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001739 }
1740
Aaron Ballmane0449042014-04-01 21:43:23 +00001741 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1742 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1743 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001744 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001745 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001746
Aaron Ballmane0449042014-04-01 21:43:23 +00001747 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1748 SourceLocation Loc) override {
1749 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001750 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001751
Aaron Ballmane0449042014-04-01 21:43:23 +00001752 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1753 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001754 SourceLocation Loc) override {
1755 if (Loc.isInvalid())
1756 Loc = FunLocation;
1757 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001758 << Kind << LockName << Received
1759 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001760 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001761 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001762
Aaron Ballmane0449042014-04-01 21:43:23 +00001763 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1764 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001765 }
1766
Aaron Ballmane0449042014-04-01 21:43:23 +00001767 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1768 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001769 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001770 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001771 unsigned DiagID = 0;
1772 switch (LEK) {
1773 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001774 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001775 break;
1776 case LEK_LockedSomeLoopIterations:
1777 DiagID = diag::warn_expecting_lock_held_on_loop;
1778 break;
1779 case LEK_LockedAtEndOfFunction:
1780 DiagID = diag::warn_no_unlock;
1781 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001782 case LEK_NotLockedAtEndOfFunction:
1783 DiagID = diag::warn_expecting_locked;
1784 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001785 }
Richard Smith92286672012-02-03 04:45:26 +00001786 if (LocEndOfScope.isInvalid())
1787 LocEndOfScope = FunEndLocation;
1788
Aaron Ballmane0449042014-04-01 21:43:23 +00001789 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1790 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001791 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001792 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1793 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001794 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001795 return;
1796 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001797 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001798 }
1799
Aaron Ballmane0449042014-04-01 21:43:23 +00001800 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1801 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001802 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001803 PartialDiagnosticAt Warning(Loc1,
1804 S.PDiag(diag::warn_lock_exclusive_and_shared)
1805 << Kind << LockName);
1806 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1807 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001808 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001809 }
1810
Aaron Ballmane0449042014-04-01 21:43:23 +00001811 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1812 ProtectedOperationKind POK, AccessKind AK,
1813 SourceLocation Loc) override {
1814 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1815 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001816 unsigned DiagID = POK == POK_VarAccess?
1817 diag::warn_variable_requires_any_lock:
1818 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001819 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001820 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001821 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001822 }
1823
Aaron Ballmane0449042014-04-01 21:43:23 +00001824 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1825 ProtectedOperationKind POK, Name LockName,
1826 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001827 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001828 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001829 if (PossibleMatch) {
1830 switch (POK) {
1831 case POK_VarAccess:
1832 DiagID = diag::warn_variable_requires_lock_precise;
1833 break;
1834 case POK_VarDereference:
1835 DiagID = diag::warn_var_deref_requires_lock_precise;
1836 break;
1837 case POK_FunctionCall:
1838 DiagID = diag::warn_fun_requires_lock_precise;
1839 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001840 case POK_PassByRef:
1841 DiagID = diag::warn_guarded_pass_by_reference;
1842 break;
1843 case POK_PtPassByRef:
1844 DiagID = diag::warn_pt_guarded_pass_by_reference;
1845 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001846 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001847 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1848 << D->getNameAsString()
1849 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001850 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001851 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001852 if (Verbose && POK == POK_VarAccess) {
1853 PartialDiagnosticAt VNote(D->getLocation(),
1854 S.PDiag(diag::note_guarded_by_declared_here)
1855 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001856 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001857 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001858 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001859 } else {
1860 switch (POK) {
1861 case POK_VarAccess:
1862 DiagID = diag::warn_variable_requires_lock;
1863 break;
1864 case POK_VarDereference:
1865 DiagID = diag::warn_var_deref_requires_lock;
1866 break;
1867 case POK_FunctionCall:
1868 DiagID = diag::warn_fun_requires_lock;
1869 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001870 case POK_PassByRef:
1871 DiagID = diag::warn_guarded_pass_by_reference;
1872 break;
1873 case POK_PtPassByRef:
1874 DiagID = diag::warn_pt_guarded_pass_by_reference;
1875 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001876 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001877 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1878 << D->getNameAsString()
1879 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001880 if (Verbose && POK == POK_VarAccess) {
1881 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001882 S.PDiag(diag::note_guarded_by_declared_here)
1883 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001884 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001885 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001886 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001887 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001888 }
1889
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001890 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1891 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001892 PartialDiagnosticAt Warning(Loc,
1893 S.PDiag(diag::warn_acquire_requires_negative_cap)
1894 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001895 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001896 }
1897
Aaron Ballmane0449042014-04-01 21:43:23 +00001898 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001899 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001900 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1901 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001902 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001903 }
1904
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001905 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1906 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001907 PartialDiagnosticAt Warning(Loc,
1908 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001909 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001910 }
1911
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001912 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001913 PartialDiagnosticAt Warning(Loc,
1914 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001915 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001916 }
1917
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001918 void enterFunction(const FunctionDecl* FD) override {
1919 CurrentFunction = FD;
1920 }
1921
1922 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001923 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001924 }
1925};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001926} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001927} // namespace threadSafety
1928} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001929
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001930//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001931// -Wconsumed
1932//===----------------------------------------------------------------------===//
1933
1934namespace clang {
1935namespace consumed {
1936namespace {
1937class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1938
1939 Sema &S;
1940 DiagList Warnings;
1941
1942public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001943
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001944 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001945
1946 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001947 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001948 for (const auto &Diag : Warnings) {
1949 S.Diag(Diag.first.first, Diag.first.second);
1950 for (const auto &Note : Diag.second)
1951 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001952 }
1953 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001954
1955 void warnLoopStateMismatch(SourceLocation Loc,
1956 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001957 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1958 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001959
1960 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001961 }
1962
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001963 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1964 StringRef VariableName,
1965 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001966 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001967
1968 PartialDiagnosticAt Warning(Loc, S.PDiag(
1969 diag::warn_param_return_typestate_mismatch) << VariableName <<
1970 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001971
1972 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001973 }
1974
DeLesley Hutchins69391772013-10-17 23:23:53 +00001975 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001976 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001977
1978 PartialDiagnosticAt Warning(Loc, S.PDiag(
1979 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001980
1981 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001982 }
1983
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001984 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001985 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001986 PartialDiagnosticAt Warning(Loc, S.PDiag(
1987 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001988
1989 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001990 }
1991
1992 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001993 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001994
1995 PartialDiagnosticAt Warning(Loc, S.PDiag(
1996 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001997
1998 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001999 }
2000
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002001 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00002002 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002003
2004 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002005 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002006
2007 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002008 }
2009
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002010 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00002011 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002012
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002013 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
2014 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002015
2016 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002017 }
2018};
Hans Wennborgdcfba332015-10-06 23:40:43 +00002019} // anonymous namespace
2020} // namespace consumed
2021} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002022
2023//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00002024// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
2025// warnings on a function, method, or block.
2026//===----------------------------------------------------------------------===//
2027
Ted Kremenek0b405322010-03-23 00:13:23 +00002028clang::sema::AnalysisBasedWarnings::Policy::Policy() {
2029 enableCheckFallThrough = 1;
2030 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002031 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002032 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00002033}
2034
Ted Kremenekad8753c2014-03-15 05:47:06 +00002035static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002036 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00002037}
2038
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002039clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2040 : S(s),
2041 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002042 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002043 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002044 MaxCFGBlocksPerFunction(0),
2045 NumUninitAnalysisFunctions(0),
2046 NumUninitAnalysisVariables(0),
2047 MaxUninitAnalysisVariablesPerFunction(0),
2048 NumUninitAnalysisBlockVisits(0),
2049 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00002050
2051 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00002052 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00002053
2054 DefaultPolicy.enableCheckUnreachable =
2055 isEnabled(D, warn_unreachable) ||
2056 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00002057 isEnabled(D, warn_unreachable_return) ||
2058 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00002059
2060 DefaultPolicy.enableThreadSafetyAnalysis =
2061 isEnabled(D, warn_double_lock);
2062
2063 DefaultPolicy.enableConsumedAnalysis =
2064 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00002065}
2066
Aaron Ballmane5195222014-05-15 20:50:47 +00002067static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2068 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00002069 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00002070}
2071
Ted Kremenek0b405322010-03-23 00:13:23 +00002072void clang::sema::
2073AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00002074 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00002075 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00002076
Ted Kremenek918fe842010-03-20 21:06:02 +00002077 // We avoid doing analysis-based warnings when there are errors for
2078 // two reasons:
2079 // (1) The CFGs often can't be constructed (if the body is invalid), so
2080 // don't bother trying.
2081 // (2) The code already has problems; running the analysis just takes more
2082 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00002083 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00002084
Ted Kremenek0b405322010-03-23 00:13:23 +00002085 // Do not do any analysis for declarations in system headers if we are
2086 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00002087 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00002088 S.SourceMgr.isInSystemHeader(D->getLocation()))
2089 return;
2090
John McCall1d570a72010-08-25 05:56:39 +00002091 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00002092 if (cast<DeclContext>(D)->isDependentContext())
2093 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00002094
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002095 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002096 // Flush out any possibly unreachable diagnostics.
2097 flushDiagnostics(S, fscope);
2098 return;
2099 }
2100
Ted Kremenek918fe842010-03-20 21:06:02 +00002101 const Stmt *Body = D->getBody();
2102 assert(Body);
2103
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002104 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00002105 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00002106
Ted Kremenek918fe842010-03-20 21:06:02 +00002107 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00002108 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00002109 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2110 AC.getCFGBuildOptions().AddEHEdges = false;
2111 AC.getCFGBuildOptions().AddInitializers = true;
2112 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002113 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00002114 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00002115 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002116
Ted Kremenek9e100ea2011-07-19 14:18:48 +00002117 // Force that certain expressions appear as CFGElements in the CFG. This
2118 // is used to speed up various analyses.
2119 // FIXME: This isn't the right factoring. This is here for initial
2120 // prototyping, but we need a way for analyses to say what expressions they
2121 // expect to always be CFGElements and then fill in the BuildOptions
2122 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002123 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2124 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002125 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00002126 AC.getCFGBuildOptions().setAllAlwaysAdd();
2127 }
2128 else {
2129 AC.getCFGBuildOptions()
2130 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00002131 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00002132 .setAlwaysAdd(Stmt::BlockExprClass)
2133 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2134 .setAlwaysAdd(Stmt::DeclRefExprClass)
2135 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00002136 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2137 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00002138 }
Ted Kremenek918fe842010-03-20 21:06:02 +00002139
Richard Trieue9fa2662014-04-15 00:57:50 +00002140 // Install the logical handler for -Wtautological-overlap-compare
2141 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002142 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2143 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00002144 LEH.reset(new LogicalErrorHandler(S));
2145 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00002146 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002147
Ted Kremenek3427fac2011-02-23 01:52:04 +00002148 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00002149 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002150 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00002151
2152 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00002153 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2154 if (D.stmt)
2155 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00002156 }
2157
2158 if (AC.getCFG()) {
2159 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00002160 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00002161 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00002162 if (D.stmt) {
2163 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00002164 CFGReverseBlockReachabilityAnalysis *cra =
2165 AC.getCFGReachablityAnalysis();
2166 // FIXME: We should be able to assert that block is non-null, but
2167 // the CFG analysis can skip potentially-evaluated expressions in
2168 // edge cases; see test/Sema/vla-2.c.
2169 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002170 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00002171 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00002172 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00002173 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00002174 }
2175 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002176 if (!processed) {
2177 // Emit the warning anyway if we cannot map to a basic block.
2178 S.Diag(D.Loc, D.PD);
2179 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002180 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002181 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002182
2183 if (!analyzed)
2184 flushDiagnostics(S, fscope);
2185 }
2186
Ted Kremenek918fe842010-03-20 21:06:02 +00002187 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002188 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00002189 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002190 (isa<BlockDecl>(D)
2191 ? CheckFallThroughDiagnostics::MakeForBlock()
2192 : (isa<CXXMethodDecl>(D) &&
2193 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2194 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2195 ? CheckFallThroughDiagnostics::MakeForLambda()
Eric Fiselierda8f9b52017-05-25 02:16:53 +00002196 : (fscope->isCoroutine()
Eric Fiselier709d1b32016-10-27 07:30:31 +00002197 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2198 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Ted Kremenek1767a272011-02-23 01:51:48 +00002199 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00002200 }
2201
2202 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002203 if (P.enableCheckUnreachable) {
2204 // Only check for unreachable code on non-template instantiations.
2205 // Different template instantiations can effectively change the control-flow
2206 // and it is very difficult to prove that a snippet of code in a template
2207 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002208 bool isTemplateInstantiation = false;
2209 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2210 isTemplateInstantiation = Function->isTemplateInstantiation();
2211 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002212 CheckUnreachable(S, AC);
2213 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002214
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002215 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002216 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002217 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00002218 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002219 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002220 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002221 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002222 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2223 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002224
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002225 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2226 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002227 Reporter.emitDiagnostics();
2228 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002229
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002230 // Check for violations of consumed properties.
2231 if (P.enableConsumedAnalysis) {
2232 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002233 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002234 Analyzer.run(AC);
2235 }
2236
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002237 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2238 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2239 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002240 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002241 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002242 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002243 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002244 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002245 reporter, stats);
2246
2247 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2248 ++NumUninitAnalysisFunctions;
2249 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2250 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2251 MaxUninitAnalysisVariablesPerFunction =
2252 std::max(MaxUninitAnalysisVariablesPerFunction,
2253 stats.NumVariablesAnalyzed);
2254 MaxUninitAnalysisBlockVisitsPerFunction =
2255 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2256 stats.NumBlockVisits);
2257 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002258 }
2259 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002260
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002261 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002262 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2263 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2264 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Richard Smith4f902c72016-03-08 00:32:55 +00002265 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2266 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002267 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002268 }
2269
John McCall460ce582015-10-22 18:38:17 +00002270 if (S.getLangOpts().ObjCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002271 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002272 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002273
Richard Trieu2f024f42013-12-21 02:33:43 +00002274
2275 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002276 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2277 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002278 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2279 checkRecursiveFunction(S, FD, Body, AC);
2280 }
2281 }
2282
Erich Keane89fe9c22017-06-23 20:22:19 +00002283 // Check for throw out of non-throwing function.
2284 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2285 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2286 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2287 checkThrowInNonThrowingFunc(S, FD, AC);
2288
Richard Trieue9fa2662014-04-15 00:57:50 +00002289 // If none of the previous checks caused a CFG build, trigger one here
2290 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002291 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002292 D->getLocStart())) {
2293 AC.getCFG();
2294 }
2295
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002296 // Collect statistics about the CFG if it was built.
2297 if (S.CollectStats && AC.isCFGBuilt()) {
2298 ++NumFunctionsAnalyzed;
2299 if (CFG *cfg = AC.getCFG()) {
2300 // If we successfully built a CFG for this context, record some more
2301 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002302 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002303 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002304 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002305 } else {
2306 ++NumFunctionsWithBadCFGs;
2307 }
2308 }
2309}
2310
2311void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2312 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2313
2314 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2315 unsigned AvgCFGBlocksPerFunction =
2316 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2317 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2318 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2319 << " " << NumCFGBlocks << " CFG blocks built.\n"
2320 << " " << AvgCFGBlocksPerFunction
2321 << " average CFG blocks per function.\n"
2322 << " " << MaxCFGBlocksPerFunction
2323 << " max CFG blocks per function.\n";
2324
2325 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2326 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2327 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2328 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2329 llvm::errs() << NumUninitAnalysisFunctions
2330 << " functions analyzed for uninitialiazed variables\n"
2331 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2332 << " " << AvgUninitVariablesPerFunction
2333 << " average variables per function.\n"
2334 << " " << MaxUninitAnalysisVariablesPerFunction
2335 << " max variables per function.\n"
2336 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2337 << " " << AvgUninitBlockVisitsPerFunction
2338 << " average block visits per function.\n"
2339 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2340 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002341}