blob: 94ec7961d3ef910ec87f6acbbde641f2b2058441 [file] [log] [blame]
Ted Kremenek918fe842010-03-20 21:06:02 +00001//=- AnalysisBasedWarnings.cpp - Sema warnings based on libAnalysis -*- C++ -*-=//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines analysis_warnings::[Policy,Executor].
11// Together they are used by Sema to issue warnings based on inexpensive
12// static analysis algorithms in libAnalysis.
13//
14//===----------------------------------------------------------------------===//
15
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000016#include "clang/Sema/AnalysisBasedWarnings.h"
John McCall28a0cf72010-08-25 07:42:41 +000017#include "clang/AST/DeclCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000018#include "clang/AST/DeclObjC.h"
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +000019#include "clang/AST/EvaluatedExprVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000020#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
Jordan Rose76831c62012-10-11 16:10:19 +000022#include "clang/AST/ParentMap.h"
Richard Smith84837d52012-05-03 18:27:39 +000023#include "clang/AST/RecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/StmtCXX.h"
25#include "clang/AST/StmtObjC.h"
26#include "clang/AST/StmtVisitor.h"
27#include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
DeLesley Hutchins48a31762013-08-12 21:20:55 +000028#include "clang/Analysis/Analyses/Consumed.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Analysis/Analyses/ReachableCode.h"
30#include "clang/Analysis/Analyses/ThreadSafety.h"
31#include "clang/Analysis/Analyses/UninitializedValues.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000032#include "clang/Analysis/AnalysisContext.h"
33#include "clang/Analysis/CFG.h"
Ted Kremenek3427fac2011-02-23 01:52:04 +000034#include "clang/Analysis/CFGStmtMap.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Basic/SourceLocation.h"
36#include "clang/Basic/SourceManager.h"
37#include "clang/Lex/Lexer.h"
38#include "clang/Lex/Preprocessor.h"
39#include "clang/Sema/ScopeInfo.h"
40#include "clang/Sema/SemaInternal.h"
Alexander Kornienkoe61e5622012-09-28 22:24:03 +000041#include "llvm/ADT/ArrayRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000042#include "llvm/ADT/BitVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/FoldingSet.h"
44#include "llvm/ADT/ImmutableMap.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000045#include "llvm/ADT/MapVector.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include "llvm/ADT/PostOrderIterator.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000047#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000048#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000049#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000050#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000051#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000053#include <iterator>
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000054#include <vector>
Ted Kremenek918fe842010-03-20 21:06:02 +000055
56using namespace clang;
57
58//===----------------------------------------------------------------------===//
59// Unreachable code analysis.
60//===----------------------------------------------------------------------===//
61
62namespace {
63 class UnreachableCodeHandler : public reachable_code::Callback {
64 Sema &S;
65 public:
66 UnreachableCodeHandler(Sema &s) : S(s) {}
67
Ted Kremenek1a8641c2014-03-15 01:26:32 +000068 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000069 SourceLocation L,
70 SourceRange SilenceableCondVal,
71 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000072 SourceRange R2) override {
Ted Kremenek1a8641c2014-03-15 01:26:32 +000073 unsigned diag = diag::warn_unreachable;
74 switch (UK) {
75 case reachable_code::UK_Break:
76 diag = diag::warn_unreachable_break;
77 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000078 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000079 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000080 break;
Ted Kremenek14210372014-03-21 06:02:36 +000081 case reachable_code::UK_Loop_Increment:
82 diag = diag::warn_unreachable_loop_increment;
83 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 case reachable_code::UK_Other:
85 break;
86 }
87
88 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000089
90 SourceLocation Open = SilenceableCondVal.getBegin();
91 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000092 SourceLocation Close = SilenceableCondVal.getEnd();
93 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000094 if (Close.isValid()) {
95 S.Diag(Open, diag::note_unreachable_silence)
96 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
97 << FixItHint::CreateInsertion(Close, ")");
98 }
99 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000100 }
101 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000102} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +0000103
104/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000105static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000106 // As a heuristic prune all diagnostics not in the main file. Currently
107 // the majority of warnings in headers are false positives. These
108 // are largely caused by configuration state, e.g. preprocessor
109 // defined code, etc.
110 //
111 // Note that this is also a performance optimization. Analyzing
112 // headers many times can be expensive.
113 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
114 return;
115
Ted Kremenek918fe842010-03-20 21:06:02 +0000116 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000117 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000118}
119
Benjamin Kramer3a002252015-02-16 16:53:12 +0000120namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000121/// \brief Warn on logical operator errors in CFGBuilder
122class LogicalErrorHandler : public CFGCallback {
123 Sema &S;
124
125public:
126 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
127
128 static bool HasMacroID(const Expr *E) {
129 if (E->getExprLoc().isMacroID())
130 return true;
131
132 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000133 for (const Stmt *SubStmt : E->children())
134 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
135 if (HasMacroID(SubExpr))
136 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000137
138 return false;
139 }
140
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000141 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000142 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 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000149
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000150 void compareBitwiseEquality(const BinaryOperator *B,
151 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000152 if (HasMacroID(B))
153 return;
154
155 SourceRange DiagRange = B->getSourceRange();
156 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
157 << DiagRange << isAlwaysTrue;
158 }
Richard Trieuf935b562014-04-05 05:17:01 +0000159};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000160} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000161
Ted Kremenek918fe842010-03-20 21:06:02 +0000162//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000163// Check for infinite self-recursion in functions
164//===----------------------------------------------------------------------===//
165
Richard Trieu6995de92015-08-21 03:43:09 +0000166// Returns true if the function is called anywhere within the CFGBlock.
167// For member functions, the additional condition of being call from the
168// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000169static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000170 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000171 for (const auto &B : Block) {
172 if (B.getKind() != CFGElement::Statement)
173 continue;
174
175 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
176 if (!CE || !CE->getCalleeDecl() ||
177 CE->getCalleeDecl()->getCanonicalDecl() != FD)
178 continue;
179
180 // Skip function calls which are qualified with a templated class.
181 if (const DeclRefExpr *DRE =
182 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
183 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
184 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
185 isa<TemplateSpecializationType>(NNS->getAsType())) {
186 continue;
187 }
188 }
189 }
190
191 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
192 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
193 !MCE->getMethodDecl()->isVirtual())
194 return true;
195 }
196 return false;
197}
198
Richard Trieu6995de92015-08-21 03:43:09 +0000199// All blocks are in one of three states. States are ordered so that blocks
200// can only move to higher states.
201enum RecursiveState {
202 FoundNoPath,
203 FoundPath,
204 FoundPathWithNoRecursiveCall
205};
206
207// Returns true if there exists a path to the exit block and every path
208// to the exit block passes through a call to FD.
209static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
210
211 const unsigned ExitID = cfg->getExit().getBlockID();
212
213 // Mark all nodes as FoundNoPath, then set the status of the entry block.
214 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
215 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
216
217 // Make the processing stack and seed it with the entry block.
218 SmallVector<CFGBlock *, 16> Stack;
219 Stack.push_back(&cfg->getEntry());
Richard Trieu2f024f42013-12-21 02:33:43 +0000220
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000221 while (!Stack.empty()) {
Richard Trieu6995de92015-08-21 03:43:09 +0000222 CFGBlock *CurBlock = Stack.back();
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000223 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000224
Richard Trieu6995de92015-08-21 03:43:09 +0000225 unsigned ID = CurBlock->getBlockID();
226 RecursiveState CurState = States[ID];
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000227
228 if (CurState == FoundPathWithNoRecursiveCall) {
229 // Found a path to the exit node without a recursive call.
230 if (ExitID == ID)
Richard Trieu6995de92015-08-21 03:43:09 +0000231 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000232
Richard Trieu6995de92015-08-21 03:43:09 +0000233 // Only change state if the block has a recursive call.
234 if (hasRecursiveCallInPath(FD, *CurBlock))
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000235 CurState = FoundPath;
236 }
237
Richard Trieu6995de92015-08-21 03:43:09 +0000238 // Loop over successor blocks and add them to the Stack if their state
239 // changes.
240 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
241 if (*I) {
242 unsigned next_ID = (*I)->getBlockID();
243 if (States[next_ID] < CurState) {
244 States[next_ID] = CurState;
245 Stack.push_back(*I);
246 }
247 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000248 }
Richard Trieu6995de92015-08-21 03:43:09 +0000249
250 // Return true if the exit node is reachable, and only reachable through
251 // a recursive call.
252 return States[ExitID] == FoundPath;
Richard Trieu2f024f42013-12-21 02:33:43 +0000253}
254
255static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000256 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000257 FD = FD->getCanonicalDecl();
258
259 // Only run on non-templated functions and non-templated members of
260 // templated classes.
261 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
262 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
263 return;
264
265 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000266 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000267
268 // If the exit block is unreachable, skip processing the function.
269 if (cfg->getExit().pred_empty())
270 return;
271
Richard Trieu6995de92015-08-21 03:43:09 +0000272 // Emit diagnostic if a recursive function call is detected for all paths.
273 if (checkForRecursiveFunctionCall(FD, cfg))
Richard Trieu2f024f42013-12-21 02:33:43 +0000274 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
275}
276
277//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000278// Check for missing return value.
279//===----------------------------------------------------------------------===//
280
John McCall5c6ec8c2010-05-16 09:34:11 +0000281enum ControlFlowKind {
282 UnknownFallThrough,
283 NeverFallThrough,
284 MaybeFallThrough,
285 AlwaysFallThrough,
286 NeverFallThroughOrReturn
287};
Ted Kremenek918fe842010-03-20 21:06:02 +0000288
289/// CheckFallThrough - Check that we don't fall off the end of a
290/// Statement that should return a value.
291///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000292/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
293/// MaybeFallThrough iff we might or might not fall off the end,
294/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
295/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000296/// statement but we may return. We assume that functions not marked noreturn
297/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000298static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000299 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000300 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000301
302 // The CFG leaves in dead things, and we don't want the dead code paths to
303 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000304 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000305 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000306 live);
307
308 bool AddEHEdges = AC.getAddEHEdges();
309 if (!AddEHEdges && count != cfg->getNumBlockIDs())
310 // When there are things remaining dead, and we didn't add EH edges
311 // from CallExprs to the catch clauses, we have to go back and
312 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000313 for (const auto *B : *cfg) {
314 if (!live[B->getBlockID()]) {
315 if (B->pred_begin() == B->pred_end()) {
316 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000317 // When not adding EH edges from calls, catch clauses
318 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000319 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000320 continue;
321 }
322 }
323 }
324
325 // Now we know what is live, we check the live precessors of the exit block
326 // and look for fall through paths, being careful to ignore normal returns,
327 // and exceptional paths.
328 bool HasLiveReturn = false;
329 bool HasFakeEdge = false;
330 bool HasPlainEdge = false;
331 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000332
333 // Ignore default cases that aren't likely to be reachable because all
334 // enums in a switch(X) have explicit case statements.
335 CFGBlock::FilterOptions FO;
336 FO.IgnoreDefaultsWithCoveredEnums = 1;
337
338 for (CFGBlock::filtered_pred_iterator
339 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
340 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000341 if (!live[B.getBlockID()])
342 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000343
Chandler Carruth03faf782011-09-13 09:53:58 +0000344 // Skip blocks which contain an element marked as no-return. They don't
345 // represent actually viable edges into the exit block, so mark them as
346 // abnormal.
347 if (B.hasNoReturnElement()) {
348 HasAbnormalEdge = true;
349 continue;
350 }
351
Ted Kremenek5d068492011-01-26 04:49:52 +0000352 // Destructors can appear after the 'return' in the CFG. This is
353 // normal. We need to look pass the destructors for the return
354 // statement (if it exists).
355 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000356
Chandler Carruth03faf782011-09-13 09:53:58 +0000357 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000358 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000359 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000360
Ted Kremenek5d068492011-01-26 04:49:52 +0000361 // No more CFGElements in the block?
362 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000363 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
364 HasAbnormalEdge = true;
365 continue;
366 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000367 // A labeled empty statement, or the entry block...
368 HasPlainEdge = true;
369 continue;
370 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000371
David Blaikie2a01f5d2013-02-21 20:58:29 +0000372 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000373 const Stmt *S = CS.getStmt();
Ted Kremenek918fe842010-03-20 21:06:02 +0000374 if (isa<ReturnStmt>(S)) {
375 HasLiveReturn = true;
376 continue;
377 }
378 if (isa<ObjCAtThrowStmt>(S)) {
379 HasFakeEdge = true;
380 continue;
381 }
382 if (isa<CXXThrowExpr>(S)) {
383 HasFakeEdge = true;
384 continue;
385 }
Chad Rosier32503022012-06-11 20:47:18 +0000386 if (isa<MSAsmStmt>(S)) {
387 // TODO: Verify this is correct.
388 HasFakeEdge = true;
389 HasLiveReturn = true;
390 continue;
391 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000392 if (isa<CXXTryStmt>(S)) {
393 HasAbnormalEdge = true;
394 continue;
395 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000396 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
397 == B.succ_end()) {
398 HasAbnormalEdge = true;
399 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000400 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000401
402 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000403 }
404 if (!HasPlainEdge) {
405 if (HasLiveReturn)
406 return NeverFallThrough;
407 return NeverFallThroughOrReturn;
408 }
409 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
410 return MaybeFallThrough;
411 // This says AlwaysFallThrough for calls to functions that are not marked
412 // noreturn, that don't return. If people would like this warning to be more
413 // accurate, such functions should be marked as noreturn.
414 return AlwaysFallThrough;
415}
416
Dan Gohman28ade552010-07-26 21:25:24 +0000417namespace {
418
Ted Kremenek918fe842010-03-20 21:06:02 +0000419struct CheckFallThroughDiagnostics {
420 unsigned diag_MaybeFallThrough_HasNoReturn;
421 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
422 unsigned diag_AlwaysFallThrough_HasNoReturn;
423 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
424 unsigned diag_NeverFallThroughOrReturn;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000425 enum { Function, Block, Lambda } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000426 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000427
Douglas Gregor24f27692010-04-16 23:28:44 +0000428 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000429 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000430 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000431 D.diag_MaybeFallThrough_HasNoReturn =
432 diag::warn_falloff_noreturn_function;
433 D.diag_MaybeFallThrough_ReturnsNonVoid =
434 diag::warn_maybe_falloff_nonvoid_function;
435 D.diag_AlwaysFallThrough_HasNoReturn =
436 diag::warn_falloff_noreturn_function;
437 D.diag_AlwaysFallThrough_ReturnsNonVoid =
438 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000439
440 // Don't suggest that virtual functions be marked "noreturn", since they
441 // might be overridden by non-noreturn functions.
442 bool isVirtualMethod = false;
443 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
444 isVirtualMethod = Method->isVirtual();
445
Douglas Gregor0de57202011-10-10 18:15:57 +0000446 // Don't suggest that template instantiations be marked "noreturn"
447 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000448 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
449 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000450
451 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000452 D.diag_NeverFallThroughOrReturn =
453 diag::warn_suggest_noreturn_function;
454 else
455 D.diag_NeverFallThroughOrReturn = 0;
456
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000457 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000458 return D;
459 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000460
Ted Kremenek918fe842010-03-20 21:06:02 +0000461 static CheckFallThroughDiagnostics MakeForBlock() {
462 CheckFallThroughDiagnostics D;
463 D.diag_MaybeFallThrough_HasNoReturn =
464 diag::err_noreturn_block_has_return_expr;
465 D.diag_MaybeFallThrough_ReturnsNonVoid =
466 diag::err_maybe_falloff_nonvoid_block;
467 D.diag_AlwaysFallThrough_HasNoReturn =
468 diag::err_noreturn_block_has_return_expr;
469 D.diag_AlwaysFallThrough_ReturnsNonVoid =
470 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000471 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000472 D.funMode = Block;
473 return D;
474 }
475
476 static CheckFallThroughDiagnostics MakeForLambda() {
477 CheckFallThroughDiagnostics D;
478 D.diag_MaybeFallThrough_HasNoReturn =
479 diag::err_noreturn_lambda_has_return_expr;
480 D.diag_MaybeFallThrough_ReturnsNonVoid =
481 diag::warn_maybe_falloff_nonvoid_lambda;
482 D.diag_AlwaysFallThrough_HasNoReturn =
483 diag::err_noreturn_lambda_has_return_expr;
484 D.diag_AlwaysFallThrough_ReturnsNonVoid =
485 diag::warn_falloff_nonvoid_lambda;
486 D.diag_NeverFallThroughOrReturn = 0;
487 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000488 return D;
489 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000490
David Blaikie9c902b52011-09-25 23:23:43 +0000491 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000492 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000493 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000494 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000495 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
496 FuncLoc)) &&
497 (!HasNoReturn ||
498 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
499 FuncLoc)) &&
500 (!ReturnsVoid ||
501 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000502 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000503
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000504 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000505 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000506 }
507};
508
Hans Wennborgdcfba332015-10-06 23:40:43 +0000509} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000510
Ted Kremenek918fe842010-03-20 21:06:02 +0000511/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
512/// function that should return a value. Check that we don't fall off the end
513/// of a noreturn function. We assume that functions and blocks not marked
514/// noreturn will return.
515static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000516 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000517 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000518 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000519
520 bool ReturnsVoid = false;
521 bool HasNoReturn = false;
522
523 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000524 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000525 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000526 }
527 else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000528 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000529 HasNoReturn = MD->hasAttr<NoReturnAttr>();
530 }
531 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000532 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000533 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000534 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000535 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000536 ReturnsVoid = true;
537 if (FT->getNoReturnAttr())
538 HasNoReturn = true;
539 }
540 }
541
David Blaikie9c902b52011-09-25 23:23:43 +0000542 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000543
544 // Short circuit for compilation speed.
545 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
546 return;
Ted Kremenek0b405322010-03-23 00:13:23 +0000547
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000548 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
549 // Either in a function body compound statement, or a function-try-block.
550 switch (CheckFallThrough(AC)) {
551 case UnknownFallThrough:
552 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000553
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000554 case MaybeFallThrough:
555 if (HasNoReturn)
556 S.Diag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
557 else if (!ReturnsVoid)
558 S.Diag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
559 break;
560 case AlwaysFallThrough:
561 if (HasNoReturn)
562 S.Diag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
563 else if (!ReturnsVoid)
564 S.Diag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
565 break;
566 case NeverFallThroughOrReturn:
567 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
568 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
569 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
570 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
571 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
572 } else {
573 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000574 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000575 }
576 break;
577 case NeverFallThrough:
578 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000579 }
580}
581
582//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000583// -Wuninitialized
584//===----------------------------------------------------------------------===//
585
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000586namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000587/// ContainsReference - A visitor class to search for references to
588/// a particular declaration (the needle) within any evaluated component of an
589/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000590class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000591 bool FoundReference;
592 const DeclRefExpr *Needle;
593
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000594public:
Scott Douglass503fc392015-06-10 13:53:15 +0000595 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000596
Scott Douglass503fc392015-06-10 13:53:15 +0000597 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
598 : Inherited(Context), FoundReference(false), Needle(Needle) {}
599
600 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000601 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000602 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000603 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000604
Scott Douglass503fc392015-06-10 13:53:15 +0000605 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000606 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000607
Scott Douglass503fc392015-06-10 13:53:15 +0000608 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000609 if (E == Needle)
610 FoundReference = true;
611 else
Scott Douglass503fc392015-06-10 13:53:15 +0000612 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000613 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000614
615 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000616};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000617} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000618
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000619static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000620 QualType VariableTy = VD->getType().getCanonicalType();
621 if (VariableTy->isBlockPointerType() &&
622 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000623 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
624 << VD->getDeclName()
625 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000626 return true;
627 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000628
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000629 // Don't issue a fixit if there is already an initializer.
630 if (VD->getInit())
631 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000632
633 // Don't suggest a fixit inside macros.
634 if (VD->getLocEnd().isMacroID())
635 return false;
636
Alp Tokerb6cc5922014-05-03 03:45:55 +0000637 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000638
639 // Suggest possible initialization (if any).
640 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
641 if (Init.empty())
642 return false;
643
Richard Smith8d06f422012-01-12 23:53:29 +0000644 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
645 << FixItHint::CreateInsertion(Loc, Init);
646 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000647}
648
Richard Smith1bb8edb82012-05-26 06:20:46 +0000649/// Create a fixit to remove an if-like statement, on the assumption that its
650/// condition is CondVal.
651static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
652 const Stmt *Else, bool CondVal,
653 FixItHint &Fixit1, FixItHint &Fixit2) {
654 if (CondVal) {
655 // If condition is always true, remove all but the 'then'.
656 Fixit1 = FixItHint::CreateRemoval(
657 CharSourceRange::getCharRange(If->getLocStart(),
658 Then->getLocStart()));
659 if (Else) {
660 SourceLocation ElseKwLoc = Lexer::getLocForEndOfToken(
661 Then->getLocEnd(), 0, S.getSourceManager(), S.getLangOpts());
662 Fixit2 = FixItHint::CreateRemoval(
663 SourceRange(ElseKwLoc, Else->getLocEnd()));
664 }
665 } else {
666 // If condition is always false, remove all but the 'else'.
667 if (Else)
668 Fixit1 = FixItHint::CreateRemoval(
669 CharSourceRange::getCharRange(If->getLocStart(),
670 Else->getLocStart()));
671 else
672 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
673 }
674}
675
676/// DiagUninitUse -- Helper function to produce a diagnostic for an
677/// uninitialized use of a variable.
678static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
679 bool IsCapturedByBlock) {
680 bool Diagnosed = false;
681
Richard Smithba8071e2013-09-12 18:49:10 +0000682 switch (Use.getKind()) {
683 case UninitUse::Always:
684 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
685 << VD->getDeclName() << IsCapturedByBlock
686 << Use.getUser()->getSourceRange();
687 return;
688
689 case UninitUse::AfterDecl:
690 case UninitUse::AfterCall:
691 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
692 << VD->getDeclName() << IsCapturedByBlock
693 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
694 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
695 << VD->getSourceRange();
696 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
697 << IsCapturedByBlock << Use.getUser()->getSourceRange();
698 return;
699
700 case UninitUse::Maybe:
701 case UninitUse::Sometimes:
702 // Carry on to report sometimes-uninitialized branches, if possible,
703 // or a 'may be used uninitialized' diagnostic otherwise.
704 break;
705 }
706
Richard Smith1bb8edb82012-05-26 06:20:46 +0000707 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000708 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
709 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000710 assert(Use.getKind() == UninitUse::Sometimes);
711
712 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000713 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000714
715 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000716 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000717 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000718 SourceRange Range;
719
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000720 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000721 // For all binary terminators, branch 0 is taken if the condition is true,
722 // and branch 1 is taken if the condition is false.
723 int RemoveDiagKind = -1;
724 const char *FixitStr =
725 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
726 : (I->Output ? "1" : "0");
727 FixItHint Fixit1, Fixit2;
728
Richard Smithba8071e2013-09-12 18:49:10 +0000729 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000730 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000731 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000732 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000733 continue;
734
735 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000736 case Stmt::IfStmtClass: {
737 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000738 DiagKind = 0;
739 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000740 Range = IS->getCond()->getSourceRange();
741 RemoveDiagKind = 0;
742 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
743 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000744 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000745 }
746 case Stmt::ConditionalOperatorClass: {
747 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000748 DiagKind = 0;
749 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000750 Range = CO->getCond()->getSourceRange();
751 RemoveDiagKind = 0;
752 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
753 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000754 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000755 }
Richard Smith4323bf82012-05-25 02:17:09 +0000756 case Stmt::BinaryOperatorClass: {
757 const BinaryOperator *BO = cast<BinaryOperator>(Term);
758 if (!BO->isLogicalOp())
759 continue;
760 DiagKind = 0;
761 Str = BO->getOpcodeStr();
762 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000763 RemoveDiagKind = 0;
764 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
765 (BO->getOpcode() == BO_LOr && !I->Output))
766 // true && y -> y, false || y -> y.
767 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
768 BO->getOperatorLoc()));
769 else
770 // false && y -> false, true || y -> true.
771 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000772 break;
773 }
774
775 // "loop is entered / loop is exited".
776 case Stmt::WhileStmtClass:
777 DiagKind = 1;
778 Str = "while";
779 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000780 RemoveDiagKind = 1;
781 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000782 break;
783 case Stmt::ForStmtClass:
784 DiagKind = 1;
785 Str = "for";
786 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000787 RemoveDiagKind = 1;
788 if (I->Output)
789 Fixit1 = FixItHint::CreateRemoval(Range);
790 else
791 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000792 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000793 case Stmt::CXXForRangeStmtClass:
794 if (I->Output == 1) {
795 // The use occurs if a range-based for loop's body never executes.
796 // That may be impossible, and there's no syntactic fix for this,
797 // so treat it as a 'may be uninitialized' case.
798 continue;
799 }
800 DiagKind = 1;
801 Str = "for";
802 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
803 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000804
805 // "condition is true / loop is exited".
806 case Stmt::DoStmtClass:
807 DiagKind = 2;
808 Str = "do";
809 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000810 RemoveDiagKind = 1;
811 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000812 break;
813
814 // "switch case is taken".
815 case Stmt::CaseStmtClass:
816 DiagKind = 3;
817 Str = "case";
818 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
819 break;
820 case Stmt::DefaultStmtClass:
821 DiagKind = 3;
822 Str = "default";
823 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
824 break;
825 }
826
Richard Smith1bb8edb82012-05-26 06:20:46 +0000827 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
828 << VD->getDeclName() << IsCapturedByBlock << DiagKind
829 << Str << I->Output << Range;
830 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
831 << IsCapturedByBlock << User->getSourceRange();
832 if (RemoveDiagKind != -1)
833 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
834 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
835
836 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +0000837 }
Richard Smith1bb8edb82012-05-26 06:20:46 +0000838
839 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +0000840 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +0000841 << VD->getDeclName() << IsCapturedByBlock
842 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +0000843}
844
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000845/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
846/// uninitialized variable. This manages the different forms of diagnostic
847/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +0000848/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000849/// false.
850static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +0000851 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +0000852 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +0000853 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +0000854 // Inspect the initializer of the variable declaration which is
855 // being referenced prior to its initialization. We emit
856 // specialized diagnostics for self-initialization, and we
857 // specifically avoid warning about self references which take the
858 // form of:
859 //
860 // int x = x;
861 //
862 // This is used to indicate to GCC that 'x' is intentionally left
863 // uninitialized. Proven code paths which access 'x' in
864 // an uninitialized state after this will still warn.
865 if (const Expr *Initializer = VD->getInit()) {
866 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
867 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +0000868
Richard Trieu43a2fc72012-05-09 21:08:22 +0000869 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +0000870 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +0000871 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +0000872 S.Diag(DRE->getLocStart(),
873 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +0000874 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
875 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +0000876 }
Chandler Carruth895904da2011-04-05 18:18:05 +0000877 }
Richard Trieu43a2fc72012-05-09 21:08:22 +0000878
Richard Smith1bb8edb82012-05-26 06:20:46 +0000879 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +0000880 } else {
Richard Smith4323bf82012-05-25 02:17:09 +0000881 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000882 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
883 S.Diag(BE->getLocStart(),
884 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000885 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000886 else
887 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +0000888 }
889
890 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000891 // the initializer of that declaration & we didn't already suggest
892 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +0000893 if (!SuggestInitializationFixit(S, VD))
Chandler Carruth895904da2011-04-05 18:18:05 +0000894 S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
895 << VD->getDeclName();
896
Chandler Carruthdd8f0d02011-04-05 18:27:05 +0000897 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +0000898}
899
Richard Smith84837d52012-05-03 18:27:39 +0000900namespace {
901 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
902 public:
903 FallthroughMapper(Sema &S)
904 : FoundSwitchStatements(false),
905 S(S) {
906 }
907
908 bool foundSwitchStatements() const { return FoundSwitchStatements; }
909
910 void markFallthroughVisited(const AttributedStmt *Stmt) {
911 bool Found = FallthroughStmts.erase(Stmt);
912 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +0000913 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +0000914 }
915
916 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
917
918 const AttrStmts &getFallthroughStmts() const {
919 return FallthroughStmts;
920 }
921
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000922 void fillReachableBlocks(CFG *Cfg) {
923 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
924 std::deque<const CFGBlock *> BlockQueue;
925
926 ReachableBlocks.insert(&Cfg->getEntry());
927 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000928 // Mark all case blocks reachable to avoid problems with switching on
929 // constants, covered enums, etc.
930 // These blocks can contain fall-through annotations, and we don't want to
931 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +0000932 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000933 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +0000934 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000935 BlockQueue.push_back(B);
936 }
937
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000938 while (!BlockQueue.empty()) {
939 const CFGBlock *P = BlockQueue.front();
940 BlockQueue.pop_front();
941 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
942 E = P->succ_end();
943 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +0000944 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000945 BlockQueue.push_back(*I);
946 }
947 }
948 }
949
Richard Smith84837d52012-05-03 18:27:39 +0000950 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000951 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
952
Richard Smith84837d52012-05-03 18:27:39 +0000953 int UnannotatedCnt = 0;
954 AnnotatedCnt = 0;
955
Aaron Ballmane5195222014-05-15 20:50:47 +0000956 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +0000957 while (!BlockQueue.empty()) {
958 const CFGBlock *P = BlockQueue.front();
959 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +0000960 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +0000961
962 const Stmt *Term = P->getTerminator();
963 if (Term && isa<SwitchStmt>(Term))
964 continue; // Switch statement, good.
965
966 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
967 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
968 continue; // Previous case label has no statements, good.
969
Alexander Kornienko09f15f32013-01-25 20:44:56 +0000970 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
971 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
972 continue; // Case label is preceded with a normal label, good.
973
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +0000974 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000975 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
976 ElemEnd = P->rend();
977 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +0000978 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
979 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith84837d52012-05-03 18:27:39 +0000980 S.Diag(AS->getLocStart(),
981 diag::warn_fallthrough_attr_unreachable);
982 markFallthroughVisited(AS);
983 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +0000984 break;
Richard Smith84837d52012-05-03 18:27:39 +0000985 }
986 // Don't care about other unreachable statements.
987 }
988 }
989 // If there are no unreachable statements, this may be a special
990 // case in CFG:
991 // case X: {
992 // A a; // A has a destructor.
993 // break;
994 // }
995 // // <<<< This place is represented by a 'hanging' CFG block.
996 // case Y:
997 continue;
998 }
999
1000 const Stmt *LastStmt = getLastStmt(*P);
1001 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1002 markFallthroughVisited(AS);
1003 ++AnnotatedCnt;
1004 continue; // Fallthrough annotation, good.
1005 }
1006
1007 if (!LastStmt) { // This block contains no executable statements.
1008 // Traverse its predecessors.
1009 std::copy(P->pred_begin(), P->pred_end(),
1010 std::back_inserter(BlockQueue));
1011 continue;
1012 }
1013
1014 ++UnannotatedCnt;
1015 }
1016 return !!UnannotatedCnt;
1017 }
1018
1019 // RecursiveASTVisitor setup.
1020 bool shouldWalkTypesOfTypeLocs() const { return false; }
1021
1022 bool VisitAttributedStmt(AttributedStmt *S) {
1023 if (asFallThroughAttr(S))
1024 FallthroughStmts.insert(S);
1025 return true;
1026 }
1027
1028 bool VisitSwitchStmt(SwitchStmt *S) {
1029 FoundSwitchStatements = true;
1030 return true;
1031 }
1032
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001033 // We don't want to traverse local type declarations. We analyze their
1034 // methods separately.
1035 bool TraverseDecl(Decl *D) { return true; }
1036
Alexander Kornienkobf911642014-06-24 15:28:21 +00001037 // We analyze lambda bodies separately. Skip them here.
1038 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1039
Richard Smith84837d52012-05-03 18:27:39 +00001040 private:
1041
1042 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1043 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1044 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1045 return AS;
1046 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001047 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001048 }
1049
1050 static const Stmt *getLastStmt(const CFGBlock &B) {
1051 if (const Stmt *Term = B.getTerminator())
1052 return Term;
1053 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1054 ElemEnd = B.rend();
1055 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001056 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1057 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001058 }
1059 // Workaround to detect a statement thrown out by CFGBuilder:
1060 // case X: {} case Y:
1061 // case X: ; case Y:
1062 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1063 if (!isa<SwitchCase>(SW->getSubStmt()))
1064 return SW->getSubStmt();
1065
Craig Topperc3ec1492014-05-26 06:22:03 +00001066 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001067 }
1068
1069 bool FoundSwitchStatements;
1070 AttrStmts FallthroughStmts;
1071 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001072 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001073 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001074} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001075
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001076static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001077 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001078 // Only perform this analysis when using C++11. There is no good workflow
1079 // for this warning when not using C++11. There is no good way to silence
1080 // the warning (no attribute is available) unless we are using C++11's support
1081 // for generalized attributes. Once could use pragmas to silence the warning,
1082 // but as a general solution that is gross and not in the spirit of this
1083 // warning.
1084 //
1085 // NOTE: This an intermediate solution. There are on-going discussions on
1086 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001087 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001088 return;
1089
Richard Smith84837d52012-05-03 18:27:39 +00001090 FallthroughMapper FM(S);
1091 FM.TraverseStmt(AC.getBody());
1092
1093 if (!FM.foundSwitchStatements())
1094 return;
1095
Alexis Hunt2178f142012-06-15 21:22:05 +00001096 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001097 return;
1098
Richard Smith84837d52012-05-03 18:27:39 +00001099 CFG *Cfg = AC.getCFG();
1100
1101 if (!Cfg)
1102 return;
1103
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001104 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001105
Pete Cooper57d3f142015-07-30 17:22:52 +00001106 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001107 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001108
1109 if (!Label || !isa<SwitchCase>(Label))
1110 continue;
1111
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001112 int AnnotatedCnt;
1113
Alexander Kornienko55488792013-01-25 15:49:34 +00001114 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt))
Richard Smith84837d52012-05-03 18:27:39 +00001115 continue;
1116
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001117 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001118 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1119 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001120
1121 if (!AnnotatedCnt) {
1122 SourceLocation L = Label->getLocStart();
1123 if (L.isMacroID())
1124 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001125 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001126 const Stmt *Term = B->getTerminator();
1127 // Skip empty cases.
1128 while (B->empty() && !Term && B->succ_size() == 1) {
1129 B = *B->succ_begin();
1130 Term = B->getTerminator();
1131 }
1132 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001133 Preprocessor &PP = S.getPreprocessor();
1134 TokenValue Tokens[] = {
1135 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1136 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1137 tok::r_square, tok::r_square
1138 };
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001139 StringRef AnnotationSpelling = "[[clang::fallthrough]]";
1140 StringRef MacroName = PP.getLastMacroWithSpelling(L, Tokens);
1141 if (!MacroName.empty())
1142 AnnotationSpelling = MacroName;
1143 SmallString<64> TextToInsert(AnnotationSpelling);
1144 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001145 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001146 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001147 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001148 }
Richard Smith84837d52012-05-03 18:27:39 +00001149 }
1150 S.Diag(L, diag::note_insert_break_fixit) <<
1151 FixItHint::CreateInsertion(L, "break; ");
1152 }
1153 }
1154
Aaron Ballmane5195222014-05-15 20:50:47 +00001155 for (const auto *F : FM.getFallthroughStmts())
1156 S.Diag(F->getLocStart(), diag::warn_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001157}
1158
Jordan Rose25c0ea82012-10-29 17:46:47 +00001159static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1160 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001161 assert(S);
1162
1163 do {
1164 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001165 case Stmt::ForStmtClass:
1166 case Stmt::WhileStmtClass:
1167 case Stmt::CXXForRangeStmtClass:
1168 case Stmt::ObjCForCollectionStmtClass:
1169 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001170 case Stmt::DoStmtClass: {
1171 const Expr *Cond = cast<DoStmt>(S)->getCond();
1172 llvm::APSInt Val;
1173 if (!Cond->EvaluateAsInt(Val, Ctx))
1174 return true;
1175 return Val.getBoolValue();
1176 }
Jordan Rose76831c62012-10-11 16:10:19 +00001177 default:
1178 break;
1179 }
1180 } while ((S = PM.getParent(S)));
1181
1182 return false;
1183}
1184
Jordan Rosed3934582012-09-28 22:21:30 +00001185static void diagnoseRepeatedUseOfWeak(Sema &S,
1186 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001187 const Decl *D,
1188 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001189 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1190 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1191 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001192 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1193 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001194
Jordan Rose25c0ea82012-10-29 17:46:47 +00001195 ASTContext &Ctx = S.getASTContext();
1196
Jordan Rosed3934582012-09-28 22:21:30 +00001197 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1198
1199 // Extract all weak objects that are referenced more than once.
1200 SmallVector<StmtUsesPair, 8> UsesByStmt;
1201 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1202 I != E; ++I) {
1203 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001204
1205 // Find the first read of the weak object.
1206 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1207 for ( ; UI != UE; ++UI) {
1208 if (UI->isUnsafe())
1209 break;
1210 }
1211
1212 // If there were only writes to this object, don't warn.
1213 if (UI == UE)
1214 continue;
1215
Jordan Rose76831c62012-10-11 16:10:19 +00001216 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001217 // read is not within a loop, don't warn. Additionally, don't warn in a
1218 // loop if the base object is a local variable -- local variables are often
1219 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001220 if (UI == Uses.begin()) {
1221 WeakUseVector::const_iterator UI2 = UI;
1222 for (++UI2; UI2 != UE; ++UI2)
1223 if (UI2->isUnsafe())
1224 break;
1225
Jordan Rose25c0ea82012-10-29 17:46:47 +00001226 if (UI2 == UE) {
1227 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001228 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001229
1230 const WeakObjectProfileTy &Profile = I->first;
1231 if (!Profile.isExactProfile())
1232 continue;
1233
1234 const NamedDecl *Base = Profile.getBase();
1235 if (!Base)
1236 Base = Profile.getProperty();
1237 assert(Base && "A profile always has a base or property.");
1238
1239 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1240 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1241 continue;
1242 }
Jordan Rose76831c62012-10-11 16:10:19 +00001243 }
1244
Jordan Rosed3934582012-09-28 22:21:30 +00001245 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1246 }
1247
1248 if (UsesByStmt.empty())
1249 return;
1250
1251 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001252 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001253 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001254 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1255 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1256 RHS.first->getLocStart());
1257 });
Jordan Rosed3934582012-09-28 22:21:30 +00001258
1259 // Classify the current code body for better warning text.
1260 // This enum should stay in sync with the cases in
1261 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1262 // FIXME: Should we use a common classification enum and the same set of
1263 // possibilities all throughout Sema?
1264 enum {
1265 Function,
1266 Method,
1267 Block,
1268 Lambda
1269 } FunctionKind;
1270
1271 if (isa<sema::BlockScopeInfo>(CurFn))
1272 FunctionKind = Block;
1273 else if (isa<sema::LambdaScopeInfo>(CurFn))
1274 FunctionKind = Lambda;
1275 else if (isa<ObjCMethodDecl>(D))
1276 FunctionKind = Method;
1277 else
1278 FunctionKind = Function;
1279
1280 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001281 for (const auto &P : UsesByStmt) {
1282 const Stmt *FirstRead = P.first;
1283 const WeakObjectProfileTy &Key = P.second->first;
1284 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001285
Jordan Rose657b5f42012-09-28 22:21:35 +00001286 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1287 // may not contain enough information to determine that these are different
1288 // properties. We can only be 100% sure of a repeated use in certain cases,
1289 // and we adjust the diagnostic kind accordingly so that the less certain
1290 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001291 unsigned DiagKind;
1292 if (Key.isExactProfile())
1293 DiagKind = diag::warn_arc_repeated_use_of_weak;
1294 else
1295 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1296
Jordan Rose657b5f42012-09-28 22:21:35 +00001297 // Classify the weak object being accessed for better warning text.
1298 // This enum should stay in sync with the cases in
1299 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1300 enum {
1301 Variable,
1302 Property,
1303 ImplicitProperty,
1304 Ivar
1305 } ObjectKind;
1306
1307 const NamedDecl *D = Key.getProperty();
1308 if (isa<VarDecl>(D))
1309 ObjectKind = Variable;
1310 else if (isa<ObjCPropertyDecl>(D))
1311 ObjectKind = Property;
1312 else if (isa<ObjCMethodDecl>(D))
1313 ObjectKind = ImplicitProperty;
1314 else if (isa<ObjCIvarDecl>(D))
1315 ObjectKind = Ivar;
1316 else
1317 llvm_unreachable("Unexpected weak object kind!");
1318
Jordan Rosed3934582012-09-28 22:21:30 +00001319 // Show the first time the object was read.
1320 S.Diag(FirstRead->getLocStart(), DiagKind)
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001321 << int(ObjectKind) << D << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001322 << FirstRead->getSourceRange();
1323
1324 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001325 for (const auto &Use : Uses) {
1326 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001327 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001328 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001329 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001330 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001331 }
1332 }
1333}
1334
Jordan Rosed3934582012-09-28 22:21:30 +00001335namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001336class UninitValsDiagReporter : public UninitVariablesHandler {
1337 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001338 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001339 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001340 // Prefer using MapVector to DenseMap, so that iteration order will be
1341 // the same as insertion order. This is needed to obtain a deterministic
1342 // order of diagnostics when calling flushDiagnostics().
1343 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001344 UsesMap *uses;
1345
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001346public:
Craig Topperc3ec1492014-05-26 06:22:03 +00001347 UninitValsDiagReporter(Sema &S) : S(S), uses(nullptr) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001348 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001349
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001350 MappedType &getUses(const VarDecl *vd) {
Ted Kremenek39fa0562011-01-21 19:41:41 +00001351 if (!uses)
1352 uses = new UsesMap();
Ted Kremenek596fa162011-10-13 18:50:06 +00001353
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001354 MappedType &V = (*uses)[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001355 if (!V.getPointer())
1356 V.setPointer(new UsesVec());
Ted Kremenek39fa0562011-01-21 19:41:41 +00001357
Ted Kremenek596fa162011-10-13 18:50:06 +00001358 return V;
1359 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001360
1361 void handleUseOfUninitVariable(const VarDecl *vd,
1362 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001363 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001364 }
1365
Craig Toppere14c0f82014-03-12 04:55:44 +00001366 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001367 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001368 }
1369
1370 void flushDiagnostics() {
1371 if (!uses)
1372 return;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001373
Aaron Ballmane5195222014-05-15 20:50:47 +00001374 for (const auto &P : *uses) {
1375 const VarDecl *vd = P.first;
1376 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001377
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001378 UsesVec *vec = V.getPointer();
1379 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001380
1381 // Specially handle the case where we have uses of an uninitialized
1382 // variable, but the root cause is an idiomatic self-init. We want
1383 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001384 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001385 DiagnoseUninitializedUse(S, vd,
1386 UninitUse(vd->getInit()->IgnoreParenCasts(),
1387 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001388 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001389 else {
1390 // Sort the uses by their SourceLocations. While not strictly
1391 // guaranteed to produce them in line/column order, this will provide
1392 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001393 std::sort(vec->begin(), vec->end(),
1394 [](const UninitUse &a, const UninitUse &b) {
1395 // Prefer a more confident report over a less confident one.
1396 if (a.getKind() != b.getKind())
1397 return a.getKind() > b.getKind();
1398 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1399 });
1400
Aaron Ballmane5195222014-05-15 20:50:47 +00001401 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001402 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001403 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001404
1405 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001406 // Skip further diagnostics for this variable. We try to warn only
1407 // on the first point at which a variable is used uninitialized.
1408 break;
1409 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001410 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001411
1412 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001413 delete vec;
1414 }
1415 delete uses;
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001416 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001417
1418private:
1419 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001420 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1421 return U.getKind() == UninitUse::Always ||
1422 U.getKind() == UninitUse::AfterCall ||
1423 U.getKind() == UninitUse::AfterDecl;
1424 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001425 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001426};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001427} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001428
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001429namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001430namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001431typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001432typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001433typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001434
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001435struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001436 SourceManager &SM;
1437 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001438
1439 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1440 // Although this call will be slow, this is only called when outputting
1441 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001442 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001443 }
1444};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001445} // anonymous namespace
1446} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001447
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001448//===----------------------------------------------------------------------===//
1449// -Wthread-safety
1450//===----------------------------------------------------------------------===//
1451namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001452namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001453namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001454class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001455 Sema &S;
1456 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001457 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001458
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001459 const FunctionDecl *CurrentFunction;
1460 bool Verbose;
1461
Aaron Ballman71291bc2014-08-15 12:38:17 +00001462 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001463 if (Verbose && CurrentFunction) {
1464 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001465 S.PDiag(diag::note_thread_warning_in_fun)
1466 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001467 return OptionalNotes(1, FNote);
1468 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001469 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001470 }
1471
Aaron Ballman71291bc2014-08-15 12:38:17 +00001472 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001473 OptionalNotes ONS(1, Note);
1474 if (Verbose && CurrentFunction) {
1475 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001476 S.PDiag(diag::note_thread_warning_in_fun)
1477 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001478 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001479 }
1480 return ONS;
1481 }
1482
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001483 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1484 const PartialDiagnosticAt &Note2) const {
1485 OptionalNotes ONS;
1486 ONS.push_back(Note1);
1487 ONS.push_back(Note2);
1488 if (Verbose && CurrentFunction) {
1489 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1490 S.PDiag(diag::note_thread_warning_in_fun)
1491 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001492 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001493 }
1494 return ONS;
1495 }
1496
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001497 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001498 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1499 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001500 // Gracefully handle rare cases when the analysis can't get a more
1501 // precise source location.
1502 if (!Loc.isValid())
1503 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001504 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001505 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001506 }
1507
1508 public:
Richard Smith92286672012-02-03 04:45:26 +00001509 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001510 : S(S), FunLocation(FL), FunEndLocation(FEL),
1511 CurrentFunction(nullptr), Verbose(false) {}
1512
1513 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001514
1515 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1516 /// We need to output diagnostics produced while iterating through
1517 /// the lockset in deterministic order, so this function orders diagnostics
1518 /// and outputs them.
1519 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001520 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001521 for (const auto &Diag : Warnings) {
1522 S.Diag(Diag.first.first, Diag.first.second);
1523 for (const auto &Note : Diag.second)
1524 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001525 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001526 }
1527
Aaron Ballmane0449042014-04-01 21:43:23 +00001528 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1529 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1530 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001531 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001532 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001533
Aaron Ballmane0449042014-04-01 21:43:23 +00001534 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1535 SourceLocation Loc) override {
1536 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001537 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001538
Aaron Ballmane0449042014-04-01 21:43:23 +00001539 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1540 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001541 SourceLocation Loc) override {
1542 if (Loc.isInvalid())
1543 Loc = FunLocation;
1544 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001545 << Kind << LockName << Received
1546 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001547 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001548 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001549
Aaron Ballmane0449042014-04-01 21:43:23 +00001550 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1551 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001552 }
1553
Aaron Ballmane0449042014-04-01 21:43:23 +00001554 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1555 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001556 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001557 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001558 unsigned DiagID = 0;
1559 switch (LEK) {
1560 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001561 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001562 break;
1563 case LEK_LockedSomeLoopIterations:
1564 DiagID = diag::warn_expecting_lock_held_on_loop;
1565 break;
1566 case LEK_LockedAtEndOfFunction:
1567 DiagID = diag::warn_no_unlock;
1568 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001569 case LEK_NotLockedAtEndOfFunction:
1570 DiagID = diag::warn_expecting_locked;
1571 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001572 }
Richard Smith92286672012-02-03 04:45:26 +00001573 if (LocEndOfScope.isInvalid())
1574 LocEndOfScope = FunEndLocation;
1575
Aaron Ballmane0449042014-04-01 21:43:23 +00001576 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1577 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001578 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001579 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1580 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001581 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001582 return;
1583 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001584 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001585 }
1586
Aaron Ballmane0449042014-04-01 21:43:23 +00001587 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1588 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001589 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001590 PartialDiagnosticAt Warning(Loc1,
1591 S.PDiag(diag::warn_lock_exclusive_and_shared)
1592 << Kind << LockName);
1593 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1594 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001595 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001596 }
1597
Aaron Ballmane0449042014-04-01 21:43:23 +00001598 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1599 ProtectedOperationKind POK, AccessKind AK,
1600 SourceLocation Loc) override {
1601 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1602 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001603 unsigned DiagID = POK == POK_VarAccess?
1604 diag::warn_variable_requires_any_lock:
1605 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001606 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001607 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001608 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001609 }
1610
Aaron Ballmane0449042014-04-01 21:43:23 +00001611 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1612 ProtectedOperationKind POK, Name LockName,
1613 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001614 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001615 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001616 if (PossibleMatch) {
1617 switch (POK) {
1618 case POK_VarAccess:
1619 DiagID = diag::warn_variable_requires_lock_precise;
1620 break;
1621 case POK_VarDereference:
1622 DiagID = diag::warn_var_deref_requires_lock_precise;
1623 break;
1624 case POK_FunctionCall:
1625 DiagID = diag::warn_fun_requires_lock_precise;
1626 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001627 case POK_PassByRef:
1628 DiagID = diag::warn_guarded_pass_by_reference;
1629 break;
1630 case POK_PtPassByRef:
1631 DiagID = diag::warn_pt_guarded_pass_by_reference;
1632 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001633 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001634 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1635 << D->getNameAsString()
1636 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001637 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001638 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001639 if (Verbose && POK == POK_VarAccess) {
1640 PartialDiagnosticAt VNote(D->getLocation(),
1641 S.PDiag(diag::note_guarded_by_declared_here)
1642 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001643 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001644 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001645 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001646 } else {
1647 switch (POK) {
1648 case POK_VarAccess:
1649 DiagID = diag::warn_variable_requires_lock;
1650 break;
1651 case POK_VarDereference:
1652 DiagID = diag::warn_var_deref_requires_lock;
1653 break;
1654 case POK_FunctionCall:
1655 DiagID = diag::warn_fun_requires_lock;
1656 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001657 case POK_PassByRef:
1658 DiagID = diag::warn_guarded_pass_by_reference;
1659 break;
1660 case POK_PtPassByRef:
1661 DiagID = diag::warn_pt_guarded_pass_by_reference;
1662 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001663 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001664 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1665 << D->getNameAsString()
1666 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001667 if (Verbose && POK == POK_VarAccess) {
1668 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001669 S.PDiag(diag::note_guarded_by_declared_here)
1670 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001671 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001672 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001673 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001674 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001675 }
1676
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001677 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1678 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001679 PartialDiagnosticAt Warning(Loc,
1680 S.PDiag(diag::warn_acquire_requires_negative_cap)
1681 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001682 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001683 }
1684
Aaron Ballmane0449042014-04-01 21:43:23 +00001685 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001686 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001687 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1688 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001689 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001690 }
1691
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001692 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1693 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001694 PartialDiagnosticAt Warning(Loc,
1695 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001696 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001697 }
1698
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001699 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001700 PartialDiagnosticAt Warning(Loc,
1701 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001702 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001703 }
1704
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001705 void enterFunction(const FunctionDecl* FD) override {
1706 CurrentFunction = FD;
1707 }
1708
1709 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001710 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001711 }
1712};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001713} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001714} // namespace threadSafety
1715} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001716
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001717//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001718// -Wconsumed
1719//===----------------------------------------------------------------------===//
1720
1721namespace clang {
1722namespace consumed {
1723namespace {
1724class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1725
1726 Sema &S;
1727 DiagList Warnings;
1728
1729public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001730
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001731 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001732
1733 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001734 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001735 for (const auto &Diag : Warnings) {
1736 S.Diag(Diag.first.first, Diag.first.second);
1737 for (const auto &Note : Diag.second)
1738 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001739 }
1740 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001741
1742 void warnLoopStateMismatch(SourceLocation Loc,
1743 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001744 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1745 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001746
1747 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001748 }
1749
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001750 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1751 StringRef VariableName,
1752 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001753 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001754
1755 PartialDiagnosticAt Warning(Loc, S.PDiag(
1756 diag::warn_param_return_typestate_mismatch) << VariableName <<
1757 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001758
1759 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001760 }
1761
DeLesley Hutchins69391772013-10-17 23:23:53 +00001762 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001763 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001764
1765 PartialDiagnosticAt Warning(Loc, S.PDiag(
1766 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001767
1768 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001769 }
1770
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001771 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001772 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001773 PartialDiagnosticAt Warning(Loc, S.PDiag(
1774 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001775
1776 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001777 }
1778
1779 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001780 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001781
1782 PartialDiagnosticAt Warning(Loc, S.PDiag(
1783 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001784
1785 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001786 }
1787
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001788 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001789 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001790
1791 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001792 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001793
1794 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001795 }
1796
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001797 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001798 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001799
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001800 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
1801 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001802
1803 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001804 }
1805};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001806} // anonymous namespace
1807} // namespace consumed
1808} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001809
1810//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00001811// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
1812// warnings on a function, method, or block.
1813//===----------------------------------------------------------------------===//
1814
Ted Kremenek0b405322010-03-23 00:13:23 +00001815clang::sema::AnalysisBasedWarnings::Policy::Policy() {
1816 enableCheckFallThrough = 1;
1817 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001818 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001819 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00001820}
1821
Ted Kremenekad8753c2014-03-15 05:47:06 +00001822static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001823 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00001824}
1825
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001826clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
1827 : S(s),
1828 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001829 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00001830 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00001831 MaxCFGBlocksPerFunction(0),
1832 NumUninitAnalysisFunctions(0),
1833 NumUninitAnalysisVariables(0),
1834 MaxUninitAnalysisVariablesPerFunction(0),
1835 NumUninitAnalysisBlockVisits(0),
1836 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00001837
1838 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00001839 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00001840
1841 DefaultPolicy.enableCheckUnreachable =
1842 isEnabled(D, warn_unreachable) ||
1843 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00001844 isEnabled(D, warn_unreachable_return) ||
1845 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00001846
1847 DefaultPolicy.enableThreadSafetyAnalysis =
1848 isEnabled(D, warn_double_lock);
1849
1850 DefaultPolicy.enableConsumedAnalysis =
1851 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00001852}
1853
Aaron Ballmane5195222014-05-15 20:50:47 +00001854static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
1855 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00001856 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00001857}
1858
Ted Kremenek0b405322010-03-23 00:13:23 +00001859void clang::sema::
1860AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00001861 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00001862 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00001863
Ted Kremenek918fe842010-03-20 21:06:02 +00001864 // We avoid doing analysis-based warnings when there are errors for
1865 // two reasons:
1866 // (1) The CFGs often can't be constructed (if the body is invalid), so
1867 // don't bother trying.
1868 // (2) The code already has problems; running the analysis just takes more
1869 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00001870 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00001871
Ted Kremenek0b405322010-03-23 00:13:23 +00001872 // Do not do any analysis for declarations in system headers if we are
1873 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00001874 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00001875 S.SourceMgr.isInSystemHeader(D->getLocation()))
1876 return;
1877
John McCall1d570a72010-08-25 05:56:39 +00001878 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00001879 if (cast<DeclContext>(D)->isDependentContext())
1880 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00001881
DeLesley Hutchins8ecd4912012-12-07 22:53:48 +00001882 if (Diags.hasUncompilableErrorOccurred() || Diags.hasFatalErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001883 // Flush out any possibly unreachable diagnostics.
1884 flushDiagnostics(S, fscope);
1885 return;
1886 }
1887
Ted Kremenek918fe842010-03-20 21:06:02 +00001888 const Stmt *Body = D->getBody();
1889 assert(Body);
1890
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001891 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00001892 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00001893
Ted Kremenek918fe842010-03-20 21:06:02 +00001894 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00001895 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00001896 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
1897 AC.getCFGBuildOptions().AddEHEdges = false;
1898 AC.getCFGBuildOptions().AddInitializers = true;
1899 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001900 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00001901 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00001902 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00001903
Ted Kremenek9e100ea2011-07-19 14:18:48 +00001904 // Force that certain expressions appear as CFGElements in the CFG. This
1905 // is used to speed up various analyses.
1906 // FIXME: This isn't the right factoring. This is here for initial
1907 // prototyping, but we need a way for analyses to say what expressions they
1908 // expect to always be CFGElements and then fill in the BuildOptions
1909 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001910 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
1911 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00001912 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00001913 AC.getCFGBuildOptions().setAllAlwaysAdd();
1914 }
1915 else {
1916 AC.getCFGBuildOptions()
1917 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00001918 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00001919 .setAlwaysAdd(Stmt::BlockExprClass)
1920 .setAlwaysAdd(Stmt::CStyleCastExprClass)
1921 .setAlwaysAdd(Stmt::DeclRefExprClass)
1922 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00001923 .setAlwaysAdd(Stmt::UnaryOperatorClass)
1924 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00001925 }
Ted Kremenek918fe842010-03-20 21:06:02 +00001926
Richard Trieue9fa2662014-04-15 00:57:50 +00001927 // Install the logical handler for -Wtautological-overlap-compare
1928 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001929 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
1930 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00001931 LEH.reset(new LogicalErrorHandler(S));
1932 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00001933 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00001934
Ted Kremenek3427fac2011-02-23 01:52:04 +00001935 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00001936 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001937 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00001938
1939 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00001940 for (const auto &D : fscope->PossiblyUnreachableDiags) {
1941 if (D.stmt)
1942 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00001943 }
1944
1945 if (AC.getCFG()) {
1946 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00001947 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00001948 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00001949 if (D.stmt) {
1950 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00001951 CFGReverseBlockReachabilityAnalysis *cra =
1952 AC.getCFGReachablityAnalysis();
1953 // FIXME: We should be able to assert that block is non-null, but
1954 // the CFG analysis can skip potentially-evaluated expressions in
1955 // edge cases; see test/Sema/vla-2.c.
1956 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00001957 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00001958 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00001959 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00001960 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00001961 }
1962 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001963 if (!processed) {
1964 // Emit the warning anyway if we cannot map to a basic block.
1965 S.Diag(D.Loc, D.PD);
1966 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001967 }
Ted Kremeneka099c592011-03-10 03:50:34 +00001968 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00001969
1970 if (!analyzed)
1971 flushDiagnostics(S, fscope);
1972 }
1973
Ted Kremenek918fe842010-03-20 21:06:02 +00001974 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00001975 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00001976 const CheckFallThroughDiagnostics &CD =
1977 (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
Douglas Gregorcf11eb72012-02-15 16:20:15 +00001978 : (isa<CXXMethodDecl>(D) &&
1979 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
1980 cast<CXXMethodDecl>(D)->getParent()->isLambda())
1981 ? CheckFallThroughDiagnostics::MakeForLambda()
1982 : CheckFallThroughDiagnostics::MakeForFunction(D));
Ted Kremenek1767a272011-02-23 01:51:48 +00001983 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00001984 }
1985
1986 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00001987 if (P.enableCheckUnreachable) {
1988 // Only check for unreachable code on non-template instantiations.
1989 // Different template instantiations can effectively change the control-flow
1990 // and it is very difficult to prove that a snippet of code in a template
1991 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00001992 bool isTemplateInstantiation = false;
1993 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
1994 isTemplateInstantiation = Function->isTemplateInstantiation();
1995 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00001996 CheckUnreachable(S, AC);
1997 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001998
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00001999 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002000 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002001 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00002002 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002003 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002004 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002005 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002006 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2007 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002008
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002009 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2010 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002011 Reporter.emitDiagnostics();
2012 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002013
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002014 // Check for violations of consumed properties.
2015 if (P.enableConsumedAnalysis) {
2016 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002017 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002018 Analyzer.run(AC);
2019 }
2020
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002021 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2022 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2023 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002024 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002025 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002026 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002027 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002028 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002029 reporter, stats);
2030
2031 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2032 ++NumUninitAnalysisFunctions;
2033 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2034 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2035 MaxUninitAnalysisVariablesPerFunction =
2036 std::max(MaxUninitAnalysisVariablesPerFunction,
2037 stats.NumVariablesAnalyzed);
2038 MaxUninitAnalysisBlockVisitsPerFunction =
2039 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2040 stats.NumBlockVisits);
2041 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002042 }
2043 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002044
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002045 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002046 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2047 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2048 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Alexis Hunt2178f142012-06-15 21:22:05 +00002049 if (FallThroughDiagFull || FallThroughDiagPerFunction) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002050 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002051 }
2052
John McCall460ce582015-10-22 18:38:17 +00002053 if (S.getLangOpts().ObjCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002054 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002055 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002056
Richard Trieu2f024f42013-12-21 02:33:43 +00002057
2058 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002059 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2060 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002061 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2062 checkRecursiveFunction(S, FD, Body, AC);
2063 }
2064 }
2065
Richard Trieue9fa2662014-04-15 00:57:50 +00002066 // If none of the previous checks caused a CFG build, trigger one here
2067 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002068 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002069 D->getLocStart())) {
2070 AC.getCFG();
2071 }
2072
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002073 // Collect statistics about the CFG if it was built.
2074 if (S.CollectStats && AC.isCFGBuilt()) {
2075 ++NumFunctionsAnalyzed;
2076 if (CFG *cfg = AC.getCFG()) {
2077 // If we successfully built a CFG for this context, record some more
2078 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002079 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002080 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002081 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002082 } else {
2083 ++NumFunctionsWithBadCFGs;
2084 }
2085 }
2086}
2087
2088void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2089 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2090
2091 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2092 unsigned AvgCFGBlocksPerFunction =
2093 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2094 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2095 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2096 << " " << NumCFGBlocks << " CFG blocks built.\n"
2097 << " " << AvgCFGBlocksPerFunction
2098 << " average CFG blocks per function.\n"
2099 << " " << MaxCFGBlocksPerFunction
2100 << " max CFG blocks per function.\n";
2101
2102 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2103 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2104 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2105 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2106 llvm::errs() << NumUninitAnalysisFunctions
2107 << " functions analyzed for uninitialiazed variables\n"
2108 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2109 << " " << AvgUninitVariablesPerFunction
2110 << " average variables per function.\n"
2111 << " " << MaxUninitAnalysisVariablesPerFunction
2112 << " max variables per function.\n"
2113 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2114 << " " << AvgUninitBlockVisitsPerFunction
2115 << " average block visits per function.\n"
2116 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2117 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002118}