blob: 36030b99a30bf0b51ccba10e1dafb07ad9d17f9d [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"
Ted Kremenek918fe842010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#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"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
Alexander Kornienkoe61e5622012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenek918fe842010-03-20 21:06:02 +000055
56using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Unreachable code analysis.
60//===----------------------------------------------------------------------===//
61
62namespace {
63 class UnreachableCodeHandler : public reachable_code::Callback {
64 Sema &S;
65 public:
66 UnreachableCodeHandler(Sema &s) : S(s) {}
67
Ted Kremenek1a8641c2014-03-15 01:26:32 +000068 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000069 SourceLocation L,
70 SourceRange SilenceableCondVal,
71 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000072 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000073 unsigned diag = diag::warn_unreachable;
74 switch (UK) {
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
77 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000078 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000079 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000080 break;
Ted Kremenek14210372014-03-21 06:02:36 +000081 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
83 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 case reachable_code::UK_Other:
85 break;
86 }
87
88 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000089
90 SourceLocation Open = SilenceableCondVal.getBegin();
91 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000092 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000094 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
98 }
99 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000100 }
101 };
102}
103
104/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000105static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000106 // As a heuristic prune all diagnostics not in the main file. Currently
107 // the majority of warnings in headers are false positives. These
108 // are largely caused by configuration state, e.g. preprocessor
109 // defined code, etc.
110 //
111 // Note that this is also a performance optimization. Analyzing
112 // headers many times can be expensive.
113 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
114 return;
115
Ted Kremenek918fe842010-03-20 21:06:02 +0000116 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000118}
119
Benjamin Kramer3a002252015-02-16 16:53:12 +0000120namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000121/// \brief Warn on logical operator errors in CFGBuilder
122class LogicalErrorHandler : public CFGCallback {
123 Sema &S;
124
125public:
126 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
127
128 static bool HasMacroID(const Expr *E) {
129 if (E->getExprLoc().isMacroID())
130 return true;
131
132 // Recurse to children.
133 for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
134 if (*SubStmts)
135 if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
136 if (HasMacroID(SubExpr))
137 return true;
138
139 return false;
140 }
141
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000142 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000143 if (HasMacroID(B))
144 return;
145
146 SourceRange DiagRange = B->getSourceRange();
147 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
148 << DiagRange << isAlwaysTrue;
149 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000150
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000151 void compareBitwiseEquality(const BinaryOperator *B,
152 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000153 if (HasMacroID(B))
154 return;
155
156 SourceRange DiagRange = B->getSourceRange();
157 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
158 << DiagRange << isAlwaysTrue;
159 }
Richard Trieuf935b562014-04-05 05:17:01 +0000160};
Benjamin Kramer3a002252015-02-16 16:53:12 +0000161} // namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000162
Ted Kremenek918fe842010-03-20 21:06:02 +0000163//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000164// Check for infinite self-recursion in functions
165//===----------------------------------------------------------------------===//
166
167// All blocks are in one of three states. States are ordered so that blocks
168// can only move to higher states.
169enum RecursiveState {
170 FoundNoPath,
171 FoundPath,
172 FoundPathWithNoRecursiveCall
173};
174
175static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
176 CFGBlock &Block, unsigned ExitID,
177 llvm::SmallVectorImpl<RecursiveState> &States,
178 RecursiveState State) {
179 unsigned ID = Block.getBlockID();
180
181 // A block's state can only move to a higher state.
182 if (States[ID] >= State)
183 return;
184
185 States[ID] = State;
186
187 // Found a path to the exit node without a recursive call.
188 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
189 return;
190
191 if (State == FoundPathWithNoRecursiveCall) {
192 // If the current state is FoundPathWithNoRecursiveCall, the successors
193 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
194 // which, process all the Stmt's in this block to find any recursive calls.
Aaron Ballmane5195222014-05-15 20:50:47 +0000195 for (const auto &B : Block) {
196 if (B.getKind() != CFGElement::Statement)
Richard Trieu2f024f42013-12-21 02:33:43 +0000197 continue;
198
Aaron Ballmane5195222014-05-15 20:50:47 +0000199 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
Richard Trieu2f024f42013-12-21 02:33:43 +0000200 if (CE && CE->getCalleeDecl() &&
201 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000202
203 // Skip function calls which are qualified with a templated class.
204 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
205 CE->getCallee()->IgnoreParenImpCasts())) {
206 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
207 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
208 isa<TemplateSpecializationType>(NNS->getAsType())) {
209 continue;
210 }
211 }
212 }
213
Richard Trieu2f024f42013-12-21 02:33:43 +0000214 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
215 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
216 !MCE->getMethodDecl()->isVirtual()) {
217 State = FoundPath;
218 break;
219 }
220 } else {
221 State = FoundPath;
222 break;
223 }
224 }
225 }
226 }
227
228 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
229 I != E; ++I)
230 if (*I)
231 checkForFunctionCall(S, FD, **I, ExitID, States, State);
232}
233
234static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
235 const Stmt *Body,
236 AnalysisDeclContext &AC) {
237 FD = FD->getCanonicalDecl();
238
239 // Only run on non-templated functions and non-templated members of
240 // templated classes.
241 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
242 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
243 return;
244
245 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000246 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000247
248 // If the exit block is unreachable, skip processing the function.
249 if (cfg->getExit().pred_empty())
250 return;
251
252 // Mark all nodes as FoundNoPath, then begin processing the entry block.
253 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
254 FoundNoPath);
255 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
256 states, FoundPathWithNoRecursiveCall);
257
258 // Check that the exit block is reachable. This prevents triggering the
259 // warning on functions that do not terminate.
260 if (states[cfg->getExit().getBlockID()] == FoundPath)
261 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
262}
263
264//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000265// Check for missing return value.
266//===----------------------------------------------------------------------===//
267
John McCall5c6ec8c2010-05-16 09:34:11 +0000268enum ControlFlowKind {
269 UnknownFallThrough,
270 NeverFallThrough,
271 MaybeFallThrough,
272 AlwaysFallThrough,
273 NeverFallThroughOrReturn
274};
Ted Kremenek918fe842010-03-20 21:06:02 +0000275
276/// CheckFallThrough - Check that we don't fall off the end of a
277/// Statement that should return a value.
278///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000279/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
280/// MaybeFallThrough iff we might or might not fall off the end,
281/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
282/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000283/// statement but we may return. We assume that functions not marked noreturn
284/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000285static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000286 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000287 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000288
289 // The CFG leaves in dead things, and we don't want the dead code paths to
290 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000291 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000292 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000293 live);
294
295 bool AddEHEdges = AC.getAddEHEdges();
296 if (!AddEHEdges && count != cfg->getNumBlockIDs())
297 // When there are things remaining dead, and we didn't add EH edges
298 // from CallExprs to the catch clauses, we have to go back and
299 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000300 for (const auto *B : *cfg) {
301 if (!live[B->getBlockID()]) {
302 if (B->pred_begin() == B->pred_end()) {
303 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000304 // When not adding EH edges from calls, catch clauses
305 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000306 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000307 continue;
308 }
309 }
310 }
311
312 // Now we know what is live, we check the live precessors of the exit block
313 // and look for fall through paths, being careful to ignore normal returns,
314 // and exceptional paths.
315 bool HasLiveReturn = false;
316 bool HasFakeEdge = false;
317 bool HasPlainEdge = false;
318 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000319
320 // Ignore default cases that aren't likely to be reachable because all
321 // enums in a switch(X) have explicit case statements.
322 CFGBlock::FilterOptions FO;
323 FO.IgnoreDefaultsWithCoveredEnums = 1;
324
325 for (CFGBlock::filtered_pred_iterator
326 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
327 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000328 if (!live[B.getBlockID()])
329 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000330
Chandler Carruth03faf782011-09-13 09:53:58 +0000331 // Skip blocks which contain an element marked as no-return. They don't
332 // represent actually viable edges into the exit block, so mark them as
333 // abnormal.
334 if (B.hasNoReturnElement()) {
335 HasAbnormalEdge = true;
336 continue;
337 }
338
Ted Kremenek5d068492011-01-26 04:49:52 +0000339 // Destructors can appear after the 'return' in the CFG. This is
340 // normal. We need to look pass the destructors for the return
341 // statement (if it exists).
342 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000343
Chandler Carruth03faf782011-09-13 09:53:58 +0000344 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000345 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000346 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000347
Ted Kremenek5d068492011-01-26 04:49:52 +0000348 // No more CFGElements in the block?
349 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000350 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
351 HasAbnormalEdge = true;
352 continue;
353 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000354 // A labeled empty statement, or the entry block...
355 HasPlainEdge = true;
356 continue;
357 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000358
David Blaikie2a01f5d2013-02-21 20:58:29 +0000359 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000360 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000361 if (isa<ReturnStmt>(S)) {
362 HasLiveReturn = true;
363 continue;
364 }
365 if (isa<ObjCAtThrowStmt>(S)) {
366 HasFakeEdge = true;
367 continue;
368 }
369 if (isa<CXXThrowExpr>(S)) {
370 HasFakeEdge = true;
371 continue;
372 }
Chad Rosier32503022012-06-11 20:47:18 +0000373 if (isa<MSAsmStmt>(S)) {
374 // TODO: Verify this is correct.
375 HasFakeEdge = true;
376 HasLiveReturn = true;
377 continue;
378 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000379 if (isa<CXXTryStmt>(S)) {
380 HasAbnormalEdge = true;
381 continue;
382 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000383 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
384 == B.succ_end()) {
385 HasAbnormalEdge = true;
386 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000387 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000388
389 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000390 }
391 if (!HasPlainEdge) {
392 if (HasLiveReturn)
393 return NeverFallThrough;
394 return NeverFallThroughOrReturn;
395 }
396 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
397 return MaybeFallThrough;
398 // This says AlwaysFallThrough for calls to functions that are not marked
399 // noreturn, that don't return. If people would like this warning to be more
400 // accurate, such functions should be marked as noreturn.
401 return AlwaysFallThrough;
402}
403
Dan Gohman28ade552010-07-26 21:25:24 +0000404namespace {
405
Ted Kremenek918fe842010-03-20 21:06:02 +0000406struct CheckFallThroughDiagnostics {
407 unsigned diag_MaybeFallThrough_HasNoReturn;
408 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
409 unsigned diag_AlwaysFallThrough_HasNoReturn;
410 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
411 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000412 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000413 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000414
Douglas Gregor24f27692010-04-16 23:28:44 +0000415 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000416 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000417 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000418 D.diag_MaybeFallThrough_HasNoReturn =
419 diag::warn_falloff_noreturn_function;
420 D.diag_MaybeFallThrough_ReturnsNonVoid =
421 diag::warn_maybe_falloff_nonvoid_function;
422 D.diag_AlwaysFallThrough_HasNoReturn =
423 diag::warn_falloff_noreturn_function;
424 D.diag_AlwaysFallThrough_ReturnsNonVoid =
425 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000426
427 // Don't suggest that virtual functions be marked "noreturn", since they
428 // might be overridden by non-noreturn functions.
429 bool isVirtualMethod = false;
430 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
431 isVirtualMethod = Method->isVirtual();
432
Douglas Gregor0de57202011-10-10 18:15:57 +0000433 // Don't suggest that template instantiations be marked "noreturn"
434 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000435 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
436 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000437
438 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000439 D.diag_NeverFallThroughOrReturn =
440 diag::warn_suggest_noreturn_function;
441 else
442 D.diag_NeverFallThroughOrReturn = 0;
443
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000444 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000445 return D;
446 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000447
Ted Kremenek918fe842010-03-20 21:06:02 +0000448 static CheckFallThroughDiagnostics MakeForBlock() {
449 CheckFallThroughDiagnostics D;
450 D.diag_MaybeFallThrough_HasNoReturn =
451 diag::err_noreturn_block_has_return_expr;
452 D.diag_MaybeFallThrough_ReturnsNonVoid =
453 diag::err_maybe_falloff_nonvoid_block;
454 D.diag_AlwaysFallThrough_HasNoReturn =
455 diag::err_noreturn_block_has_return_expr;
456 D.diag_AlwaysFallThrough_ReturnsNonVoid =
457 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000458 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000459 D.funMode = Block;
460 return D;
461 }
462
463 static CheckFallThroughDiagnostics MakeForLambda() {
464 CheckFallThroughDiagnostics D;
465 D.diag_MaybeFallThrough_HasNoReturn =
466 diag::err_noreturn_lambda_has_return_expr;
467 D.diag_MaybeFallThrough_ReturnsNonVoid =
468 diag::warn_maybe_falloff_nonvoid_lambda;
469 D.diag_AlwaysFallThrough_HasNoReturn =
470 diag::err_noreturn_lambda_has_return_expr;
471 D.diag_AlwaysFallThrough_ReturnsNonVoid =
472 diag::warn_falloff_nonvoid_lambda;
473 D.diag_NeverFallThroughOrReturn = 0;
474 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000475 return D;
476 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000477
David Blaikie9c902b52011-09-25 23:23:43 +0000478 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000479 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000480 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000481 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000482 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
483 FuncLoc)) &&
484 (!HasNoReturn ||
485 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
486 FuncLoc)) &&
487 (!ReturnsVoid ||
488 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000489 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000490
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000491 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000492 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000493 }
494};
495
Dan Gohman28ade552010-07-26 21:25:24 +0000496}
497
Ted Kremenek918fe842010-03-20 21:06:02 +0000498/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
499/// function that should return a value. Check that we don't fall off the end
500/// of a noreturn function. We assume that functions and blocks not marked
501/// noreturn will return.
502static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000503 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000504 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000505 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000506
507 bool ReturnsVoid = false;
508 bool HasNoReturn = false;
509
510 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000511 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000512 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000513 }
514 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000515 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000516 HasNoReturn = MD->hasAttr<NoReturnAttr>();
517 }
518 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000519 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000520 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000521 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000522 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000523 ReturnsVoid = true;
524 if (FT->getNoReturnAttr())
525 HasNoReturn = true;
526 }
527 }
528
David Blaikie9c902b52011-09-25 23:23:43 +0000529 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000530
531 // Short circuit for compilation speed.
532 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
533 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000534
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000535 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
536 // Either in a function body compound statement, or a function-try-block.
537 switch (CheckFallThrough(AC)) {
538 case UnknownFallThrough:
539 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000540
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000541 case MaybeFallThrough:
542 if (HasNoReturn)
543 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
544 else if (!ReturnsVoid)
545 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
546 break;
547 case AlwaysFallThrough:
548 if (HasNoReturn)
549 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
550 else if (!ReturnsVoid)
551 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
552 break;
553 case NeverFallThroughOrReturn:
554 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
555 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
556 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
557 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
558 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
559 } else {
560 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000561 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000562 }
563 break;
564 case NeverFallThrough:
565 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000566 }
567}
568
569//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000570// -Wuninitialized
571//===----------------------------------------------------------------------===//
572
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000573namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000574/// ContainsReference - A visitor class to search for references to
575/// a particular declaration (the needle) within any evaluated component of an
576/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000577class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000578 bool FoundReference;
579 const DeclRefExpr *Needle;
580
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000581public:
Scott Douglass503fc392015-06-10 13:53:15 +0000582 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000583
Scott Douglass503fc392015-06-10 13:53:15 +0000584 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
585 : Inherited(Context), FoundReference(false), Needle(Needle) {}
586
587 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000588 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000589 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000590 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000591
Scott Douglass503fc392015-06-10 13:53:15 +0000592 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000593 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000594
Scott Douglass503fc392015-06-10 13:53:15 +0000595 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000596 if (E == Needle)
597 FoundReference = true;
598 else
Scott Douglass503fc392015-06-10 13:53:15 +0000599 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000600 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000601
602 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000603};
604}
605
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000606static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000607 QualType VariableTy = VD->getType().getCanonicalType();
608 if (VariableTy->isBlockPointerType() &&
609 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000610 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
611 << VD->getDeclName()
612 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000613 return true;
614 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000615
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000616 // Don't issue a fixit if there is already an initializer.
617 if (VD->getInit())
618 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000619
620 // Don't suggest a fixit inside macros.
621 if (VD->getLocEnd().isMacroID())
622 return false;
623
Alp Tokerb6cc5922014-05-03 03:45:55 +0000624 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000625
626 // Suggest possible initialization (if any).
627 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
628 if (Init.empty())
629 return false;
630
Richard Smith8d06f422012-01-12 23:53:29 +0000631 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
632 << FixItHint::CreateInsertion(Loc, Init);
633 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000634}
635
Richard Smith1bb8edb82012-05-26 06:20:46 +0000636/// Create a fixit to remove an if-like statement, on the assumption that its
637/// condition is CondVal.
638static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
639 const Stmt *Else, bool CondVal,
640 FixItHint &Fixit1, FixItHint &Fixit2) {
641 if (CondVal) {
642 // If condition is always true, remove all but the 'then'.
643 Fixit1 = FixItHint::CreateRemoval(
644 CharSourceRange::getCharRange(If->getLocStart(),
645 Then->getLocStart()));
646 if (Else) {
647 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
648 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
649 Fixit2 = FixItHint::CreateRemoval(
650 SourceRange(ElseKwLoc, Else->getLocEnd()));
651 }
652 } else {
653 // If condition is always false, remove all but the 'else'.
654 if (Else)
655 Fixit1 = FixItHint::CreateRemoval(
656 CharSourceRange::getCharRange(If->getLocStart(),
657 Else->getLocStart()));
658 else
659 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
660 }
661}
662
663/// DiagUninitUse -- Helper function to produce a diagnostic for an
664/// uninitialized use of a variable.
665static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
666 bool IsCapturedByBlock) {
667 bool Diagnosed = false;
668
Richard Smithba8071e2013-09-12 18:49:10 +0000669 switch (Use.getKind()) {
670 case UninitUse::Always:
671 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
672 << VD->getDeclName() << IsCapturedByBlock
673 << Use.getUser()->getSourceRange();
674 return;
675
676 case UninitUse::AfterDecl:
677 case UninitUse::AfterCall:
678 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
679 << VD->getDeclName() << IsCapturedByBlock
680 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
681 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
682 << VD->getSourceRange();
683 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
684 << IsCapturedByBlock << Use.getUser()->getSourceRange();
685 return;
686
687 case UninitUse::Maybe:
688 case UninitUse::Sometimes:
689 // Carry on to report sometimes-uninitialized branches, if possible,
690 // or a 'may be used uninitialized' diagnostic otherwise.
691 break;
692 }
693
Richard Smith1bb8edb82012-05-26 06:20:46 +0000694 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000695 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
696 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000697 assert(Use.getKind() == UninitUse::Sometimes);
698
699 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000700 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000701
702 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000703 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000704 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000705 SourceRange Range;
706
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000707 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000708 // For all binary terminators, branch 0 is taken if the condition is true,
709 // and branch 1 is taken if the condition is false.
710 int RemoveDiagKind = -1;
711 const char *FixitStr =
712 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
713 : (I->Output ? "1" : "0");
714 FixItHint Fixit1, Fixit2;
715
Richard Smithba8071e2013-09-12 18:49:10 +0000716 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000717 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000718 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000719 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000720 continue;
721
722 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000723 case Stmt::IfStmtClass: {
724 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000725 DiagKind = 0;
726 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000727 Range = IS->getCond()->getSourceRange();
728 RemoveDiagKind = 0;
729 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
730 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000731 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000732 }
733 case Stmt::ConditionalOperatorClass: {
734 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000735 DiagKind = 0;
736 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000737 Range = CO->getCond()->getSourceRange();
738 RemoveDiagKind = 0;
739 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
740 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000741 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000742 }
Richard Smith4323bf82012-05-25 02:17:09 +0000743 case Stmt::BinaryOperatorClass: {
744 const BinaryOperator *BO = cast<BinaryOperator>(Term);
745 if (!BO->isLogicalOp())
746 continue;
747 DiagKind = 0;
748 Str = BO->getOpcodeStr();
749 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000750 RemoveDiagKind = 0;
751 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
752 (BO->getOpcode() == BO_LOr && !I->Output))
753 // true && y -> y, false || y -> y.
754 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
755 BO->getOperatorLoc()));
756 else
757 // false && y -> false, true || y -> true.
758 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000759 break;
760 }
761
762 // "loop is entered / loop is exited".
763 case Stmt::WhileStmtClass:
764 DiagKind = 1;
765 Str = "while";
766 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000767 RemoveDiagKind = 1;
768 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000769 break;
770 case Stmt::ForStmtClass:
771 DiagKind = 1;
772 Str = "for";
773 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000774 RemoveDiagKind = 1;
775 if (I->Output)
776 Fixit1 = FixItHint::CreateRemoval(Range);
777 else
778 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000779 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000780 case Stmt::CXXForRangeStmtClass:
781 if (I->Output == 1) {
782 // The use occurs if a range-based for loop's body never executes.
783 // That may be impossible, and there's no syntactic fix for this,
784 // so treat it as a 'may be uninitialized' case.
785 continue;
786 }
787 DiagKind = 1;
788 Str = "for";
789 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
790 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000791
792 // "condition is true / loop is exited".
793 case Stmt::DoStmtClass:
794 DiagKind = 2;
795 Str = "do";
796 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000797 RemoveDiagKind = 1;
798 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000799 break;
800
801 // "switch case is taken".
802 case Stmt::CaseStmtClass:
803 DiagKind = 3;
804 Str = "case";
805 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
806 break;
807 case Stmt::DefaultStmtClass:
808 DiagKind = 3;
809 Str = "default";
810 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
811 break;
812 }
813
Richard Smith1bb8edb82012-05-26 06:20:46 +0000814 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
815 << VD->getDeclName() << IsCapturedByBlock << DiagKind
816 << Str << I->Output << Range;
817 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
818 << IsCapturedByBlock << User->getSourceRange();
819 if (RemoveDiagKind != -1)
820 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
821 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
822
823 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000824 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000825
826 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000827 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000828 << VD->getDeclName() << IsCapturedByBlock
829 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000830}
831
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000832/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
833/// uninitialized variable. This manages the different forms of diagnostic
834/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000835/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000836/// false.
837static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000838 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000839 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000840
Richard Smith4323bf82012-05-25 02:17:09 +0000841 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000842 // Inspect the initializer of the variable declaration which is
843 // being referenced prior to its initialization. We emit
844 // specialized diagnostics for self-initialization, and we
845 // specifically avoid warning about self references which take the
846 // form of:
847 //
848 // int x = x;
849 //
850 // This is used to indicate to GCC that 'x' is intentionally left
851 // uninitialized. Proven code paths which access 'x' in
852 // an uninitialized state after this will still warn.
853 if (const Expr *Initializer = VD->getInit()) {
854 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
855 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000856
Richard Trieu43a2fc72012-05-09 21:08:22 +0000857 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +0000858 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +0000859 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000860 S.Diag(DRE->getLocStart(),
861 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000862 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
863 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000864 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000865 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000866
Richard Smith1bb8edb82012-05-26 06:20:46 +0000867 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000868 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000869 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000870 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
871 S.Diag(BE->getLocStart(),
872 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000873 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000874 else
875 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000876 }
877
878 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000879 // the initializer of that declaration & we didn't already suggest
880 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000881 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000882 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
883 << VD->getDeclName();
884
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000885 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000886}
887
Richard Smith84837d52012-05-03 18:27:39 +0000888namespace {
889 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
890 public:
891 FallthroughMapper(Sema &S)
892 : FoundSwitchStatements(false),
893 S(S) {
894 }
895
896 bool foundSwitchStatements() const { return FoundSwitchStatements; }
897
898 void markFallthroughVisited(const AttributedStmt *Stmt) {
899 bool Found = FallthroughStmts.erase(Stmt);
900 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000901 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000902 }
903
904 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
905
906 const AttrStmts &getFallthroughStmts() const {
907 return FallthroughStmts;
908 }
909
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000910 void fillReachableBlocks(CFG *Cfg) {
911 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
912 std::deque<const CFGBlock *> BlockQueue;
913
914 ReachableBlocks.insert(&Cfg->getEntry());
915 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000916 // Mark all case blocks reachable to avoid problems with switching on
917 // constants, covered enums, etc.
918 // These blocks can contain fall-through annotations, and we don't want to
919 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +0000920 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000921 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +0000922 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000923 BlockQueue.push_back(B);
924 }
925
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000926 while (!BlockQueue.empty()) {
927 const CFGBlock *P = BlockQueue.front();
928 BlockQueue.pop_front();
929 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
930 E = P->succ_end();
931 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +0000932 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000933 BlockQueue.push_back(*I);
934 }
935 }
936 }
937
Richard Smith84837d52012-05-03 18:27:39 +0000938 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000939 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
940
Richard Smith84837d52012-05-03 18:27:39 +0000941 int UnannotatedCnt = 0;
942 AnnotatedCnt = 0;
943
Aaron Ballmane5195222014-05-15 20:50:47 +0000944 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +0000945 while (!BlockQueue.empty()) {
946 const CFGBlock *P = BlockQueue.front();
947 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000948 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000949
950 const Stmt *Term = P->getTerminator();
951 if (Term && isa<SwitchStmt>(Term))
952 continue; // Switch statement, good.
953
954 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
955 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
956 continue; // Previous case label has no statements, good.
957
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000958 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
959 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
960 continue; // Case label is preceded with a normal label, good.
961
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000962 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000963 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
964 ElemEnd = P->rend();
965 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000966 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
967 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000968 S.Diag(AS->getLocStart(),
969 diag::warn_fallthrough_attr_unreachable);
970 markFallthroughVisited(AS);
971 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000972 break;
Richard Smith84837d52012-05-03 18:27:39 +0000973 }
974 // Don't care about other unreachable statements.
975 }
976 }
977 // If there are no unreachable statements, this may be a special
978 // case in CFG:
979 // case X: {
980 // A a; // A has a destructor.
981 // break;
982 // }
983 // // <<<< This place is represented by a 'hanging' CFG block.
984 // case Y:
985 continue;
986 }
987
988 const Stmt *LastStmt = getLastStmt(*P);
989 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
990 markFallthroughVisited(AS);
991 ++AnnotatedCnt;
992 continue; // Fallthrough annotation, good.
993 }
994
995 if (!LastStmt) { // This block contains no executable statements.
996 // Traverse its predecessors.
997 std::copy(P->pred_begin(), P->pred_end(),
998 std::back_inserter(BlockQueue));
999 continue;
1000 }
1001
1002 ++UnannotatedCnt;
1003 }
1004 return !!UnannotatedCnt;
1005 }
1006
1007 // RecursiveASTVisitor setup.
1008 bool shouldWalkTypesOfTypeLocs() const { return false; }
1009
1010 bool VisitAttributedStmt(AttributedStmt *S) {
1011 if (asFallThroughAttr(S))
1012 FallthroughStmts.insert(S);
1013 return true;
1014 }
1015
1016 bool VisitSwitchStmt(SwitchStmt *S) {
1017 FoundSwitchStatements = true;
1018 return true;
1019 }
1020
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001021 // We don't want to traverse local type declarations. We analyze their
1022 // methods separately.
1023 bool TraverseDecl(Decl *D) { return true; }
1024
Alexander Kornienkobf911642014-06-24 15:28:21 +00001025 // We analyze lambda bodies separately. Skip them here.
1026 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1027
Richard Smith84837d52012-05-03 18:27:39 +00001028 private:
1029
1030 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1031 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1032 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1033 return AS;
1034 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001035 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001036 }
1037
1038 static const Stmt *getLastStmt(const CFGBlock &B) {
1039 if (const Stmt *Term = B.getTerminator())
1040 return Term;
1041 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1042 ElemEnd = B.rend();
1043 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001044 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1045 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001046 }
1047 // Workaround to detect a statement thrown out by CFGBuilder:
1048 // case X: {} case Y:
1049 // case X: ; case Y:
1050 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1051 if (!isa<SwitchCase>(SW->getSubStmt()))
1052 return SW->getSubStmt();
1053
Craig Topperc3ec1492014-05-26 06:22:03 +00001054 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001055 }
1056
1057 bool FoundSwitchStatements;
1058 AttrStmts FallthroughStmts;
1059 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001060 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001061 };
1062}
1063
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001064static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001065 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001066 // Only perform this analysis when using C++11. There is no good workflow
1067 // for this warning when not using C++11. There is no good way to silence
1068 // the warning (no attribute is available) unless we are using C++11's support
1069 // for generalized attributes. Once could use pragmas to silence the warning,
1070 // but as a general solution that is gross and not in the spirit of this
1071 // warning.
1072 //
1073 // NOTE: This an intermediate solution. There are on-going discussions on
1074 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001075 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001076 return;
1077
Richard Smith84837d52012-05-03 18:27:39 +00001078 FallthroughMapper FM(S);
1079 FM.TraverseStmt(AC.getBody());
1080
1081 if (!FM.foundSwitchStatements())
1082 return;
1083
Alexis Hunt2178f142012-06-15 21:22:05 +00001084 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001085 return;
1086
Richard Smith84837d52012-05-03 18:27:39 +00001087 CFG *Cfg = AC.getCFG();
1088
1089 if (!Cfg)
1090 return;
1091
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001092 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001093
1094 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001095 const CFGBlock *B = *I;
1096 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001097
1098 if (!Label || !isa<SwitchCase>(Label))
1099 continue;
1100
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001101 int AnnotatedCnt;
1102
Alexander Kornienko55488792013-01-25 15:49:34 +00001103 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001104 continue;
1105
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001106 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001107 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1108 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001109
1110 if (!AnnotatedCnt) {
1111 SourceLocation L = Label->getLocStart();
1112 if (L.isMacroID())
1113 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001114 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001115 const Stmt *Term = B->getTerminator();
1116 // Skip empty cases.
1117 while (B->empty() && !Term && B->succ_size() == 1) {
1118 B = *B->succ_begin();
1119 Term = B->getTerminator();
1120 }
1121 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001122 Preprocessor &PP = S.getPreprocessor();
1123 TokenValue Tokens[] = {
1124 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1125 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1126 tok::r_square, tok::r_square
1127 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001128 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1129 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1130 if (!MacroName.empty())
1131 AnnotationSpelling = MacroName;
1132 SmallString<64> TextToInsert(AnnotationSpelling);
1133 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001134 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001135 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001136 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001137 }
Richard Smith84837d52012-05-03 18:27:39 +00001138 }
1139 S.Diag(L, diag::note_insert_break_fixit) <<
1140 FixItHint::CreateInsertion(L, "break; ");
1141 }
1142 }
1143
Aaron Ballmane5195222014-05-15 20:50:47 +00001144 for (const auto *F : FM.getFallthroughStmts())
1145 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001146}
1147
Jordan Rose25c0ea82012-10-29 17:46:47 +00001148static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1149 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001150 assert(S);
1151
1152 do {
1153 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001154 case Stmt::ForStmtClass:
1155 case Stmt::WhileStmtClass:
1156 case Stmt::CXXForRangeStmtClass:
1157 case Stmt::ObjCForCollectionStmtClass:
1158 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001159 case Stmt::DoStmtClass: {
1160 const Expr *Cond = cast<DoStmt>(S)->getCond();
1161 llvm::APSInt Val;
1162 if (!Cond->EvaluateAsInt(Val, Ctx))
1163 return true;
1164 return Val.getBoolValue();
1165 }
Jordan Rose76831c62012-10-11 16:10:19 +00001166 default:
1167 break;
1168 }
1169 } while ((S = PM.getParent(S)));
1170
1171 return false;
1172}
1173
Jordan Rosed3934582012-09-28 22:21:30 +00001174
1175static void diagnoseRepeatedUseOfWeak(Sema &S,
1176 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001177 const Decl *D,
1178 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001179 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1180 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1181 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001182 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1183 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001184
Jordan Rose25c0ea82012-10-29 17:46:47 +00001185 ASTContext &Ctx = S.getASTContext();
1186
Jordan Rosed3934582012-09-28 22:21:30 +00001187 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1188
1189 // Extract all weak objects that are referenced more than once.
1190 SmallVector<StmtUsesPair, 8> UsesByStmt;
1191 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1192 I != E; ++I) {
1193 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001194
1195 // Find the first read of the weak object.
1196 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1197 for ( ; UI != UE; ++UI) {
1198 if (UI->isUnsafe())
1199 break;
1200 }
1201
1202 // If there were only writes to this object, don't warn.
1203 if (UI == UE)
1204 continue;
1205
Jordan Rose76831c62012-10-11 16:10:19 +00001206 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001207 // read is not within a loop, don't warn. Additionally, don't warn in a
1208 // loop if the base object is a local variable -- local variables are often
1209 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001210 if (UI == Uses.begin()) {
1211 WeakUseVector::const_iterator UI2 = UI;
1212 for (++UI2; UI2 != UE; ++UI2)
1213 if (UI2->isUnsafe())
1214 break;
1215
Jordan Rose25c0ea82012-10-29 17:46:47 +00001216 if (UI2 == UE) {
1217 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001218 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001219
1220 const WeakObjectProfileTy &Profile = I->first;
1221 if (!Profile.isExactProfile())
1222 continue;
1223
1224 const NamedDecl *Base = Profile.getBase();
1225 if (!Base)
1226 Base = Profile.getProperty();
1227 assert(Base && "A profile always has a base or property.");
1228
1229 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1230 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1231 continue;
1232 }
Jordan Rose76831c62012-10-11 16:10:19 +00001233 }
1234
Jordan Rosed3934582012-09-28 22:21:30 +00001235 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1236 }
1237
1238 if (UsesByStmt.empty())
1239 return;
1240
1241 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001242 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001243 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001244 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1245 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1246 RHS.first->getLocStart());
1247 });
Jordan Rosed3934582012-09-28 22:21:30 +00001248
1249 // Classify the current code body for better warning text.
1250 // This enum should stay in sync with the cases in
1251 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1252 // FIXME: Should we use a common classification enum and the same set of
1253 // possibilities all throughout Sema?
1254 enum {
1255 Function,
1256 Method,
1257 Block,
1258 Lambda
1259 } FunctionKind;
1260
1261 if (isa<sema::BlockScopeInfo>(CurFn))
1262 FunctionKind = Block;
1263 else if (isa<sema::LambdaScopeInfo>(CurFn))
1264 FunctionKind = Lambda;
1265 else if (isa<ObjCMethodDecl>(D))
1266 FunctionKind = Method;
1267 else
1268 FunctionKind = Function;
1269
1270 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001271 for (const auto &P : UsesByStmt) {
1272 const Stmt *FirstRead = P.first;
1273 const WeakObjectProfileTy &Key = P.second->first;
1274 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001275
Jordan Rose657b5f42012-09-28 22:21:35 +00001276 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1277 // may not contain enough information to determine that these are different
1278 // properties. We can only be 100% sure of a repeated use in certain cases,
1279 // and we adjust the diagnostic kind accordingly so that the less certain
1280 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001281 unsigned DiagKind;
1282 if (Key.isExactProfile())
1283 DiagKind = diag::warn_arc_repeated_use_of_weak;
1284 else
1285 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1286
Jordan Rose657b5f42012-09-28 22:21:35 +00001287 // Classify the weak object being accessed for better warning text.
1288 // This enum should stay in sync with the cases in
1289 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1290 enum {
1291 Variable,
1292 Property,
1293 ImplicitProperty,
1294 Ivar
1295 } ObjectKind;
1296
1297 const NamedDecl *D = Key.getProperty();
1298 if (isa<VarDecl>(D))
1299 ObjectKind = Variable;
1300 else if (isa<ObjCPropertyDecl>(D))
1301 ObjectKind = Property;
1302 else if (isa<ObjCMethodDecl>(D))
1303 ObjectKind = ImplicitProperty;
1304 else if (isa<ObjCIvarDecl>(D))
1305 ObjectKind = Ivar;
1306 else
1307 llvm_unreachable("Unexpected weak object kind!");
1308
Jordan Rosed3934582012-09-28 22:21:30 +00001309 // Show the first time the object was read.
1310 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001311 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001312 << FirstRead->getSourceRange();
1313
1314 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001315 for (const auto &Use : Uses) {
1316 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001317 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001318 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001319 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001320 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001321 }
1322 }
1323}
1324
Jordan Rosed3934582012-09-28 22:21:30 +00001325namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001326class UninitValsDiagReporter : public UninitVariablesHandler {
1327 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001328 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001329 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001330 // Prefer using MapVector to DenseMap, so that iteration order will be
1331 // the same as insertion order. This is needed to obtain a deterministic
1332 // order of diagnostics when calling flushDiagnostics().
1333 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001334 UsesMap *uses;
1335
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001336public:
Craig Topperc3ec1492014-05-26 06:22:03 +00001337 UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001338 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001339
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001340 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001341 if (!uses)
1342 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001343
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001344 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001345 if (!V.getPointer())
1346 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001347
Ted Kremenek596fa162011-10-13 18:50:06 +00001348 return V;
1349 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001350
1351 void handleUseOfUninitVariable(const VarDecl *vd,
1352 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001353 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001354 }
1355
Craig Toppere14c0f82014-03-12 04:55:44 +00001356 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001357 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001358 }
1359
1360 void flushDiagnostics() {
1361 if (!uses)
1362 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001363
Aaron Ballmane5195222014-05-15 20:50:47 +00001364 for (const auto &P : *uses) {
1365 const VarDecl *vd = P.first;
1366 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001367
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001368 UsesVec *vec = V.getPointer();
1369 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001370
1371 // Specially handle the case where we have uses of an uninitialized
1372 // variable, but the root cause is an idiomatic self-init. We want
1373 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001374 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001375 DiagnoseUninitializedUse(S, vd,
1376 UninitUse(vd->getInit()->IgnoreParenCasts(),
1377 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001378 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001379 else {
1380 // Sort the uses by their SourceLocations. While not strictly
1381 // guaranteed to produce them in line/column order, this will provide
1382 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001383 std::sort(vec->begin(), vec->end(),
1384 [](const UninitUse &a, const UninitUse &b) {
1385 // Prefer a more confident report over a less confident one.
1386 if (a.getKind() != b.getKind())
1387 return a.getKind() > b.getKind();
1388 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1389 });
1390
Aaron Ballmane5195222014-05-15 20:50:47 +00001391 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001392 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001393 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001394
1395 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001396 // Skip further diagnostics for this variable. We try to warn only
1397 // on the first point at which a variable is used uninitialized.
1398 break;
1399 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001400 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001401
1402 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001403 delete vec;
1404 }
1405 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001406 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001407
1408private:
1409 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001410 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1411 return U.getKind() == UninitUse::Always ||
1412 U.getKind() == UninitUse::AfterCall ||
1413 U.getKind() == UninitUse::AfterDecl;
1414 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001415 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001416};
1417}
1418
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001419namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001420namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001421typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001422typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001423typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001424
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001425struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001426 SourceManager &SM;
1427 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001428
1429 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1430 // Although this call will be slow, this is only called when outputting
1431 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001432 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001433 }
1434};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001435}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001436
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001437//===----------------------------------------------------------------------===//
1438// -Wthread-safety
1439//===----------------------------------------------------------------------===//
1440namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001441namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001442namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001443class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001444 Sema &S;
1445 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001446 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001447
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001448 const FunctionDecl *CurrentFunction;
1449 bool Verbose;
1450
Aaron Ballman71291bc2014-08-15 12:38:17 +00001451 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001452 if (Verbose && CurrentFunction) {
1453 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001454 S.PDiag(diag::note_thread_warning_in_fun)
1455 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001456 return OptionalNotes(1, FNote);
1457 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001458 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001459 }
1460
Aaron Ballman71291bc2014-08-15 12:38:17 +00001461 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001462 OptionalNotes ONS(1, Note);
1463 if (Verbose && CurrentFunction) {
1464 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001465 S.PDiag(diag::note_thread_warning_in_fun)
1466 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001467 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001468 }
1469 return ONS;
1470 }
1471
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001472 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1473 const PartialDiagnosticAt &Note2) const {
1474 OptionalNotes ONS;
1475 ONS.push_back(Note1);
1476 ONS.push_back(Note2);
1477 if (Verbose && CurrentFunction) {
1478 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1479 S.PDiag(diag::note_thread_warning_in_fun)
1480 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001481 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001482 }
1483 return ONS;
1484 }
1485
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001486 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001487 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1488 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001489 // Gracefully handle rare cases when the analysis can't get a more
1490 // precise source location.
1491 if (!Loc.isValid())
1492 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001493 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001494 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001495 }
1496
1497 public:
Richard Smith92286672012-02-03 04:45:26 +00001498 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001499 : S(S), FunLocation(FL), FunEndLocation(FEL),
1500 CurrentFunction(nullptr), Verbose(false) {}
1501
1502 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001503
1504 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1505 /// We need to output diagnostics produced while iterating through
1506 /// the lockset in deterministic order, so this function orders diagnostics
1507 /// and outputs them.
1508 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001509 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001510 for (const auto &Diag : Warnings) {
1511 S.Diag(Diag.first.first, Diag.first.second);
1512 for (const auto &Note : Diag.second)
1513 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001514 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001515 }
1516
Aaron Ballmane0449042014-04-01 21:43:23 +00001517 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1518 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1519 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001520 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001521 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001522
Aaron Ballmane0449042014-04-01 21:43:23 +00001523 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1524 SourceLocation Loc) override {
1525 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001526 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001527
Aaron Ballmane0449042014-04-01 21:43:23 +00001528 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1529 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001530 SourceLocation Loc) override {
1531 if (Loc.isInvalid())
1532 Loc = FunLocation;
1533 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001534 << Kind << LockName << Received
1535 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001536 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001537 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001538
Aaron Ballmane0449042014-04-01 21:43:23 +00001539 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1540 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001541 }
1542
Aaron Ballmane0449042014-04-01 21:43:23 +00001543 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1544 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001545 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001546 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001547 unsigned DiagID = 0;
1548 switch (LEK) {
1549 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001550 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001551 break;
1552 case LEK_LockedSomeLoopIterations:
1553 DiagID = diag::warn_expecting_lock_held_on_loop;
1554 break;
1555 case LEK_LockedAtEndOfFunction:
1556 DiagID = diag::warn_no_unlock;
1557 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001558 case LEK_NotLockedAtEndOfFunction:
1559 DiagID = diag::warn_expecting_locked;
1560 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001561 }
Richard Smith92286672012-02-03 04:45:26 +00001562 if (LocEndOfScope.isInvalid())
1563 LocEndOfScope = FunEndLocation;
1564
Aaron Ballmane0449042014-04-01 21:43:23 +00001565 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1566 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001567 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001568 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1569 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001570 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001571 return;
1572 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001573 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001574 }
1575
Aaron Ballmane0449042014-04-01 21:43:23 +00001576 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1577 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001578 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001579 PartialDiagnosticAt Warning(Loc1,
1580 S.PDiag(diag::warn_lock_exclusive_and_shared)
1581 << Kind << LockName);
1582 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1583 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001584 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001585 }
1586
Aaron Ballmane0449042014-04-01 21:43:23 +00001587 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1588 ProtectedOperationKind POK, AccessKind AK,
1589 SourceLocation Loc) override {
1590 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1591 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001592 unsigned DiagID = POK == POK_VarAccess?
1593 diag::warn_variable_requires_any_lock:
1594 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001595 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001596 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001597 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001598 }
1599
Aaron Ballmane0449042014-04-01 21:43:23 +00001600 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1601 ProtectedOperationKind POK, Name LockName,
1602 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001603 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001604 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001605 if (PossibleMatch) {
1606 switch (POK) {
1607 case POK_VarAccess:
1608 DiagID = diag::warn_variable_requires_lock_precise;
1609 break;
1610 case POK_VarDereference:
1611 DiagID = diag::warn_var_deref_requires_lock_precise;
1612 break;
1613 case POK_FunctionCall:
1614 DiagID = diag::warn_fun_requires_lock_precise;
1615 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001616 case POK_PassByRef:
1617 DiagID = diag::warn_guarded_pass_by_reference;
1618 break;
1619 case POK_PtPassByRef:
1620 DiagID = diag::warn_pt_guarded_pass_by_reference;
1621 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001622 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001623 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1624 << D->getNameAsString()
1625 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001626 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001627 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001628 if (Verbose && POK == POK_VarAccess) {
1629 PartialDiagnosticAt VNote(D->getLocation(),
1630 S.PDiag(diag::note_guarded_by_declared_here)
1631 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001632 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001633 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001634 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001635 } else {
1636 switch (POK) {
1637 case POK_VarAccess:
1638 DiagID = diag::warn_variable_requires_lock;
1639 break;
1640 case POK_VarDereference:
1641 DiagID = diag::warn_var_deref_requires_lock;
1642 break;
1643 case POK_FunctionCall:
1644 DiagID = diag::warn_fun_requires_lock;
1645 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001646 case POK_PassByRef:
1647 DiagID = diag::warn_guarded_pass_by_reference;
1648 break;
1649 case POK_PtPassByRef:
1650 DiagID = diag::warn_pt_guarded_pass_by_reference;
1651 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001652 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001653 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1654 << D->getNameAsString()
1655 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001656 if (Verbose && POK == POK_VarAccess) {
1657 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001658 S.PDiag(diag::note_guarded_by_declared_here)
1659 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001660 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001661 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001662 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001663 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001664 }
1665
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001666 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1667 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001668 PartialDiagnosticAt Warning(Loc,
1669 S.PDiag(diag::warn_acquire_requires_negative_cap)
1670 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001671 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001672 }
1673
1674
Aaron Ballmane0449042014-04-01 21:43:23 +00001675 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001676 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001677 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1678 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001679 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001680 }
1681
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001682 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1683 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001684 PartialDiagnosticAt Warning(Loc,
1685 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001686 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001687 }
1688
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001689 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001690 PartialDiagnosticAt Warning(Loc,
1691 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001692 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001693 }
1694
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001695 void enterFunction(const FunctionDecl* FD) override {
1696 CurrentFunction = FD;
1697 }
1698
1699 void leaveFunction(const FunctionDecl* FD) override {
1700 CurrentFunction = 0;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001701 }
1702};
Benjamin Kramer539803c2015-03-19 14:23:45 +00001703} // namespace
1704} // namespace threadSafety
1705} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001706
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001707//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001708// -Wconsumed
1709//===----------------------------------------------------------------------===//
1710
1711namespace clang {
1712namespace consumed {
1713namespace {
1714class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1715
1716 Sema &S;
1717 DiagList Warnings;
1718
1719public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001720
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001721 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001722
1723 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001724 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001725 for (const auto &Diag : Warnings) {
1726 S.Diag(Diag.first.first, Diag.first.second);
1727 for (const auto &Note : Diag.second)
1728 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001729 }
1730 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001731
1732 void warnLoopStateMismatch(SourceLocation Loc,
1733 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001734 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1735 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001736
1737 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001738 }
1739
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001740 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1741 StringRef VariableName,
1742 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001743 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001744
1745 PartialDiagnosticAt Warning(Loc, S.PDiag(
1746 diag::warn_param_return_typestate_mismatch) << VariableName <<
1747 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001748
1749 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001750 }
1751
DeLesley Hutchins69391772013-10-17 23:23:53 +00001752 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001753 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001754
1755 PartialDiagnosticAt Warning(Loc, S.PDiag(
1756 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001757
1758 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001759 }
1760
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001761 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001762 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001763 PartialDiagnosticAt Warning(Loc, S.PDiag(
1764 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001765
1766 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001767 }
1768
1769 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001770 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001771
1772 PartialDiagnosticAt Warning(Loc, S.PDiag(
1773 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001774
1775 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001776 }
1777
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001778 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001779 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001780
1781 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001782 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001783
1784 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001785 }
1786
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001787 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001788 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001789
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001790 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1791 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001792
1793 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001794 }
1795};
1796}}}
1797
1798//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001799// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1800// warnings on a function, method, or block.
1801//===----------------------------------------------------------------------===//
1802
Ted Kremenek0b405322010-03-23 00:13:23 +00001803clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1804 enableCheckFallThrough = 1;
1805 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001806 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001807 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001808}
1809
Ted Kremenekad8753c2014-03-15 05:47:06 +00001810static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001811 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001812}
1813
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001814clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1815 : S(s),
1816 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001817 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001818 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001819 MaxCFGBlocksPerFunction(0),
1820 NumUninitAnalysisFunctions(0),
1821 NumUninitAnalysisVariables(0),
1822 MaxUninitAnalysisVariablesPerFunction(0),
1823 NumUninitAnalysisBlockVisits(0),
1824 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001825
1826 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001827 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001828
1829 DefaultPolicy.enableCheckUnreachable =
1830 isEnabled(D, warn_unreachable) ||
1831 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001832 isEnabled(D, warn_unreachable_return) ||
1833 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001834
1835 DefaultPolicy.enableThreadSafetyAnalysis =
1836 isEnabled(D, warn_double_lock);
1837
1838 DefaultPolicy.enableConsumedAnalysis =
1839 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001840}
1841
Aaron Ballmane5195222014-05-15 20:50:47 +00001842static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1843 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001844 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001845}
1846
Ted Kremenek0b405322010-03-23 00:13:23 +00001847void clang::sema::
1848AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001849 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001850 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001851
Ted Kremenek918fe842010-03-20 21:06:02 +00001852 // We avoid doing analysis-based warnings when there are errors for
1853 // two reasons:
1854 // (1) The CFGs often can't be constructed (if the body is invalid), so
1855 // don't bother trying.
1856 // (2) The code already has problems; running the analysis just takes more
1857 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001858 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001859
Ted Kremenek0b405322010-03-23 00:13:23 +00001860 // Do not do any analysis for declarations in system headers if we are
1861 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001862 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001863 S.SourceMgr.isInSystemHeader(D->getLocation()))
1864 return;
1865
John McCall1d570a72010-08-25 05:56:39 +00001866 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001867 if (cast<DeclContext>(D)->isDependentContext())
1868 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001869
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001870 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001871 // Flush out any possibly unreachable diagnostics.
1872 flushDiagnostics(S, fscope);
1873 return;
1874 }
1875
Ted Kremenek918fe842010-03-20 21:06:02 +00001876 const Stmt *Body = D->getBody();
1877 assert(Body);
1878
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001879 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00001880 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001881
Ted Kremenek918fe842010-03-20 21:06:02 +00001882 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001883 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001884 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1885 AC.getCFGBuildOptions().AddEHEdges = false;
1886 AC.getCFGBuildOptions().AddInitializers = true;
1887 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001888 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001889 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00001890 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001891
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001892 // Force that certain expressions appear as CFGElements in the CFG. This
1893 // is used to speed up various analyses.
1894 // FIXME: This isn't the right factoring. This is here for initial
1895 // prototyping, but we need a way for analyses to say what expressions they
1896 // expect to always be CFGElements and then fill in the BuildOptions
1897 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001898 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1899 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001900 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001901 AC.getCFGBuildOptions().setAllAlwaysAdd();
1902 }
1903 else {
1904 AC.getCFGBuildOptions()
1905 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001906 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001907 .setAlwaysAdd(Stmt::BlockExprClass)
1908 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1909 .setAlwaysAdd(Stmt::DeclRefExprClass)
1910 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001911 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1912 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001913 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001914
Richard Trieue9fa2662014-04-15 00:57:50 +00001915 // Install the logical handler for -Wtautological-overlap-compare
1916 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001917 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1918 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00001919 LEH.reset(new LogicalErrorHandler(S));
1920 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00001921 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001922
Ted Kremenek3427fac2011-02-23 01:52:04 +00001923 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001924 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001925 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001926
1927 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00001928 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1929 if (D.stmt)
1930 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00001931 }
1932
1933 if (AC.getCFG()) {
1934 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00001935 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00001936 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00001937 if (D.stmt) {
1938 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001939 CFGReverseBlockReachabilityAnalysis *cra =
1940 AC.getCFGReachablityAnalysis();
1941 // FIXME: We should be able to assert that block is non-null, but
1942 // the CFG analysis can skip potentially-evaluated expressions in
1943 // edge cases; see test/Sema/vla-2.c.
1944 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001945 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001946 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001947 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001948 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001949 }
1950 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001951 if (!processed) {
1952 // Emit the warning anyway if we cannot map to a basic block.
1953 S.Diag(D.Loc, D.PD);
1954 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001955 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001956 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001957
1958 if (!analyzed)
1959 flushDiagnostics(S, fscope);
1960 }
1961
1962
Ted Kremenek918fe842010-03-20 21:06:02 +00001963 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001964 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001965 const CheckFallThroughDiagnostics &CD =
1966 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001967 : (isa<CXXMethodDecl>(D) &&
1968 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1969 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1970 ? CheckFallThroughDiagnostics::MakeForLambda()
1971 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001972 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001973 }
1974
1975 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001976 if (P.enableCheckUnreachable) {
1977 // Only check for unreachable code on non-template instantiations.
1978 // Different template instantiations can effectively change the control-flow
1979 // and it is very difficult to prove that a snippet of code in a template
1980 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001981 bool isTemplateInstantiation = false;
1982 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1983 isTemplateInstantiation = Function->isTemplateInstantiation();
1984 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001985 CheckUnreachable(S, AC);
1986 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001987
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001988 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001989 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001990 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001991 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001992 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001993 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001994 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001995 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
1996 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001997
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001998 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
1999 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002000 Reporter.emitDiagnostics();
2001 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002002
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002003 // Check for violations of consumed properties.
2004 if (P.enableConsumedAnalysis) {
2005 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002006 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002007 Analyzer.run(AC);
2008 }
2009
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002010 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2011 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2012 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002013 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002014 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002015 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002016 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002017 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002018 reporter, stats);
2019
2020 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2021 ++NumUninitAnalysisFunctions;
2022 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2023 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2024 MaxUninitAnalysisVariablesPerFunction =
2025 std::max(MaxUninitAnalysisVariablesPerFunction,
2026 stats.NumVariablesAnalyzed);
2027 MaxUninitAnalysisBlockVisitsPerFunction =
2028 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2029 stats.NumBlockVisits);
2030 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002031 }
2032 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002033
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002034 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002035 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2036 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2037 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Alexis Hunt2178f142012-06-15 21:22:05 +00002038 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002039 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002040 }
2041
Jordan Rosed3934582012-09-28 22:21:30 +00002042 if (S.getLangOpts().ObjCARCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002043 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002044 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002045
Richard Trieu2f024f42013-12-21 02:33:43 +00002046
2047 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002048 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2049 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002050 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2051 checkRecursiveFunction(S, FD, Body, AC);
2052 }
2053 }
2054
Richard Trieue9fa2662014-04-15 00:57:50 +00002055 // If none of the previous checks caused a CFG build, trigger one here
2056 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002057 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002058 D->getLocStart())) {
2059 AC.getCFG();
2060 }
2061
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002062 // Collect statistics about the CFG if it was built.
2063 if (S.CollectStats && AC.isCFGBuilt()) {
2064 ++NumFunctionsAnalyzed;
2065 if (CFG *cfg = AC.getCFG()) {
2066 // If we successfully built a CFG for this context, record some more
2067 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002068 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002069 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002070 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002071 } else {
2072 ++NumFunctionsWithBadCFGs;
2073 }
2074 }
2075}
2076
2077void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2078 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2079
2080 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2081 unsigned AvgCFGBlocksPerFunction =
2082 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2083 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2084 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2085 << " " << NumCFGBlocks << " CFG blocks built.\n"
2086 << " " << AvgCFGBlocksPerFunction
2087 << " average CFG blocks per function.\n"
2088 << " " << MaxCFGBlocksPerFunction
2089 << " max CFG blocks per function.\n";
2090
2091 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2092 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2093 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2094 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2095 llvm::errs() << NumUninitAnalysisFunctions
2096 << " functions analyzed for uninitialiazed variables\n"
2097 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2098 << " " << AvgUninitVariablesPerFunction
2099 << " average variables per function.\n"
2100 << " " << MaxUninitAnalysisVariablesPerFunction
2101 << " max variables per function.\n"
2102 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2103 << " " << AvgUninitBlockVisitsPerFunction
2104 << " average block visits per function.\n"
2105 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2106 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002107}