blob: 32bdef6da92dabafac4259c6f96dcc43f7b33078 [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()) {
92 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.PP.getLocForEndOfToken(Close);
94 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
Richard Trieuf935b562014-04-05 05:17:01 +0000120/// \brief Warn on logical operator errors in CFGBuilder
121class LogicalErrorHandler : public CFGCallback {
122 Sema &S;
123
124public:
125 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
126
127 static bool HasMacroID(const Expr *E) {
128 if (E->getExprLoc().isMacroID())
129 return true;
130
131 // Recurse to children.
132 for (ConstStmtRange SubStmts = E->children(); SubStmts; ++SubStmts)
133 if (*SubStmts)
134 if (const Expr *SubExpr = dyn_cast<Expr>(*SubStmts))
135 if (HasMacroID(SubExpr))
136 return true;
137
138 return false;
139 }
140
141 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) {
142 if (HasMacroID(B))
143 return;
144
145 SourceRange DiagRange = B->getSourceRange();
146 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
147 << DiagRange << isAlwaysTrue;
148 }
149};
150
151
Ted Kremenek918fe842010-03-20 21:06:02 +0000152//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000153// Check for infinite self-recursion in functions
154//===----------------------------------------------------------------------===//
155
156// All blocks are in one of three states. States are ordered so that blocks
157// can only move to higher states.
158enum RecursiveState {
159 FoundNoPath,
160 FoundPath,
161 FoundPathWithNoRecursiveCall
162};
163
164static void checkForFunctionCall(Sema &S, const FunctionDecl *FD,
165 CFGBlock &Block, unsigned ExitID,
166 llvm::SmallVectorImpl<RecursiveState> &States,
167 RecursiveState State) {
168 unsigned ID = Block.getBlockID();
169
170 // A block's state can only move to a higher state.
171 if (States[ID] >= State)
172 return;
173
174 States[ID] = State;
175
176 // Found a path to the exit node without a recursive call.
177 if (ID == ExitID && State == FoundPathWithNoRecursiveCall)
178 return;
179
180 if (State == FoundPathWithNoRecursiveCall) {
181 // If the current state is FoundPathWithNoRecursiveCall, the successors
182 // will be either FoundPathWithNoRecursiveCall or FoundPath. To determine
183 // which, process all the Stmt's in this block to find any recursive calls.
184 for (CFGBlock::iterator I = Block.begin(), E = Block.end(); I != E; ++I) {
185 if (I->getKind() != CFGElement::Statement)
186 continue;
187
188 const CallExpr *CE = dyn_cast<CallExpr>(I->getAs<CFGStmt>()->getStmt());
189 if (CE && CE->getCalleeDecl() &&
190 CE->getCalleeDecl()->getCanonicalDecl() == FD) {
Richard Trieu658eb682014-01-04 01:57:42 +0000191
192 // Skip function calls which are qualified with a templated class.
193 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(
194 CE->getCallee()->IgnoreParenImpCasts())) {
195 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
196 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
197 isa<TemplateSpecializationType>(NNS->getAsType())) {
198 continue;
199 }
200 }
201 }
202
Richard Trieu2f024f42013-12-21 02:33:43 +0000203 if (const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE)) {
204 if (isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
205 !MCE->getMethodDecl()->isVirtual()) {
206 State = FoundPath;
207 break;
208 }
209 } else {
210 State = FoundPath;
211 break;
212 }
213 }
214 }
215 }
216
217 for (CFGBlock::succ_iterator I = Block.succ_begin(), E = Block.succ_end();
218 I != E; ++I)
219 if (*I)
220 checkForFunctionCall(S, FD, **I, ExitID, States, State);
221}
222
223static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
224 const Stmt *Body,
225 AnalysisDeclContext &AC) {
226 FD = FD->getCanonicalDecl();
227
228 // Only run on non-templated functions and non-templated members of
229 // templated classes.
230 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
231 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
232 return;
233
234 CFG *cfg = AC.getCFG();
235 if (cfg == 0) return;
236
237 // If the exit block is unreachable, skip processing the function.
238 if (cfg->getExit().pred_empty())
239 return;
240
241 // Mark all nodes as FoundNoPath, then begin processing the entry block.
242 llvm::SmallVector<RecursiveState, 16> states(cfg->getNumBlockIDs(),
243 FoundNoPath);
244 checkForFunctionCall(S, FD, cfg->getEntry(), cfg->getExit().getBlockID(),
245 states, FoundPathWithNoRecursiveCall);
246
247 // Check that the exit block is reachable. This prevents triggering the
248 // warning on functions that do not terminate.
249 if (states[cfg->getExit().getBlockID()] == FoundPath)
250 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
251}
252
253//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000254// Check for missing return value.
255//===----------------------------------------------------------------------===//
256
John McCall5c6ec8c2010-05-16 09:34:11 +0000257enum ControlFlowKind {
258 UnknownFallThrough,
259 NeverFallThrough,
260 MaybeFallThrough,
261 AlwaysFallThrough,
262 NeverFallThroughOrReturn
263};
Ted Kremenek918fe842010-03-20 21:06:02 +0000264
265/// CheckFallThrough - Check that we don't fall off the end of a
266/// Statement that should return a value.
267///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000268/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
269/// MaybeFallThrough iff we might or might not fall off the end,
270/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
271/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000272/// statement but we may return. We assume that functions not marked noreturn
273/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000274static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000275 CFG *cfg = AC.getCFG();
John McCall5c6ec8c2010-05-16 09:34:11 +0000276 if (cfg == 0) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000277
278 // The CFG leaves in dead things, and we don't want the dead code paths to
279 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000280 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000281 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000282 live);
283
284 bool AddEHEdges = AC.getAddEHEdges();
285 if (!AddEHEdges && count != cfg->getNumBlockIDs())
286 // When there are things remaining dead, and we didn't add EH edges
287 // from CallExprs to the catch clauses, we have to go back and
288 // mark them as live.
289 for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
290 CFGBlock &b = **I;
291 if (!live[b.getBlockID()]) {
292 if (b.pred_begin() == b.pred_end()) {
293 if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
294 // When not adding EH edges from calls, catch clauses
295 // can otherwise seem dead. Avoid noting them as dead.
Ted Kremenekbd913712011-08-23 23:05:11 +0000296 count += reachable_code::ScanReachableFromBlock(&b, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000297 continue;
298 }
299 }
300 }
301
302 // Now we know what is live, we check the live precessors of the exit block
303 // and look for fall through paths, being careful to ignore normal returns,
304 // and exceptional paths.
305 bool HasLiveReturn = false;
306 bool HasFakeEdge = false;
307 bool HasPlainEdge = false;
308 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000309
310 // Ignore default cases that aren't likely to be reachable because all
311 // enums in a switch(X) have explicit case statements.
312 CFGBlock::FilterOptions FO;
313 FO.IgnoreDefaultsWithCoveredEnums = 1;
314
315 for (CFGBlock::filtered_pred_iterator
316 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
317 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000318 if (!live[B.getBlockID()])
319 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000320
Chandler Carruth03faf782011-09-13 09:53:58 +0000321 // Skip blocks which contain an element marked as no-return. They don't
322 // represent actually viable edges into the exit block, so mark them as
323 // abnormal.
324 if (B.hasNoReturnElement()) {
325 HasAbnormalEdge = true;
326 continue;
327 }
328
Ted Kremenek5d068492011-01-26 04:49:52 +0000329 // Destructors can appear after the 'return' in the CFG. This is
330 // normal. We need to look pass the destructors for the return
331 // statement (if it exists).
332 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000333
Chandler Carruth03faf782011-09-13 09:53:58 +0000334 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000335 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000336 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000337
Ted Kremenek5d068492011-01-26 04:49:52 +0000338 // No more CFGElements in the block?
339 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000340 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
341 HasAbnormalEdge = true;
342 continue;
343 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000344 // A labeled empty statement, or the entry block...
345 HasPlainEdge = true;
346 continue;
347 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000348
David Blaikie2a01f5d2013-02-21 20:58:29 +0000349 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000350 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000351 if (isa<ReturnStmt>(S)) {
352 HasLiveReturn = true;
353 continue;
354 }
355 if (isa<ObjCAtThrowStmt>(S)) {
356 HasFakeEdge = true;
357 continue;
358 }
359 if (isa<CXXThrowExpr>(S)) {
360 HasFakeEdge = true;
361 continue;
362 }
Chad Rosier32503022012-06-11 20:47:18 +0000363 if (isa<MSAsmStmt>(S)) {
364 // TODO: Verify this is correct.
365 HasFakeEdge = true;
366 HasLiveReturn = true;
367 continue;
368 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000369 if (isa<CXXTryStmt>(S)) {
370 HasAbnormalEdge = true;
371 continue;
372 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000373 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
374 == B.succ_end()) {
375 HasAbnormalEdge = true;
376 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000377 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000378
379 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000380 }
381 if (!HasPlainEdge) {
382 if (HasLiveReturn)
383 return NeverFallThrough;
384 return NeverFallThroughOrReturn;
385 }
386 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
387 return MaybeFallThrough;
388 // This says AlwaysFallThrough for calls to functions that are not marked
389 // noreturn, that don't return. If people would like this warning to be more
390 // accurate, such functions should be marked as noreturn.
391 return AlwaysFallThrough;
392}
393
Dan Gohman28ade552010-07-26 21:25:24 +0000394namespace {
395
Ted Kremenek918fe842010-03-20 21:06:02 +0000396struct CheckFallThroughDiagnostics {
397 unsigned diag_MaybeFallThrough_HasNoReturn;
398 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
399 unsigned diag_AlwaysFallThrough_HasNoReturn;
400 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
401 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000402 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000403 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000404
Douglas Gregor24f27692010-04-16 23:28:44 +0000405 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000406 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000407 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000408 D.diag_MaybeFallThrough_HasNoReturn =
409 diag::warn_falloff_noreturn_function;
410 D.diag_MaybeFallThrough_ReturnsNonVoid =
411 diag::warn_maybe_falloff_nonvoid_function;
412 D.diag_AlwaysFallThrough_HasNoReturn =
413 diag::warn_falloff_noreturn_function;
414 D.diag_AlwaysFallThrough_ReturnsNonVoid =
415 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000416
417 // Don't suggest that virtual functions be marked "noreturn", since they
418 // might be overridden by non-noreturn functions.
419 bool isVirtualMethod = false;
420 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
421 isVirtualMethod = Method->isVirtual();
422
Douglas Gregor0de57202011-10-10 18:15:57 +0000423 // Don't suggest that template instantiations be marked "noreturn"
424 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000425 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
426 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000427
428 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000429 D.diag_NeverFallThroughOrReturn =
430 diag::warn_suggest_noreturn_function;
431 else
432 D.diag_NeverFallThroughOrReturn = 0;
433
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000434 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000435 return D;
436 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000437
Ted Kremenek918fe842010-03-20 21:06:02 +0000438 static CheckFallThroughDiagnostics MakeForBlock() {
439 CheckFallThroughDiagnostics D;
440 D.diag_MaybeFallThrough_HasNoReturn =
441 diag::err_noreturn_block_has_return_expr;
442 D.diag_MaybeFallThrough_ReturnsNonVoid =
443 diag::err_maybe_falloff_nonvoid_block;
444 D.diag_AlwaysFallThrough_HasNoReturn =
445 diag::err_noreturn_block_has_return_expr;
446 D.diag_AlwaysFallThrough_ReturnsNonVoid =
447 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000448 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000449 D.funMode = Block;
450 return D;
451 }
452
453 static CheckFallThroughDiagnostics MakeForLambda() {
454 CheckFallThroughDiagnostics D;
455 D.diag_MaybeFallThrough_HasNoReturn =
456 diag::err_noreturn_lambda_has_return_expr;
457 D.diag_MaybeFallThrough_ReturnsNonVoid =
458 diag::warn_maybe_falloff_nonvoid_lambda;
459 D.diag_AlwaysFallThrough_HasNoReturn =
460 diag::err_noreturn_lambda_has_return_expr;
461 D.diag_AlwaysFallThrough_ReturnsNonVoid =
462 diag::warn_falloff_nonvoid_lambda;
463 D.diag_NeverFallThroughOrReturn = 0;
464 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000465 return D;
466 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000467
David Blaikie9c902b52011-09-25 23:23:43 +0000468 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000469 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000470 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000471 return (ReturnsVoid ||
472 D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
David Blaikie9c902b52011-09-25 23:23:43 +0000473 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000474 && (!HasNoReturn ||
475 D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
David Blaikie9c902b52011-09-25 23:23:43 +0000476 FuncLoc) == DiagnosticsEngine::Ignored)
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000477 && (!ReturnsVoid ||
478 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
David Blaikie9c902b52011-09-25 23:23:43 +0000479 == DiagnosticsEngine::Ignored);
Ted Kremenek918fe842010-03-20 21:06:02 +0000480 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000481
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000482 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000483 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000484 }
485};
486
Dan Gohman28ade552010-07-26 21:25:24 +0000487}
488
Ted Kremenek918fe842010-03-20 21:06:02 +0000489/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
490/// function that should return a value. Check that we don't fall off the end
491/// of a noreturn function. We assume that functions and blocks not marked
492/// noreturn will return.
493static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000494 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000495 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000496 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000497
498 bool ReturnsVoid = false;
499 bool HasNoReturn = false;
500
501 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000502 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000503 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000504 }
505 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000506 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000507 HasNoReturn = MD->hasAttr<NoReturnAttr>();
508 }
509 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000510 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000511 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000512 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000513 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000514 ReturnsVoid = true;
515 if (FT->getNoReturnAttr())
516 HasNoReturn = true;
517 }
518 }
519
David Blaikie9c902b52011-09-25 23:23:43 +0000520 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000521
522 // Short circuit for compilation speed.
523 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
524 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000525
Ted Kremenek918fe842010-03-20 21:06:02 +0000526 // FIXME: Function try block
527 if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
528 switch (CheckFallThrough(AC)) {
John McCall5c6ec8c2010-05-16 09:34:11 +0000529 case UnknownFallThrough:
530 break;
531
Ted Kremenek918fe842010-03-20 21:06:02 +0000532 case MaybeFallThrough:
533 if (HasNoReturn)
534 S.Diag(Compound->getRBracLoc(),
535 CD.diag_MaybeFallThrough_HasNoReturn);
536 else if (!ReturnsVoid)
537 S.Diag(Compound->getRBracLoc(),
538 CD.diag_MaybeFallThrough_ReturnsNonVoid);
539 break;
540 case AlwaysFallThrough:
541 if (HasNoReturn)
542 S.Diag(Compound->getRBracLoc(),
543 CD.diag_AlwaysFallThrough_HasNoReturn);
544 else if (!ReturnsVoid)
545 S.Diag(Compound->getRBracLoc(),
546 CD.diag_AlwaysFallThrough_ReturnsNonVoid);
547 break;
548 case NeverFallThroughOrReturn:
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000549 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
550 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
551 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
Douglas Gregor97e35902011-09-10 00:56:20 +0000552 << 0 << FD;
553 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
554 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
555 << 1 << MD;
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000556 } else {
557 S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
558 }
559 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000560 break;
561 case NeverFallThrough:
562 break;
563 }
564 }
565}
566
567//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000568// -Wuninitialized
569//===----------------------------------------------------------------------===//
570
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000571namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000572/// ContainsReference - A visitor class to search for references to
573/// a particular declaration (the needle) within any evaluated component of an
574/// expression (recursively).
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000575class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000576 bool FoundReference;
577 const DeclRefExpr *Needle;
578
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000579public:
Chandler Carruth4e021822011-04-05 06:48:00 +0000580 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
581 : EvaluatedExprVisitor<ContainsReference>(Context),
582 FoundReference(false), Needle(Needle) {}
583
584 void VisitExpr(Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000585 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000586 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000587 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000588
589 EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000590 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000591
592 void VisitDeclRefExpr(DeclRefExpr *E) {
593 if (E == Needle)
594 FoundReference = true;
595 else
596 EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000597 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000598
599 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000600};
601}
602
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000603static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000604 QualType VariableTy = VD->getType().getCanonicalType();
605 if (VariableTy->isBlockPointerType() &&
606 !VD->hasAttr<BlocksAttr>()) {
607 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization) << VD->getDeclName()
608 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
609 return true;
610 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000611
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000612 // Don't issue a fixit if there is already an initializer.
613 if (VD->getInit())
614 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000615
616 // Don't suggest a fixit inside macros.
617 if (VD->getLocEnd().isMacroID())
618 return false;
619
Richard Smith8d06f422012-01-12 23:53:29 +0000620 SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000621
622 // Suggest possible initialization (if any).
623 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
624 if (Init.empty())
625 return false;
626
Richard Smith8d06f422012-01-12 23:53:29 +0000627 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
628 << FixItHint::CreateInsertion(Loc, Init);
629 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000630}
631
Richard Smith1bb8edb82012-05-26 06:20:46 +0000632/// Create a fixit to remove an if-like statement, on the assumption that its
633/// condition is CondVal.
634static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
635 const Stmt *Else, bool CondVal,
636 FixItHint &Fixit1, FixItHint &Fixit2) {
637 if (CondVal) {
638 // If condition is always true, remove all but the 'then'.
639 Fixit1 = FixItHint::CreateRemoval(
640 CharSourceRange::getCharRange(If->getLocStart(),
641 Then->getLocStart()));
642 if (Else) {
643 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
644 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
645 Fixit2 = FixItHint::CreateRemoval(
646 SourceRange(ElseKwLoc, Else->getLocEnd()));
647 }
648 } else {
649 // If condition is always false, remove all but the 'else'.
650 if (Else)
651 Fixit1 = FixItHint::CreateRemoval(
652 CharSourceRange::getCharRange(If->getLocStart(),
653 Else->getLocStart()));
654 else
655 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
656 }
657}
658
659/// DiagUninitUse -- Helper function to produce a diagnostic for an
660/// uninitialized use of a variable.
661static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
662 bool IsCapturedByBlock) {
663 bool Diagnosed = false;
664
Richard Smithba8071e2013-09-12 18:49:10 +0000665 switch (Use.getKind()) {
666 case UninitUse::Always:
667 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
668 << VD->getDeclName() << IsCapturedByBlock
669 << Use.getUser()->getSourceRange();
670 return;
671
672 case UninitUse::AfterDecl:
673 case UninitUse::AfterCall:
674 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
675 << VD->getDeclName() << IsCapturedByBlock
676 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
677 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
678 << VD->getSourceRange();
679 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
680 << IsCapturedByBlock << Use.getUser()->getSourceRange();
681 return;
682
683 case UninitUse::Maybe:
684 case UninitUse::Sometimes:
685 // Carry on to report sometimes-uninitialized branches, if possible,
686 // or a 'may be used uninitialized' diagnostic otherwise.
687 break;
688 }
689
Richard Smith1bb8edb82012-05-26 06:20:46 +0000690 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000691 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
692 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000693 assert(Use.getKind() == UninitUse::Sometimes);
694
695 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000696 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000697
698 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000699 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000700 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000701 SourceRange Range;
702
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000703 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000704 // For all binary terminators, branch 0 is taken if the condition is true,
705 // and branch 1 is taken if the condition is false.
706 int RemoveDiagKind = -1;
707 const char *FixitStr =
708 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
709 : (I->Output ? "1" : "0");
710 FixItHint Fixit1, Fixit2;
711
Richard Smithba8071e2013-09-12 18:49:10 +0000712 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000713 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000714 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000715 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000716 continue;
717
718 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000719 case Stmt::IfStmtClass: {
720 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000721 DiagKind = 0;
722 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000723 Range = IS->getCond()->getSourceRange();
724 RemoveDiagKind = 0;
725 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
726 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000727 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000728 }
729 case Stmt::ConditionalOperatorClass: {
730 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000731 DiagKind = 0;
732 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000733 Range = CO->getCond()->getSourceRange();
734 RemoveDiagKind = 0;
735 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
736 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000737 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000738 }
Richard Smith4323bf82012-05-25 02:17:09 +0000739 case Stmt::BinaryOperatorClass: {
740 const BinaryOperator *BO = cast<BinaryOperator>(Term);
741 if (!BO->isLogicalOp())
742 continue;
743 DiagKind = 0;
744 Str = BO->getOpcodeStr();
745 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000746 RemoveDiagKind = 0;
747 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
748 (BO->getOpcode() == BO_LOr && !I->Output))
749 // true && y -> y, false || y -> y.
750 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
751 BO->getOperatorLoc()));
752 else
753 // false && y -> false, true || y -> true.
754 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000755 break;
756 }
757
758 // "loop is entered / loop is exited".
759 case Stmt::WhileStmtClass:
760 DiagKind = 1;
761 Str = "while";
762 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000763 RemoveDiagKind = 1;
764 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000765 break;
766 case Stmt::ForStmtClass:
767 DiagKind = 1;
768 Str = "for";
769 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000770 RemoveDiagKind = 1;
771 if (I->Output)
772 Fixit1 = FixItHint::CreateRemoval(Range);
773 else
774 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000775 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000776 case Stmt::CXXForRangeStmtClass:
777 if (I->Output == 1) {
778 // The use occurs if a range-based for loop's body never executes.
779 // That may be impossible, and there's no syntactic fix for this,
780 // so treat it as a 'may be uninitialized' case.
781 continue;
782 }
783 DiagKind = 1;
784 Str = "for";
785 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
786 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000787
788 // "condition is true / loop is exited".
789 case Stmt::DoStmtClass:
790 DiagKind = 2;
791 Str = "do";
792 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000793 RemoveDiagKind = 1;
794 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000795 break;
796
797 // "switch case is taken".
798 case Stmt::CaseStmtClass:
799 DiagKind = 3;
800 Str = "case";
801 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
802 break;
803 case Stmt::DefaultStmtClass:
804 DiagKind = 3;
805 Str = "default";
806 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
807 break;
808 }
809
Richard Smith1bb8edb82012-05-26 06:20:46 +0000810 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
811 << VD->getDeclName() << IsCapturedByBlock << DiagKind
812 << Str << I->Output << Range;
813 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
814 << IsCapturedByBlock << User->getSourceRange();
815 if (RemoveDiagKind != -1)
816 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
817 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
818
819 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000820 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000821
822 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000823 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000824 << VD->getDeclName() << IsCapturedByBlock
825 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000826}
827
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000828/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
829/// uninitialized variable. This manages the different forms of diagnostic
830/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000831/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000832/// false.
833static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000834 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000835 bool alwaysReportSelfInit = false) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000836
Richard Smith4323bf82012-05-25 02:17:09 +0000837 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000838 // Inspect the initializer of the variable declaration which is
839 // being referenced prior to its initialization. We emit
840 // specialized diagnostics for self-initialization, and we
841 // specifically avoid warning about self references which take the
842 // form of:
843 //
844 // int x = x;
845 //
846 // This is used to indicate to GCC that 'x' is intentionally left
847 // uninitialized. Proven code paths which access 'x' in
848 // an uninitialized state after this will still warn.
849 if (const Expr *Initializer = VD->getInit()) {
850 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
851 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000852
Richard Trieu43a2fc72012-05-09 21:08:22 +0000853 ContainsReference CR(S.Context, DRE);
854 CR.Visit(const_cast<Expr*>(Initializer));
855 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000856 S.Diag(DRE->getLocStart(),
857 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000858 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
859 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000860 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000861 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000862
Richard Smith1bb8edb82012-05-26 06:20:46 +0000863 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000864 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000865 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000866 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
867 S.Diag(BE->getLocStart(),
868 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000869 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000870 else
871 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000872 }
873
874 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000875 // the initializer of that declaration & we didn't already suggest
876 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000877 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000878 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
879 << VD->getDeclName();
880
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000881 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000882}
883
Richard Smith84837d52012-05-03 18:27:39 +0000884namespace {
885 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
886 public:
887 FallthroughMapper(Sema &S)
888 : FoundSwitchStatements(false),
889 S(S) {
890 }
891
892 bool foundSwitchStatements() const { return FoundSwitchStatements; }
893
894 void markFallthroughVisited(const AttributedStmt *Stmt) {
895 bool Found = FallthroughStmts.erase(Stmt);
896 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000897 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000898 }
899
900 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
901
902 const AttrStmts &getFallthroughStmts() const {
903 return FallthroughStmts;
904 }
905
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000906 void fillReachableBlocks(CFG *Cfg) {
907 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
908 std::deque<const CFGBlock *> BlockQueue;
909
910 ReachableBlocks.insert(&Cfg->getEntry());
911 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000912 // Mark all case blocks reachable to avoid problems with switching on
913 // constants, covered enums, etc.
914 // These blocks can contain fall-through annotations, and we don't want to
915 // issue a warn_fallthrough_attr_unreachable for them.
916 for (CFG::iterator I = Cfg->begin(), E = Cfg->end(); I != E; ++I) {
917 const CFGBlock *B = *I;
918 const Stmt *L = B->getLabel();
919 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B))
920 BlockQueue.push_back(B);
921 }
922
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000923 while (!BlockQueue.empty()) {
924 const CFGBlock *P = BlockQueue.front();
925 BlockQueue.pop_front();
926 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
927 E = P->succ_end();
928 I != E; ++I) {
Alexander Kornienko527fa4f2013-02-01 15:39:20 +0000929 if (*I && ReachableBlocks.insert(*I))
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000930 BlockQueue.push_back(*I);
931 }
932 }
933 }
934
Richard Smith84837d52012-05-03 18:27:39 +0000935 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000936 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
937
Richard Smith84837d52012-05-03 18:27:39 +0000938 int UnannotatedCnt = 0;
939 AnnotatedCnt = 0;
940
941 std::deque<const CFGBlock*> BlockQueue;
942
943 std::copy(B.pred_begin(), B.pred_end(), std::back_inserter(BlockQueue));
944
945 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
Richard Smith84837d52012-05-03 18:27:39 +00001025 private:
1026
1027 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1028 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1029 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1030 return AS;
1031 }
1032 return 0;
1033 }
1034
1035 static const Stmt *getLastStmt(const CFGBlock &B) {
1036 if (const Stmt *Term = B.getTerminator())
1037 return Term;
1038 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1039 ElemEnd = B.rend();
1040 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001041 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1042 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001043 }
1044 // Workaround to detect a statement thrown out by CFGBuilder:
1045 // case X: {} case Y:
1046 // case X: ; case Y:
1047 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1048 if (!isa<SwitchCase>(SW->getSubStmt()))
1049 return SW->getSubStmt();
1050
1051 return 0;
1052 }
1053
1054 bool FoundSwitchStatements;
1055 AttrStmts FallthroughStmts;
1056 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001057 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001058 };
1059}
1060
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001061static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001062 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001063 // Only perform this analysis when using C++11. There is no good workflow
1064 // for this warning when not using C++11. There is no good way to silence
1065 // the warning (no attribute is available) unless we are using C++11's support
1066 // for generalized attributes. Once could use pragmas to silence the warning,
1067 // but as a general solution that is gross and not in the spirit of this
1068 // warning.
1069 //
1070 // NOTE: This an intermediate solution. There are on-going discussions on
1071 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001072 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001073 return;
1074
Richard Smith84837d52012-05-03 18:27:39 +00001075 FallthroughMapper FM(S);
1076 FM.TraverseStmt(AC.getBody());
1077
1078 if (!FM.foundSwitchStatements())
1079 return;
1080
Alexis Hunt2178f142012-06-15 21:22:05 +00001081 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001082 return;
1083
Richard Smith84837d52012-05-03 18:27:39 +00001084 CFG *Cfg = AC.getCFG();
1085
1086 if (!Cfg)
1087 return;
1088
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001089 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001090
1091 for (CFG::reverse_iterator I = Cfg->rbegin(), E = Cfg->rend(); I != E; ++I) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001092 const CFGBlock *B = *I;
1093 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001094
1095 if (!Label || !isa<SwitchCase>(Label))
1096 continue;
1097
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001098 int AnnotatedCnt;
1099
Alexander Kornienko55488792013-01-25 15:49:34 +00001100 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001101 continue;
1102
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001103 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001104 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1105 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001106
1107 if (!AnnotatedCnt) {
1108 SourceLocation L = Label->getLocStart();
1109 if (L.isMacroID())
1110 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001111 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001112 const Stmt *Term = B->getTerminator();
1113 // Skip empty cases.
1114 while (B->empty() && !Term && B->succ_size() == 1) {
1115 B = *B->succ_begin();
1116 Term = B->getTerminator();
1117 }
1118 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001119 Preprocessor &PP = S.getPreprocessor();
1120 TokenValue Tokens[] = {
1121 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1122 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1123 tok::r_square, tok::r_square
1124 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001125 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1126 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1127 if (!MacroName.empty())
1128 AnnotationSpelling = MacroName;
1129 SmallString<64> TextToInsert(AnnotationSpelling);
1130 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001131 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001132 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001133 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001134 }
Richard Smith84837d52012-05-03 18:27:39 +00001135 }
1136 S.Diag(L, diag::note_insert_break_fixit) <<
1137 FixItHint::CreateInsertion(L, "break; ");
1138 }
1139 }
1140
1141 const FallthroughMapper::AttrStmts &Fallthroughs = FM.getFallthroughStmts();
1142 for (FallthroughMapper::AttrStmts::const_iterator I = Fallthroughs.begin(),
1143 E = Fallthroughs.end();
1144 I != E; ++I) {
1145 S.Diag((*I)->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
1146 }
1147
1148}
1149
Jordan Rose25c0ea82012-10-29 17:46:47 +00001150static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1151 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001152 assert(S);
1153
1154 do {
1155 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001156 case Stmt::ForStmtClass:
1157 case Stmt::WhileStmtClass:
1158 case Stmt::CXXForRangeStmtClass:
1159 case Stmt::ObjCForCollectionStmtClass:
1160 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001161 case Stmt::DoStmtClass: {
1162 const Expr *Cond = cast<DoStmt>(S)->getCond();
1163 llvm::APSInt Val;
1164 if (!Cond->EvaluateAsInt(Val, Ctx))
1165 return true;
1166 return Val.getBoolValue();
1167 }
Jordan Rose76831c62012-10-11 16:10:19 +00001168 default:
1169 break;
1170 }
1171 } while ((S = PM.getParent(S)));
1172
1173 return false;
1174}
1175
Jordan Rosed3934582012-09-28 22:21:30 +00001176
1177static void diagnoseRepeatedUseOfWeak(Sema &S,
1178 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001179 const Decl *D,
1180 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001181 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1182 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1183 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001184 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1185 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001186
Jordan Rose25c0ea82012-10-29 17:46:47 +00001187 ASTContext &Ctx = S.getASTContext();
1188
Jordan Rosed3934582012-09-28 22:21:30 +00001189 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1190
1191 // Extract all weak objects that are referenced more than once.
1192 SmallVector<StmtUsesPair, 8> UsesByStmt;
1193 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1194 I != E; ++I) {
1195 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001196
1197 // Find the first read of the weak object.
1198 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1199 for ( ; UI != UE; ++UI) {
1200 if (UI->isUnsafe())
1201 break;
1202 }
1203
1204 // If there were only writes to this object, don't warn.
1205 if (UI == UE)
1206 continue;
1207
Jordan Rose76831c62012-10-11 16:10:19 +00001208 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001209 // read is not within a loop, don't warn. Additionally, don't warn in a
1210 // loop if the base object is a local variable -- local variables are often
1211 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001212 if (UI == Uses.begin()) {
1213 WeakUseVector::const_iterator UI2 = UI;
1214 for (++UI2; UI2 != UE; ++UI2)
1215 if (UI2->isUnsafe())
1216 break;
1217
Jordan Rose25c0ea82012-10-29 17:46:47 +00001218 if (UI2 == UE) {
1219 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001220 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001221
1222 const WeakObjectProfileTy &Profile = I->first;
1223 if (!Profile.isExactProfile())
1224 continue;
1225
1226 const NamedDecl *Base = Profile.getBase();
1227 if (!Base)
1228 Base = Profile.getProperty();
1229 assert(Base && "A profile always has a base or property.");
1230
1231 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1232 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1233 continue;
1234 }
Jordan Rose76831c62012-10-11 16:10:19 +00001235 }
1236
Jordan Rosed3934582012-09-28 22:21:30 +00001237 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1238 }
1239
1240 if (UsesByStmt.empty())
1241 return;
1242
1243 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001244 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001245 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001246 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1247 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1248 RHS.first->getLocStart());
1249 });
Jordan Rosed3934582012-09-28 22:21:30 +00001250
1251 // Classify the current code body for better warning text.
1252 // This enum should stay in sync with the cases in
1253 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1254 // FIXME: Should we use a common classification enum and the same set of
1255 // possibilities all throughout Sema?
1256 enum {
1257 Function,
1258 Method,
1259 Block,
1260 Lambda
1261 } FunctionKind;
1262
1263 if (isa<sema::BlockScopeInfo>(CurFn))
1264 FunctionKind = Block;
1265 else if (isa<sema::LambdaScopeInfo>(CurFn))
1266 FunctionKind = Lambda;
1267 else if (isa<ObjCMethodDecl>(D))
1268 FunctionKind = Method;
1269 else
1270 FunctionKind = Function;
1271
1272 // Iterate through the sorted problems and emit warnings for each.
1273 for (SmallVectorImpl<StmtUsesPair>::const_iterator I = UsesByStmt.begin(),
1274 E = UsesByStmt.end();
1275 I != E; ++I) {
1276 const Stmt *FirstRead = I->first;
1277 const WeakObjectProfileTy &Key = I->second->first;
1278 const WeakUseVector &Uses = I->second->second;
1279
Jordan Rose657b5f42012-09-28 22:21:35 +00001280 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1281 // may not contain enough information to determine that these are different
1282 // properties. We can only be 100% sure of a repeated use in certain cases,
1283 // and we adjust the diagnostic kind accordingly so that the less certain
1284 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001285 unsigned DiagKind;
1286 if (Key.isExactProfile())
1287 DiagKind = diag::warn_arc_repeated_use_of_weak;
1288 else
1289 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1290
Jordan Rose657b5f42012-09-28 22:21:35 +00001291 // Classify the weak object being accessed for better warning text.
1292 // This enum should stay in sync with the cases in
1293 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1294 enum {
1295 Variable,
1296 Property,
1297 ImplicitProperty,
1298 Ivar
1299 } ObjectKind;
1300
1301 const NamedDecl *D = Key.getProperty();
1302 if (isa<VarDecl>(D))
1303 ObjectKind = Variable;
1304 else if (isa<ObjCPropertyDecl>(D))
1305 ObjectKind = Property;
1306 else if (isa<ObjCMethodDecl>(D))
1307 ObjectKind = ImplicitProperty;
1308 else if (isa<ObjCIvarDecl>(D))
1309 ObjectKind = Ivar;
1310 else
1311 llvm_unreachable("Unexpected weak object kind!");
1312
Jordan Rosed3934582012-09-28 22:21:30 +00001313 // Show the first time the object was read.
1314 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001315 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001316 << FirstRead->getSourceRange();
1317
1318 // Print all the other accesses as notes.
1319 for (WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1320 UI != UE; ++UI) {
1321 if (UI->getUseExpr() == FirstRead)
1322 continue;
1323 S.Diag(UI->getUseExpr()->getLocStart(),
1324 diag::note_arc_weak_also_accessed_here)
1325 << UI->getUseExpr()->getSourceRange();
1326 }
1327 }
1328}
1329
Jordan Rosed3934582012-09-28 22:21:30 +00001330namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001331class UninitValsDiagReporter : public UninitVariablesHandler {
1332 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001333 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001334 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001335 // Prefer using MapVector to DenseMap, so that iteration order will be
1336 // the same as insertion order. This is needed to obtain a deterministic
1337 // order of diagnostics when calling flushDiagnostics().
1338 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001339 UsesMap *uses;
1340
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001341public:
Ted Kremenek39fa0562011-01-21 19:41:41 +00001342 UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
1343 ~UninitValsDiagReporter() {
1344 flushDiagnostics();
1345 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001346
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001347 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001348 if (!uses)
1349 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001350
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001351 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001352 if (!V.getPointer())
1353 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001354
Ted Kremenek596fa162011-10-13 18:50:06 +00001355 return V;
1356 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001357
1358 void handleUseOfUninitVariable(const VarDecl *vd,
1359 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001360 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001361 }
1362
Craig Toppere14c0f82014-03-12 04:55:44 +00001363 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001364 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001365 }
1366
1367 void flushDiagnostics() {
1368 if (!uses)
1369 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001370
Ted Kremenek39fa0562011-01-21 19:41:41 +00001371 for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
1372 const VarDecl *vd = i->first;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001373 const MappedType &V = i->second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001374
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001375 UsesVec *vec = V.getPointer();
1376 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001377
1378 // Specially handle the case where we have uses of an uninitialized
1379 // variable, but the root cause is an idiomatic self-init. We want
1380 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001381 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001382 DiagnoseUninitializedUse(S, vd,
1383 UninitUse(vd->getInit()->IgnoreParenCasts(),
1384 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001385 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001386 else {
1387 // Sort the uses by their SourceLocations. While not strictly
1388 // guaranteed to produce them in line/column order, this will provide
1389 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001390 std::sort(vec->begin(), vec->end(),
1391 [](const UninitUse &a, const UninitUse &b) {
1392 // Prefer a more confident report over a less confident one.
1393 if (a.getKind() != b.getKind())
1394 return a.getKind() > b.getKind();
1395 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1396 });
1397
Ted Kremenek596fa162011-10-13 18:50:06 +00001398 for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
1399 ++vi) {
Richard Smith4323bf82012-05-25 02:17:09 +00001400 // If we have self-init, downgrade all uses to 'may be uninitialized'.
1401 UninitUse Use = hasSelfInit ? UninitUse(vi->getUser(), false) : *vi;
1402
1403 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001404 // Skip further diagnostics for this variable. We try to warn only
1405 // on the first point at which a variable is used uninitialized.
1406 break;
1407 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001408 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001409
1410 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001411 delete vec;
1412 }
1413 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001414 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001415
1416private:
1417 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
1418 for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
Richard Smithba8071e2013-09-12 18:49:10 +00001419 if (i->getKind() == UninitUse::Always ||
1420 i->getKind() == UninitUse::AfterCall ||
1421 i->getKind() == UninitUse::AfterDecl) {
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001422 return true;
1423 }
1424 }
1425 return false;
1426}
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001427};
1428}
1429
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001430namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001431namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001432typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001433typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001434typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001435
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001436struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001437 SourceManager &SM;
1438 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001439
1440 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1441 // Although this call will be slow, this is only called when outputting
1442 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001443 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001444 }
1445};
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001446}}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001447
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001448//===----------------------------------------------------------------------===//
1449// -Wthread-safety
1450//===----------------------------------------------------------------------===//
1451namespace clang {
1452namespace thread_safety {
David Blaikie68e081d2011-12-20 02:48:34 +00001453namespace {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001454class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
1455 Sema &S;
1456 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001457 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001458
1459 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001460 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1461 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001462 // Gracefully handle rare cases when the analysis can't get a more
1463 // precise source location.
1464 if (!Loc.isValid())
1465 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001466 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001467 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001468 }
1469
1470 public:
Richard Smith92286672012-02-03 04:45:26 +00001471 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
1472 : S(S), FunLocation(FL), FunEndLocation(FEL) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001473
1474 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1475 /// We need to output diagnostics produced while iterating through
1476 /// the lockset in deterministic order, so this function orders diagnostics
1477 /// and outputs them.
1478 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001479 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001480 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
Richard Smith92286672012-02-03 04:45:26 +00001481 I != E; ++I) {
1482 S.Diag(I->first.first, I->first.second);
1483 const OptionalNotes &Notes = I->second;
1484 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
1485 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1486 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001487 }
1488
Aaron Ballmane0449042014-04-01 21:43:23 +00001489 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1490 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1491 << Loc);
Richard Smith92286672012-02-03 04:45:26 +00001492 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001493 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001494 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1495 SourceLocation Loc) override {
1496 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001497 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001498 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1499 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001500 SourceLocation Loc) override {
1501 if (Loc.isInvalid())
1502 Loc = FunLocation;
1503 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001504 << Kind << LockName << Received
1505 << Expected);
Aaron Ballmandf115d92014-03-21 14:48:48 +00001506 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1507 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001508 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1509 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001510 }
1511
Aaron Ballmane0449042014-04-01 21:43:23 +00001512 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1513 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001514 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001515 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001516 unsigned DiagID = 0;
1517 switch (LEK) {
1518 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001519 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001520 break;
1521 case LEK_LockedSomeLoopIterations:
1522 DiagID = diag::warn_expecting_lock_held_on_loop;
1523 break;
1524 case LEK_LockedAtEndOfFunction:
1525 DiagID = diag::warn_no_unlock;
1526 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001527 case LEK_NotLockedAtEndOfFunction:
1528 DiagID = diag::warn_expecting_locked;
1529 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001530 }
Richard Smith92286672012-02-03 04:45:26 +00001531 if (LocEndOfScope.isInvalid())
1532 LocEndOfScope = FunEndLocation;
1533
Aaron Ballmane0449042014-04-01 21:43:23 +00001534 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1535 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001536 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001537 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1538 << Kind);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001539 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1540 return;
1541 }
1542 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001543 }
1544
Aaron Ballmane0449042014-04-01 21:43:23 +00001545 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1546 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001547 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001548 PartialDiagnosticAt Warning(Loc1,
1549 S.PDiag(diag::warn_lock_exclusive_and_shared)
1550 << Kind << LockName);
1551 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1552 << Kind << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001553 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001554 }
1555
Aaron Ballmane0449042014-04-01 21:43:23 +00001556 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1557 ProtectedOperationKind POK, AccessKind AK,
1558 SourceLocation Loc) override {
1559 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1560 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001561 unsigned DiagID = POK == POK_VarAccess?
1562 diag::warn_variable_requires_any_lock:
1563 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001564 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001565 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Richard Smith92286672012-02-03 04:45:26 +00001566 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001567 }
1568
Aaron Ballmane0449042014-04-01 21:43:23 +00001569 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1570 ProtectedOperationKind POK, Name LockName,
1571 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001572 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001573 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001574 if (PossibleMatch) {
1575 switch (POK) {
1576 case POK_VarAccess:
1577 DiagID = diag::warn_variable_requires_lock_precise;
1578 break;
1579 case POK_VarDereference:
1580 DiagID = diag::warn_var_deref_requires_lock_precise;
1581 break;
1582 case POK_FunctionCall:
1583 DiagID = diag::warn_fun_requires_lock_precise;
1584 break;
1585 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001586 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1587 << D->getNameAsString()
1588 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001589 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001590 << *PossibleMatch);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001591 Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
1592 } else {
1593 switch (POK) {
1594 case POK_VarAccess:
1595 DiagID = diag::warn_variable_requires_lock;
1596 break;
1597 case POK_VarDereference:
1598 DiagID = diag::warn_var_deref_requires_lock;
1599 break;
1600 case POK_FunctionCall:
1601 DiagID = diag::warn_fun_requires_lock;
1602 break;
1603 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001604 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1605 << D->getNameAsString()
1606 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001607 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001608 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001609 }
1610
Aaron Ballmane0449042014-04-01 21:43:23 +00001611 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001612 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001613 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1614 << Kind << FunName << LockName);
Richard Smith92286672012-02-03 04:45:26 +00001615 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001616 }
1617};
1618}
1619}
David Blaikie68e081d2011-12-20 02:48:34 +00001620}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001621
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001622//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001623// -Wconsumed
1624//===----------------------------------------------------------------------===//
1625
1626namespace clang {
1627namespace consumed {
1628namespace {
1629class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1630
1631 Sema &S;
1632 DiagList Warnings;
1633
1634public:
1635
1636 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001637
1638 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001639 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
1640
1641 for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
1642 I != E; ++I) {
1643
1644 const OptionalNotes &Notes = I->second;
1645 S.Diag(I->first.first, I->first.second);
1646
1647 for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI) {
1648 S.Diag(Notes[NoteI].first, Notes[NoteI].second);
1649 }
1650 }
1651 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001652
1653 void warnLoopStateMismatch(SourceLocation Loc,
1654 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001655 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1656 VariableName);
1657
1658 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1659 }
1660
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001661 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1662 StringRef VariableName,
1663 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001664 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001665
1666 PartialDiagnosticAt Warning(Loc, S.PDiag(
1667 diag::warn_param_return_typestate_mismatch) << VariableName <<
1668 ExpectedState << ObservedState);
1669
1670 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1671 }
1672
DeLesley Hutchins69391772013-10-17 23:23:53 +00001673 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001674 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001675
1676 PartialDiagnosticAt Warning(Loc, S.PDiag(
1677 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
1678
1679 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1680 }
1681
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001682 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001683 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001684 PartialDiagnosticAt Warning(Loc, S.PDiag(
1685 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
1686
1687 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1688 }
1689
1690 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001691 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001692
1693 PartialDiagnosticAt Warning(Loc, S.PDiag(
1694 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
1695
1696 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1697 }
1698
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001699 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001700 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001701
1702 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001703 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001704
1705 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1706 }
1707
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001708 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001709 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001710
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001711 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1712 MethodName << VariableName << State);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001713
1714 Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
1715 }
1716};
1717}}}
1718
1719//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001720// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1721// warnings on a function, method, or block.
1722//===----------------------------------------------------------------------===//
1723
Ted Kremenek0b405322010-03-23 00:13:23 +00001724clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1725 enableCheckFallThrough = 1;
1726 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001727 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001728 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001729}
1730
Ted Kremenekad8753c2014-03-15 05:47:06 +00001731static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
1732 return (unsigned) D.getDiagnosticLevel(diag, SourceLocation()) !=
1733 DiagnosticsEngine::Ignored;
1734}
1735
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001736clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1737 : S(s),
1738 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001739 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001740 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001741 MaxCFGBlocksPerFunction(0),
1742 NumUninitAnalysisFunctions(0),
1743 NumUninitAnalysisVariables(0),
1744 MaxUninitAnalysisVariablesPerFunction(0),
1745 NumUninitAnalysisBlockVisits(0),
1746 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001747
1748 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001749 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001750
1751 DefaultPolicy.enableCheckUnreachable =
1752 isEnabled(D, warn_unreachable) ||
1753 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001754 isEnabled(D, warn_unreachable_return) ||
1755 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001756
1757 DefaultPolicy.enableThreadSafetyAnalysis =
1758 isEnabled(D, warn_double_lock);
1759
1760 DefaultPolicy.enableConsumedAnalysis =
1761 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001762}
1763
Ted Kremenek3427fac2011-02-23 01:52:04 +00001764static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001765 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremenek3427fac2011-02-23 01:52:04 +00001766 i = fscope->PossiblyUnreachableDiags.begin(),
1767 e = fscope->PossiblyUnreachableDiags.end();
1768 i != e; ++i) {
1769 const sema::PossiblyUnreachableDiag &D = *i;
1770 S.Diag(D.Loc, D.PD);
1771 }
1772}
1773
Ted Kremenek0b405322010-03-23 00:13:23 +00001774void clang::sema::
1775AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001776 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001777 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001778
Ted Kremenek918fe842010-03-20 21:06:02 +00001779 // We avoid doing analysis-based warnings when there are errors for
1780 // two reasons:
1781 // (1) The CFGs often can't be constructed (if the body is invalid), so
1782 // don't bother trying.
1783 // (2) The code already has problems; running the analysis just takes more
1784 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001785 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001786
Ted Kremenek0b405322010-03-23 00:13:23 +00001787 // Do not do any analysis for declarations in system headers if we are
1788 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001789 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001790 S.SourceMgr.isInSystemHeader(D->getLocation()))
1791 return;
1792
John McCall1d570a72010-08-25 05:56:39 +00001793 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001794 if (cast<DeclContext>(D)->isDependentContext())
1795 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001796
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001797 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001798 // Flush out any possibly unreachable diagnostics.
1799 flushDiagnostics(S, fscope);
1800 return;
1801 }
1802
Ted Kremenek918fe842010-03-20 21:06:02 +00001803 const Stmt *Body = D->getBody();
1804 assert(Body);
1805
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001806 // Construct the analysis context with the specified CFG build options.
Jordy Rose4f8198e2012-04-28 01:58:08 +00001807 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001808
Ted Kremenek918fe842010-03-20 21:06:02 +00001809 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001810 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001811 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1812 AC.getCFGBuildOptions().AddEHEdges = false;
1813 AC.getCFGBuildOptions().AddInitializers = true;
1814 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001815 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001816 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Jordan Rose91f78402012-09-05 23:11:06 +00001817
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001818 // Force that certain expressions appear as CFGElements in the CFG. This
1819 // is used to speed up various analyses.
1820 // FIXME: This isn't the right factoring. This is here for initial
1821 // prototyping, but we need a way for analyses to say what expressions they
1822 // expect to always be CFGElements and then fill in the BuildOptions
1823 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001824 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1825 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001826 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001827 AC.getCFGBuildOptions().setAllAlwaysAdd();
1828 }
1829 else {
1830 AC.getCFGBuildOptions()
1831 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001832 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001833 .setAlwaysAdd(Stmt::BlockExprClass)
1834 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1835 .setAlwaysAdd(Stmt::DeclRefExprClass)
1836 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001837 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1838 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001839 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001840
Richard Trieuf935b562014-04-05 05:17:01 +00001841 if (Diags.getDiagnosticLevel(diag::warn_tautological_overlap_comparison,
1842 D->getLocStart())) {
1843 LogicalErrorHandler LEH(S);
1844 AC.getCFGBuildOptions().Observer = &LEH;
1845 AC.getCFG();
1846 AC.getCFGBuildOptions().Observer = 0;
1847 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001848
Ted Kremenek3427fac2011-02-23 01:52:04 +00001849 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001850 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001851 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001852
1853 // Register the expressions with the CFGBuilder.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001854 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001855 i = fscope->PossiblyUnreachableDiags.begin(),
1856 e = fscope->PossiblyUnreachableDiags.end();
1857 i != e; ++i) {
1858 if (const Stmt *stmt = i->stmt)
1859 AC.registerForcedBlockExpression(stmt);
1860 }
1861
1862 if (AC.getCFG()) {
1863 analyzed = true;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001864 for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
Ted Kremeneka099c592011-03-10 03:50:34 +00001865 i = fscope->PossiblyUnreachableDiags.begin(),
1866 e = fscope->PossiblyUnreachableDiags.end();
1867 i != e; ++i)
1868 {
1869 const sema::PossiblyUnreachableDiag &D = *i;
1870 bool processed = false;
1871 if (const Stmt *stmt = i->stmt) {
1872 const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001873 CFGReverseBlockReachabilityAnalysis *cra =
1874 AC.getCFGReachablityAnalysis();
1875 // FIXME: We should be able to assert that block is non-null, but
1876 // the CFG analysis can skip potentially-evaluated expressions in
1877 // edge cases; see test/Sema/vla-2.c.
1878 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001879 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001880 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001881 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001882 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001883 }
1884 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001885 if (!processed) {
1886 // Emit the warning anyway if we cannot map to a basic block.
1887 S.Diag(D.Loc, D.PD);
1888 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001889 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001890 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001891
1892 if (!analyzed)
1893 flushDiagnostics(S, fscope);
1894 }
1895
1896
Ted Kremenek918fe842010-03-20 21:06:02 +00001897 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001898 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001899 const CheckFallThroughDiagnostics &CD =
1900 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001901 : (isa<CXXMethodDecl>(D) &&
1902 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1903 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1904 ? CheckFallThroughDiagnostics::MakeForLambda()
1905 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001906 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001907 }
1908
1909 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001910 if (P.enableCheckUnreachable) {
1911 // Only check for unreachable code on non-template instantiations.
1912 // Different template instantiations can effectively change the control-flow
1913 // and it is very difficult to prove that a snippet of code in a template
1914 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001915 bool isTemplateInstantiation = false;
1916 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1917 isTemplateInstantiation = Function->isTemplateInstantiation();
1918 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001919 CheckUnreachable(S, AC);
1920 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001921
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001922 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00001923 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001924 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00001925 SourceLocation FEL = AC.getDecl()->getLocEnd();
1926 thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00001927 if (Diags.getDiagnosticLevel(diag::warn_thread_safety_beta,D->getLocStart())
1928 != DiagnosticsEngine::Ignored)
1929 Reporter.setIssueBetaWarnings(true);
1930
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001931 thread_safety::runThreadSafetyAnalysis(AC, Reporter);
1932 Reporter.emitDiagnostics();
1933 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001934
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001935 // Check for violations of consumed properties.
1936 if (P.enableConsumedAnalysis) {
1937 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00001938 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001939 Analyzer.run(AC);
1940 }
1941
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001942 if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001943 != DiagnosticsEngine::Ignored ||
Richard Smith4323bf82012-05-25 02:17:09 +00001944 Diags.getDiagnosticLevel(diag::warn_sometimes_uninit_var,D->getLocStart())
1945 != DiagnosticsEngine::Ignored ||
Ted Kremenek1a47f362011-03-15 05:22:28 +00001946 Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
David Blaikie9c902b52011-09-25 23:23:43 +00001947 != DiagnosticsEngine::Ignored) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00001948 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00001949 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00001950 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00001951 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00001952 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001953 reporter, stats);
1954
1955 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
1956 ++NumUninitAnalysisFunctions;
1957 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
1958 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
1959 MaxUninitAnalysisVariablesPerFunction =
1960 std::max(MaxUninitAnalysisVariablesPerFunction,
1961 stats.NumVariablesAnalyzed);
1962 MaxUninitAnalysisBlockVisitsPerFunction =
1963 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
1964 stats.NumBlockVisits);
1965 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001966 }
1967 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001968
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001969 bool FallThroughDiagFull =
1970 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough,
1971 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001972 bool FallThroughDiagPerFunction =
1973 Diags.getDiagnosticLevel(diag::warn_unannotated_fallthrough_per_function,
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001974 D->getLocStart()) != DiagnosticsEngine::Ignored;
Alexis Hunt2178f142012-06-15 21:22:05 +00001975 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001976 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00001977 }
1978
Jordan Rosed3934582012-09-28 22:21:30 +00001979 if (S.getLangOpts().ObjCARCWeak &&
1980 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1981 D->getLocStart()) != DiagnosticsEngine::Ignored)
Jordan Rose76831c62012-10-11 16:10:19 +00001982 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00001983
Richard Trieu2f024f42013-12-21 02:33:43 +00001984
1985 // Check for infinite self-recursion in functions
1986 if (Diags.getDiagnosticLevel(diag::warn_infinite_recursive_function,
1987 D->getLocStart())
1988 != DiagnosticsEngine::Ignored) {
1989 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1990 checkRecursiveFunction(S, FD, Body, AC);
1991 }
1992 }
1993
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001994 // Collect statistics about the CFG if it was built.
1995 if (S.CollectStats && AC.isCFGBuilt()) {
1996 ++NumFunctionsAnalyzed;
1997 if (CFG *cfg = AC.getCFG()) {
1998 // If we successfully built a CFG for this context, record some more
1999 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002000 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002001 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002002 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002003 } else {
2004 ++NumFunctionsWithBadCFGs;
2005 }
2006 }
2007}
2008
2009void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2010 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2011
2012 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2013 unsigned AvgCFGBlocksPerFunction =
2014 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2015 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2016 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2017 << " " << NumCFGBlocks << " CFG blocks built.\n"
2018 << " " << AvgCFGBlocksPerFunction
2019 << " average CFG blocks per function.\n"
2020 << " " << MaxCFGBlocksPerFunction
2021 << " max CFG blocks per function.\n";
2022
2023 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2024 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2025 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2026 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2027 llvm::errs() << NumUninitAnalysisFunctions
2028 << " functions analyzed for uninitialiazed variables\n"
2029 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2030 << " " << AvgUninitVariablesPerFunction
2031 << " average variables per function.\n"
2032 << " " << MaxUninitAnalysisVariablesPerFunction
2033 << " max variables per function.\n"
2034 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2035 << " " << AvgUninitBlockVisitsPerFunction
2036 << " average block visits per function.\n"
2037 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2038 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002039}