blob: 934e13e72d056bb83828ed1bcec7e638b4bbf624 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000037#include "clang/Lex/Preprocessor.h"
38#include "clang/Sema/ScopeInfo.h"
39#include "clang/Sema/SemaInternal.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000040#include "llvm/ADT/BitVector.h"
Enea Zaffanella2f40be72013-02-15 20:09:55 +000041#include "llvm/ADT/MapVector.h"
Dmitri Gribenko6743e042012-09-29 11:40:46 +000042#include "llvm/ADT/SmallString.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000043#include "llvm/ADT/SmallVector.h"
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +000044#include "llvm/ADT/StringRef.h"
Ted Kremenek918fe842010-03-20 21:06:02 +000045#include "llvm/Support/Casting.h"
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +000046#include <algorithm>
Chandler Carruth3a022472012-12-04 09:13:33 +000047#include <deque>
Richard Smith84837d52012-05-03 18:27:39 +000048#include <iterator>
Ted Kremenek918fe842010-03-20 21:06:02 +000049
50using namespace clang;
51
52//===----------------------------------------------------------------------===//
53// Unreachable code analysis.
54//===----------------------------------------------------------------------===//
55
56namespace {
57 class UnreachableCodeHandler : public reachable_code::Callback {
58 Sema &S;
Alex Lorenz569ad732017-01-12 10:48:03 +000059 SourceRange PreviousSilenceableCondVal;
60
Ted Kremenek918fe842010-03-20 21:06:02 +000061 public:
62 UnreachableCodeHandler(Sema &s) : S(s) {}
63
Ted Kremenek1a8641c2014-03-15 01:26:32 +000064 void HandleUnreachable(reachable_code::UnreachableKind UK,
Ted Kremenekec3bbf42014-03-29 00:35:20 +000065 SourceLocation L,
66 SourceRange SilenceableCondVal,
67 SourceRange R1,
Craig Toppere14c0f82014-03-12 04:55:44 +000068 SourceRange R2) override {
Alex Lorenz569ad732017-01-12 10:48:03 +000069 // Avoid reporting multiple unreachable code diagnostics that are
70 // triggered by the same conditional value.
71 if (PreviousSilenceableCondVal.isValid() &&
72 SilenceableCondVal.isValid() &&
73 PreviousSilenceableCondVal == SilenceableCondVal)
74 return;
75 PreviousSilenceableCondVal = SilenceableCondVal;
76
Ted Kremenek1a8641c2014-03-15 01:26:32 +000077 unsigned diag = diag::warn_unreachable;
78 switch (UK) {
79 case reachable_code::UK_Break:
80 diag = diag::warn_unreachable_break;
81 break;
Ted Kremenekf3c93bb2014-03-20 06:07:30 +000082 case reachable_code::UK_Return:
Ted Kremenekad8753c2014-03-15 05:47:06 +000083 diag = diag::warn_unreachable_return;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000084 break;
Ted Kremenek14210372014-03-21 06:02:36 +000085 case reachable_code::UK_Loop_Increment:
86 diag = diag::warn_unreachable_loop_increment;
87 break;
Ted Kremenek1a8641c2014-03-15 01:26:32 +000088 case reachable_code::UK_Other:
89 break;
90 }
91
92 S.Diag(L, diag) << R1 << R2;
Ted Kremenekec3bbf42014-03-29 00:35:20 +000093
94 SourceLocation Open = SilenceableCondVal.getBegin();
95 if (Open.isValid()) {
Alp Tokerb6cc5922014-05-03 03:45:55 +000096 SourceLocation Close = SilenceableCondVal.getEnd();
97 Close = S.getLocForEndOfToken(Close);
Ted Kremenekec3bbf42014-03-29 00:35:20 +000098 if (Close.isValid()) {
99 S.Diag(Open, diag::note_unreachable_silence)
100 << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
101 << FixItHint::CreateInsertion(Close, ")");
102 }
103 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000104 }
105 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000106} // anonymous namespace
Ted Kremenek918fe842010-03-20 21:06:02 +0000107
108/// CheckUnreachable - Check for unreachable code.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000109static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
Ted Kremenekc1b28752014-02-25 22:35:37 +0000110 // As a heuristic prune all diagnostics not in the main file. Currently
111 // the majority of warnings in headers are false positives. These
112 // are largely caused by configuration state, e.g. preprocessor
113 // defined code, etc.
114 //
115 // Note that this is also a performance optimization. Analyzing
116 // headers many times can be expensive.
117 if (!S.getSourceManager().isInMainFile(AC.getDecl()->getLocStart()))
118 return;
119
Ted Kremenek918fe842010-03-20 21:06:02 +0000120 UnreachableCodeHandler UC(S);
Ted Kremenek2dd810a2014-03-09 08:13:49 +0000121 reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
Ted Kremenek918fe842010-03-20 21:06:02 +0000122}
123
Benjamin Kramer3a002252015-02-16 16:53:12 +0000124namespace {
Richard Trieuf935b562014-04-05 05:17:01 +0000125/// \brief Warn on logical operator errors in CFGBuilder
126class LogicalErrorHandler : public CFGCallback {
127 Sema &S;
128
129public:
130 LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
131
132 static bool HasMacroID(const Expr *E) {
133 if (E->getExprLoc().isMacroID())
134 return true;
135
136 // Recurse to children.
Benjamin Kramer642f1732015-07-02 21:03:14 +0000137 for (const Stmt *SubStmt : E->children())
138 if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
139 if (HasMacroID(SubExpr))
140 return true;
Richard Trieuf935b562014-04-05 05:17:01 +0000141
142 return false;
143 }
144
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000145 void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
Richard Trieuf935b562014-04-05 05:17:01 +0000146 if (HasMacroID(B))
147 return;
148
149 SourceRange DiagRange = B->getSourceRange();
150 S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
151 << DiagRange << isAlwaysTrue;
152 }
Jordan Rose7afd71e2014-05-20 17:31:11 +0000153
Alexander Kornienko34eb2072015-04-11 02:00:23 +0000154 void compareBitwiseEquality(const BinaryOperator *B,
155 bool isAlwaysTrue) override {
Jordan Rose7afd71e2014-05-20 17:31:11 +0000156 if (HasMacroID(B))
157 return;
158
159 SourceRange DiagRange = B->getSourceRange();
160 S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
161 << DiagRange << isAlwaysTrue;
162 }
Richard Trieuf935b562014-04-05 05:17:01 +0000163};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000164} // anonymous namespace
Richard Trieuf935b562014-04-05 05:17:01 +0000165
Ted Kremenek918fe842010-03-20 21:06:02 +0000166//===----------------------------------------------------------------------===//
Richard Trieu2f024f42013-12-21 02:33:43 +0000167// Check for infinite self-recursion in functions
168//===----------------------------------------------------------------------===//
169
Richard Trieu6995de92015-08-21 03:43:09 +0000170// Returns true if the function is called anywhere within the CFGBlock.
171// For member functions, the additional condition of being call from the
172// this pointer is required.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000173static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
Richard Trieu6995de92015-08-21 03:43:09 +0000174 // Process all the Stmt's in this block to find any calls to FD.
Duncan P. N. Exon Smithf0eafc72015-07-23 20:11:47 +0000175 for (const auto &B : Block) {
176 if (B.getKind() != CFGElement::Statement)
177 continue;
178
179 const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
180 if (!CE || !CE->getCalleeDecl() ||
181 CE->getCalleeDecl()->getCanonicalDecl() != FD)
182 continue;
183
184 // Skip function calls which are qualified with a templated class.
185 if (const DeclRefExpr *DRE =
186 dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
187 if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
188 if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
189 isa<TemplateSpecializationType>(NNS->getAsType())) {
190 continue;
191 }
192 }
193 }
194
195 const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
196 if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
197 !MCE->getMethodDecl()->isVirtual())
198 return true;
199 }
200 return false;
201}
202
Richard Trieu6995de92015-08-21 03:43:09 +0000203// All blocks are in one of three states. States are ordered so that blocks
204// can only move to higher states.
205enum RecursiveState {
206 FoundNoPath,
207 FoundPath,
208 FoundPathWithNoRecursiveCall
209};
210
211// Returns true if there exists a path to the exit block and every path
212// to the exit block passes through a call to FD.
213static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
214
215 const unsigned ExitID = cfg->getExit().getBlockID();
216
217 // Mark all nodes as FoundNoPath, then set the status of the entry block.
218 SmallVector<RecursiveState, 16> States(cfg->getNumBlockIDs(), FoundNoPath);
219 States[cfg->getEntry().getBlockID()] = FoundPathWithNoRecursiveCall;
220
221 // Make the processing stack and seed it with the entry block.
222 SmallVector<CFGBlock *, 16> Stack;
223 Stack.push_back(&cfg->getEntry());
Richard Trieu2f024f42013-12-21 02:33:43 +0000224
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000225 while (!Stack.empty()) {
Richard Trieu6995de92015-08-21 03:43:09 +0000226 CFGBlock *CurBlock = Stack.back();
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000227 Stack.pop_back();
Richard Trieu2f024f42013-12-21 02:33:43 +0000228
Richard Trieu6995de92015-08-21 03:43:09 +0000229 unsigned ID = CurBlock->getBlockID();
230 RecursiveState CurState = States[ID];
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000231
232 if (CurState == FoundPathWithNoRecursiveCall) {
233 // Found a path to the exit node without a recursive call.
234 if (ExitID == ID)
Richard Trieu6995de92015-08-21 03:43:09 +0000235 return false;
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000236
Richard Trieu6995de92015-08-21 03:43:09 +0000237 // Only change state if the block has a recursive call.
238 if (hasRecursiveCallInPath(FD, *CurBlock))
Duncan P. N. Exon Smithdccc30a2015-07-23 20:15:50 +0000239 CurState = FoundPath;
240 }
241
Richard Trieu6995de92015-08-21 03:43:09 +0000242 // Loop over successor blocks and add them to the Stack if their state
243 // changes.
244 for (auto I = CurBlock->succ_begin(), E = CurBlock->succ_end(); I != E; ++I)
245 if (*I) {
246 unsigned next_ID = (*I)->getBlockID();
247 if (States[next_ID] < CurState) {
248 States[next_ID] = CurState;
249 Stack.push_back(*I);
250 }
251 }
Richard Trieu2f024f42013-12-21 02:33:43 +0000252 }
Richard Trieu6995de92015-08-21 03:43:09 +0000253
254 // Return true if the exit node is reachable, and only reachable through
255 // a recursive call.
256 return States[ExitID] == FoundPath;
Richard Trieu2f024f42013-12-21 02:33:43 +0000257}
258
259static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
Richard Trieu6995de92015-08-21 03:43:09 +0000260 const Stmt *Body, AnalysisDeclContext &AC) {
Richard Trieu2f024f42013-12-21 02:33:43 +0000261 FD = FD->getCanonicalDecl();
262
263 // Only run on non-templated functions and non-templated members of
264 // templated classes.
265 if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
266 FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
267 return;
268
269 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000270 if (!cfg) return;
Richard Trieu2f024f42013-12-21 02:33:43 +0000271
272 // If the exit block is unreachable, skip processing the function.
273 if (cfg->getExit().pred_empty())
274 return;
275
Richard Trieu6995de92015-08-21 03:43:09 +0000276 // Emit diagnostic if a recursive function call is detected for all paths.
277 if (checkForRecursiveFunctionCall(FD, cfg))
Richard Trieu2f024f42013-12-21 02:33:43 +0000278 S.Diag(Body->getLocStart(), diag::warn_infinite_recursive_function);
279}
280
281//===----------------------------------------------------------------------===//
Erich Keane89fe9c22017-06-23 20:22:19 +0000282// Check for throw in a non-throwing function.
283//===----------------------------------------------------------------------===//
284enum ThrowState {
285 FoundNoPathForThrow,
286 FoundPathForThrow,
287 FoundPathWithNoThrowOutFunction,
288};
289
290static bool isThrowCaught(const CXXThrowExpr *Throw,
291 const CXXCatchStmt *Catch) {
292 const Type *ThrowType = nullptr;
293 if (Throw->getSubExpr())
294 ThrowType = Throw->getSubExpr()->getType().getTypePtrOrNull();
295 if (!ThrowType)
296 return false;
297 const Type *CaughtType = Catch->getCaughtType().getTypePtrOrNull();
298 if (!CaughtType)
299 return true;
300 if (ThrowType->isReferenceType())
301 ThrowType = ThrowType->castAs<ReferenceType>()
302 ->getPointeeType()
303 ->getUnqualifiedDesugaredType();
304 if (CaughtType->isReferenceType())
305 CaughtType = CaughtType->castAs<ReferenceType>()
306 ->getPointeeType()
307 ->getUnqualifiedDesugaredType();
308 if (CaughtType == ThrowType)
309 return true;
310 const CXXRecordDecl *CaughtAsRecordType =
311 CaughtType->getPointeeCXXRecordDecl();
312 const CXXRecordDecl *ThrowTypeAsRecordType = ThrowType->getAsCXXRecordDecl();
313 if (CaughtAsRecordType && ThrowTypeAsRecordType)
314 return ThrowTypeAsRecordType->isDerivedFrom(CaughtAsRecordType);
315 return false;
316}
317
318static bool isThrowCaughtByHandlers(const CXXThrowExpr *CE,
319 const CXXTryStmt *TryStmt) {
320 for (unsigned H = 0, E = TryStmt->getNumHandlers(); H < E; ++H) {
321 if (isThrowCaught(CE, TryStmt->getHandler(H)))
322 return true;
323 }
324 return false;
325}
326
327static bool doesThrowEscapePath(CFGBlock Block, SourceLocation &OpLoc) {
328 for (const auto &B : Block) {
329 if (B.getKind() != CFGElement::Statement)
330 continue;
331 const auto *CE = dyn_cast<CXXThrowExpr>(B.getAs<CFGStmt>()->getStmt());
332 if (!CE)
333 continue;
334
335 OpLoc = CE->getThrowLoc();
336 for (const auto &I : Block.succs()) {
337 if (!I.isReachable())
338 continue;
339 if (const auto *Terminator =
340 dyn_cast_or_null<CXXTryStmt>(I->getTerminator()))
341 if (isThrowCaughtByHandlers(CE, Terminator))
342 return false;
343 }
344 return true;
345 }
346 return false;
347}
348
349static bool hasThrowOutNonThrowingFunc(SourceLocation &OpLoc, CFG *BodyCFG) {
350
351 unsigned ExitID = BodyCFG->getExit().getBlockID();
352
353 SmallVector<ThrowState, 16> States(BodyCFG->getNumBlockIDs(),
354 FoundNoPathForThrow);
355 States[BodyCFG->getEntry().getBlockID()] = FoundPathWithNoThrowOutFunction;
356
357 SmallVector<CFGBlock *, 16> Stack;
358 Stack.push_back(&BodyCFG->getEntry());
359 while (!Stack.empty()) {
360 CFGBlock *CurBlock = Stack.back();
361 Stack.pop_back();
362
363 unsigned ID = CurBlock->getBlockID();
364 ThrowState CurState = States[ID];
365 if (CurState == FoundPathWithNoThrowOutFunction) {
366 if (ExitID == ID)
367 continue;
368
369 if (doesThrowEscapePath(*CurBlock, OpLoc))
370 CurState = FoundPathForThrow;
371 }
372
373 // Loop over successor blocks and add them to the Stack if their state
374 // changes.
375 for (const auto &I : CurBlock->succs())
376 if (I.isReachable()) {
377 unsigned NextID = I->getBlockID();
378 if (NextID == ExitID && CurState == FoundPathForThrow) {
379 States[NextID] = CurState;
380 } else if (States[NextID] < CurState) {
381 States[NextID] = CurState;
382 Stack.push_back(I);
383 }
384 }
385 }
386 // Return true if the exit node is reachable, and only reachable through
387 // a throw expression.
388 return States[ExitID] == FoundPathForThrow;
389}
390
391static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
392 const FunctionDecl *FD) {
393 if (!S.getSourceManager().isInSystemHeader(OpLoc)) {
394 S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
395 if (S.getLangOpts().CPlusPlus11 &&
396 (isa<CXXDestructorDecl>(FD) ||
397 FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
398 FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete))
399 S.Diag(FD->getLocation(), diag::note_throw_in_dtor);
400 else
401 S.Diag(FD->getLocation(), diag::note_throw_in_function);
402 }
403}
404
405static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
406 AnalysisDeclContext &AC) {
407 CFG *BodyCFG = AC.getCFG();
408 if (!BodyCFG)
409 return;
410 if (BodyCFG->getExit().pred_empty())
411 return;
412 SourceLocation OpLoc;
413 if (hasThrowOutNonThrowingFunc(OpLoc, BodyCFG))
414 EmitDiagForCXXThrowInNonThrowingFunc(S, OpLoc, FD);
415}
416
417static bool isNoexcept(const FunctionDecl *FD) {
418 const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
419 if (FPT->getExceptionSpecType() != EST_None &&
420 FPT->isNothrow(FD->getASTContext()))
421 return true;
422 return false;
423}
424
425//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +0000426// Check for missing return value.
427//===----------------------------------------------------------------------===//
428
John McCall5c6ec8c2010-05-16 09:34:11 +0000429enum ControlFlowKind {
430 UnknownFallThrough,
431 NeverFallThrough,
432 MaybeFallThrough,
433 AlwaysFallThrough,
434 NeverFallThroughOrReturn
435};
Ted Kremenek918fe842010-03-20 21:06:02 +0000436
437/// CheckFallThrough - Check that we don't fall off the end of a
438/// Statement that should return a value.
439///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000440/// \returns AlwaysFallThrough iff we always fall off the end of the statement,
441/// MaybeFallThrough iff we might or might not fall off the end,
442/// NeverFallThroughOrReturn iff we never fall off the end of the statement or
443/// return. We assume NeverFallThrough iff we never fall off the end of the
Ted Kremenek918fe842010-03-20 21:06:02 +0000444/// statement but we may return. We assume that functions not marked noreturn
445/// will return.
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000446static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000447 CFG *cfg = AC.getCFG();
Craig Topperc3ec1492014-05-26 06:22:03 +0000448 if (!cfg) return UnknownFallThrough;
Ted Kremenek918fe842010-03-20 21:06:02 +0000449
450 // The CFG leaves in dead things, and we don't want the dead code paths to
451 // confuse us, so we mark all live things first.
Ted Kremenek918fe842010-03-20 21:06:02 +0000452 llvm::BitVector live(cfg->getNumBlockIDs());
Ted Kremenekbd913712011-08-23 23:05:11 +0000453 unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
Ted Kremenek918fe842010-03-20 21:06:02 +0000454 live);
455
456 bool AddEHEdges = AC.getAddEHEdges();
457 if (!AddEHEdges && count != cfg->getNumBlockIDs())
458 // When there are things remaining dead, and we didn't add EH edges
459 // from CallExprs to the catch clauses, we have to go back and
460 // mark them as live.
Aaron Ballmane5195222014-05-15 20:50:47 +0000461 for (const auto *B : *cfg) {
462 if (!live[B->getBlockID()]) {
463 if (B->pred_begin() == B->pred_end()) {
464 if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
Ted Kremenek918fe842010-03-20 21:06:02 +0000465 // When not adding EH edges from calls, catch clauses
466 // can otherwise seem dead. Avoid noting them as dead.
Aaron Ballmane5195222014-05-15 20:50:47 +0000467 count += reachable_code::ScanReachableFromBlock(B, live);
Ted Kremenek918fe842010-03-20 21:06:02 +0000468 continue;
469 }
470 }
471 }
472
473 // Now we know what is live, we check the live precessors of the exit block
474 // and look for fall through paths, being careful to ignore normal returns,
475 // and exceptional paths.
476 bool HasLiveReturn = false;
477 bool HasFakeEdge = false;
478 bool HasPlainEdge = false;
479 bool HasAbnormalEdge = false;
Ted Kremenek50205742010-09-09 00:06:07 +0000480
481 // Ignore default cases that aren't likely to be reachable because all
482 // enums in a switch(X) have explicit case statements.
483 CFGBlock::FilterOptions FO;
484 FO.IgnoreDefaultsWithCoveredEnums = 1;
485
486 for (CFGBlock::filtered_pred_iterator
487 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
488 const CFGBlock& B = **I;
Ted Kremenek918fe842010-03-20 21:06:02 +0000489 if (!live[B.getBlockID()])
490 continue;
Ted Kremenek5d068492011-01-26 04:49:52 +0000491
Chandler Carruth03faf782011-09-13 09:53:58 +0000492 // Skip blocks which contain an element marked as no-return. They don't
493 // represent actually viable edges into the exit block, so mark them as
494 // abnormal.
495 if (B.hasNoReturnElement()) {
496 HasAbnormalEdge = true;
497 continue;
498 }
499
Ted Kremenek5d068492011-01-26 04:49:52 +0000500 // Destructors can appear after the 'return' in the CFG. This is
501 // normal. We need to look pass the destructors for the return
502 // statement (if it exists).
503 CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
Ted Kremeneke06a55c2011-03-02 20:32:29 +0000504
Chandler Carruth03faf782011-09-13 09:53:58 +0000505 for ( ; ri != re ; ++ri)
David Blaikie2a01f5d2013-02-21 20:58:29 +0000506 if (ri->getAs<CFGStmt>())
Ted Kremenek5d068492011-01-26 04:49:52 +0000507 break;
Chandler Carruth03faf782011-09-13 09:53:58 +0000508
Ted Kremenek5d068492011-01-26 04:49:52 +0000509 // No more CFGElements in the block?
510 if (ri == re) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000511 if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
512 HasAbnormalEdge = true;
513 continue;
514 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000515 // A labeled empty statement, or the entry block...
516 HasPlainEdge = true;
517 continue;
518 }
Ted Kremenekebe62602011-01-25 22:50:47 +0000519
David Blaikie2a01f5d2013-02-21 20:58:29 +0000520 CFGStmt CS = ri->castAs<CFGStmt>();
Ted Kremenekadfb4452011-08-23 23:05:04 +0000521 const Stmt *S = CS.getStmt();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000522 if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000523 HasLiveReturn = true;
524 continue;
525 }
526 if (isa<ObjCAtThrowStmt>(S)) {
527 HasFakeEdge = true;
528 continue;
529 }
530 if (isa<CXXThrowExpr>(S)) {
531 HasFakeEdge = true;
532 continue;
533 }
Chad Rosier32503022012-06-11 20:47:18 +0000534 if (isa<MSAsmStmt>(S)) {
535 // TODO: Verify this is correct.
536 HasFakeEdge = true;
537 HasLiveReturn = true;
538 continue;
539 }
Ted Kremenek918fe842010-03-20 21:06:02 +0000540 if (isa<CXXTryStmt>(S)) {
541 HasAbnormalEdge = true;
542 continue;
543 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000544 if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
545 == B.succ_end()) {
546 HasAbnormalEdge = true;
547 continue;
Ted Kremenek918fe842010-03-20 21:06:02 +0000548 }
Chandler Carruth03faf782011-09-13 09:53:58 +0000549
550 HasPlainEdge = true;
Ted Kremenek918fe842010-03-20 21:06:02 +0000551 }
552 if (!HasPlainEdge) {
553 if (HasLiveReturn)
554 return NeverFallThrough;
555 return NeverFallThroughOrReturn;
556 }
557 if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
558 return MaybeFallThrough;
559 // This says AlwaysFallThrough for calls to functions that are not marked
560 // noreturn, that don't return. If people would like this warning to be more
561 // accurate, such functions should be marked as noreturn.
562 return AlwaysFallThrough;
563}
564
Dan Gohman28ade552010-07-26 21:25:24 +0000565namespace {
566
Ted Kremenek918fe842010-03-20 21:06:02 +0000567struct CheckFallThroughDiagnostics {
568 unsigned diag_MaybeFallThrough_HasNoReturn;
569 unsigned diag_MaybeFallThrough_ReturnsNonVoid;
570 unsigned diag_AlwaysFallThrough_HasNoReturn;
571 unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
572 unsigned diag_NeverFallThroughOrReturn;
Eric Fiselier709d1b32016-10-27 07:30:31 +0000573 enum { Function, Block, Lambda, Coroutine } funMode;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000574 SourceLocation FuncLoc;
Ted Kremenek0b405322010-03-23 00:13:23 +0000575
Douglas Gregor24f27692010-04-16 23:28:44 +0000576 static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000577 CheckFallThroughDiagnostics D;
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000578 D.FuncLoc = Func->getLocation();
Ted Kremenek918fe842010-03-20 21:06:02 +0000579 D.diag_MaybeFallThrough_HasNoReturn =
580 diag::warn_falloff_noreturn_function;
581 D.diag_MaybeFallThrough_ReturnsNonVoid =
582 diag::warn_maybe_falloff_nonvoid_function;
583 D.diag_AlwaysFallThrough_HasNoReturn =
584 diag::warn_falloff_noreturn_function;
585 D.diag_AlwaysFallThrough_ReturnsNonVoid =
586 diag::warn_falloff_nonvoid_function;
Douglas Gregor24f27692010-04-16 23:28:44 +0000587
588 // Don't suggest that virtual functions be marked "noreturn", since they
589 // might be overridden by non-noreturn functions.
590 bool isVirtualMethod = false;
591 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
592 isVirtualMethod = Method->isVirtual();
593
Douglas Gregor0de57202011-10-10 18:15:57 +0000594 // Don't suggest that template instantiations be marked "noreturn"
595 bool isTemplateInstantiation = false;
Ted Kremenek85825ae2011-12-01 00:59:17 +0000596 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
597 isTemplateInstantiation = Function->isTemplateInstantiation();
Douglas Gregor0de57202011-10-10 18:15:57 +0000598
599 if (!isVirtualMethod && !isTemplateInstantiation)
Douglas Gregor24f27692010-04-16 23:28:44 +0000600 D.diag_NeverFallThroughOrReturn =
601 diag::warn_suggest_noreturn_function;
602 else
603 D.diag_NeverFallThroughOrReturn = 0;
604
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000605 D.funMode = Function;
Ted Kremenek918fe842010-03-20 21:06:02 +0000606 return D;
607 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000608
Eric Fiselier709d1b32016-10-27 07:30:31 +0000609 static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
610 CheckFallThroughDiagnostics D;
611 D.FuncLoc = Func->getLocation();
612 D.diag_MaybeFallThrough_HasNoReturn = 0;
613 D.diag_MaybeFallThrough_ReturnsNonVoid =
614 diag::warn_maybe_falloff_nonvoid_coroutine;
615 D.diag_AlwaysFallThrough_HasNoReturn = 0;
616 D.diag_AlwaysFallThrough_ReturnsNonVoid =
617 diag::warn_falloff_nonvoid_coroutine;
618 D.funMode = Coroutine;
619 return D;
620 }
621
Ted Kremenek918fe842010-03-20 21:06:02 +0000622 static CheckFallThroughDiagnostics MakeForBlock() {
623 CheckFallThroughDiagnostics D;
624 D.diag_MaybeFallThrough_HasNoReturn =
625 diag::err_noreturn_block_has_return_expr;
626 D.diag_MaybeFallThrough_ReturnsNonVoid =
627 diag::err_maybe_falloff_nonvoid_block;
628 D.diag_AlwaysFallThrough_HasNoReturn =
629 diag::err_noreturn_block_has_return_expr;
630 D.diag_AlwaysFallThrough_ReturnsNonVoid =
631 diag::err_falloff_nonvoid_block;
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000632 D.diag_NeverFallThroughOrReturn = 0;
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000633 D.funMode = Block;
634 return D;
635 }
636
637 static CheckFallThroughDiagnostics MakeForLambda() {
638 CheckFallThroughDiagnostics D;
639 D.diag_MaybeFallThrough_HasNoReturn =
640 diag::err_noreturn_lambda_has_return_expr;
641 D.diag_MaybeFallThrough_ReturnsNonVoid =
642 diag::warn_maybe_falloff_nonvoid_lambda;
643 D.diag_AlwaysFallThrough_HasNoReturn =
644 diag::err_noreturn_lambda_has_return_expr;
645 D.diag_AlwaysFallThrough_ReturnsNonVoid =
646 diag::warn_falloff_nonvoid_lambda;
647 D.diag_NeverFallThroughOrReturn = 0;
648 D.funMode = Lambda;
Ted Kremenek918fe842010-03-20 21:06:02 +0000649 return D;
650 }
Ted Kremenek0b405322010-03-23 00:13:23 +0000651
David Blaikie9c902b52011-09-25 23:23:43 +0000652 bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
Ted Kremenek918fe842010-03-20 21:06:02 +0000653 bool HasNoReturn) const {
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000654 if (funMode == Function) {
Argyrios Kyrtzidis1cb0de12010-12-15 18:44:22 +0000655 return (ReturnsVoid ||
Alp Tokerd4a3f0e2014-06-15 23:30:39 +0000656 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
657 FuncLoc)) &&
658 (!HasNoReturn ||
659 D.isIgnored(diag::warn_noreturn_function_has_return_expr,
660 FuncLoc)) &&
661 (!ReturnsVoid ||
662 D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
Ted Kremenek918fe842010-03-20 21:06:02 +0000663 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000664 if (funMode == Coroutine) {
665 return (ReturnsVoid ||
666 D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
667 D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
668 FuncLoc)) &&
669 (!HasNoReturn);
670 }
Douglas Gregorcf11eb72012-02-15 16:20:15 +0000671 // For blocks / lambdas.
Fariborz Jahanian5ce22792014-04-03 23:06:35 +0000672 return ReturnsVoid && !HasNoReturn;
Ted Kremenek918fe842010-03-20 21:06:02 +0000673 }
674};
675
Hans Wennborgdcfba332015-10-06 23:40:43 +0000676} // anonymous namespace
Dan Gohman28ade552010-07-26 21:25:24 +0000677
Ted Kremenek918fe842010-03-20 21:06:02 +0000678/// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
679/// function that should return a value. Check that we don't fall off the end
680/// of a noreturn function. We assume that functions and blocks not marked
681/// noreturn will return.
682static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
Ted Kremenek1767a272011-02-23 01:51:48 +0000683 const BlockExpr *blkExpr,
Ted Kremenek918fe842010-03-20 21:06:02 +0000684 const CheckFallThroughDiagnostics& CD,
Ted Kremenek81ce1c82011-10-24 01:32:45 +0000685 AnalysisDeclContext &AC) {
Ted Kremenek918fe842010-03-20 21:06:02 +0000686
687 bool ReturnsVoid = false;
688 bool HasNoReturn = false;
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000689 bool IsCoroutine = S.getCurFunction() && S.getCurFunction()->isCoroutine();
Ted Kremenek918fe842010-03-20 21:06:02 +0000690
Eric Fiselier709d1b32016-10-27 07:30:31 +0000691 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
692 if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
693 ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
694 else
695 ReturnsVoid = FD->getReturnType()->isVoidType();
Richard Smith10876ef2013-01-17 01:30:42 +0000696 HasNoReturn = FD->isNoReturn();
Ted Kremenek918fe842010-03-20 21:06:02 +0000697 }
Eric Fiselier709d1b32016-10-27 07:30:31 +0000698 else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
Alp Toker314cc812014-01-25 16:55:45 +0000699 ReturnsVoid = MD->getReturnType()->isVoidType();
Ted Kremenek918fe842010-03-20 21:06:02 +0000700 HasNoReturn = MD->hasAttr<NoReturnAttr>();
701 }
702 else if (isa<BlockDecl>(D)) {
Ted Kremenek1767a272011-02-23 01:51:48 +0000703 QualType BlockTy = blkExpr->getType();
Ted Kremenek0b405322010-03-23 00:13:23 +0000704 if (const FunctionType *FT =
Ted Kremenek918fe842010-03-20 21:06:02 +0000705 BlockTy->getPointeeType()->getAs<FunctionType>()) {
Alp Toker314cc812014-01-25 16:55:45 +0000706 if (FT->getReturnType()->isVoidType())
Ted Kremenek918fe842010-03-20 21:06:02 +0000707 ReturnsVoid = true;
708 if (FT->getNoReturnAttr())
709 HasNoReturn = true;
710 }
711 }
712
David Blaikie9c902b52011-09-25 23:23:43 +0000713 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenek918fe842010-03-20 21:06:02 +0000714
715 // Short circuit for compilation speed.
716 if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
717 return;
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000718 SourceLocation LBrace = Body->getLocStart(), RBrace = Body->getLocEnd();
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000719 auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
720 if (IsCoroutine)
721 S.Diag(Loc, DiagID) << S.getCurFunction()->CoroutinePromise->getType();
722 else
723 S.Diag(Loc, DiagID);
724 };
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000725 // Either in a function body compound statement, or a function-try-block.
726 switch (CheckFallThrough(AC)) {
727 case UnknownFallThrough:
728 break;
John McCall5c6ec8c2010-05-16 09:34:11 +0000729
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000730 case MaybeFallThrough:
731 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000732 EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000733 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000734 EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000735 break;
736 case AlwaysFallThrough:
737 if (HasNoReturn)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000738 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000739 else if (!ReturnsVoid)
Eric Fiselierda8f9b52017-05-25 02:16:53 +0000740 EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000741 break;
742 case NeverFallThroughOrReturn:
743 if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
744 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
745 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
746 } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
747 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
748 } else {
749 S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
Chandler Carruthc841b6e2011-08-31 09:01:53 +0000750 }
Aaron Ballmanb2e2c1b2014-10-24 13:19:19 +0000751 }
752 break;
753 case NeverFallThrough:
754 break;
Ted Kremenek918fe842010-03-20 21:06:02 +0000755 }
756}
757
758//===----------------------------------------------------------------------===//
Ted Kremenekb749a6d2011-01-15 02:58:47 +0000759// -Wuninitialized
760//===----------------------------------------------------------------------===//
761
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000762namespace {
Chandler Carruth4e021822011-04-05 06:48:00 +0000763/// ContainsReference - A visitor class to search for references to
764/// a particular declaration (the needle) within any evaluated component of an
765/// expression (recursively).
Scott Douglass503fc392015-06-10 13:53:15 +0000766class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
Chandler Carruth4e021822011-04-05 06:48:00 +0000767 bool FoundReference;
768 const DeclRefExpr *Needle;
769
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000770public:
Scott Douglass503fc392015-06-10 13:53:15 +0000771 typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
Chandler Carruth4e021822011-04-05 06:48:00 +0000772
Scott Douglass503fc392015-06-10 13:53:15 +0000773 ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
774 : Inherited(Context), FoundReference(false), Needle(Needle) {}
775
776 void VisitExpr(const Expr *E) {
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000777 // Stop evaluating if we already have a reference.
Chandler Carruth4e021822011-04-05 06:48:00 +0000778 if (FoundReference)
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000779 return;
Chandler Carruth4e021822011-04-05 06:48:00 +0000780
Scott Douglass503fc392015-06-10 13:53:15 +0000781 Inherited::VisitExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000782 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000783
Scott Douglass503fc392015-06-10 13:53:15 +0000784 void VisitDeclRefExpr(const DeclRefExpr *E) {
Chandler Carruth4e021822011-04-05 06:48:00 +0000785 if (E == Needle)
786 FoundReference = true;
787 else
Scott Douglass503fc392015-06-10 13:53:15 +0000788 Inherited::VisitDeclRefExpr(E);
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000789 }
Chandler Carruth4e021822011-04-05 06:48:00 +0000790
791 bool doesContainReference() const { return FoundReference; }
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000792};
Hans Wennborgdcfba332015-10-06 23:40:43 +0000793} // anonymous namespace
Ted Kremenekb8d8c4e2011-04-04 20:56:00 +0000794
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000795static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000796 QualType VariableTy = VD->getType().getCanonicalType();
797 if (VariableTy->isBlockPointerType() &&
798 !VD->hasAttr<BlocksAttr>()) {
Nico Weber3c68ee92014-07-08 23:46:20 +0000799 S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
800 << VD->getDeclName()
801 << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
Fariborz Jahanian429fadb2012-03-08 00:22:50 +0000802 return true;
803 }
Richard Smithf7ec86a2013-09-20 00:27:40 +0000804
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000805 // Don't issue a fixit if there is already an initializer.
806 if (VD->getInit())
807 return false;
Richard Trieu2cdcf822012-05-03 01:09:59 +0000808
809 // Don't suggest a fixit inside macros.
810 if (VD->getLocEnd().isMacroID())
811 return false;
812
Alp Tokerb6cc5922014-05-03 03:45:55 +0000813 SourceLocation Loc = S.getLocForEndOfToken(VD->getLocEnd());
Richard Smithf7ec86a2013-09-20 00:27:40 +0000814
815 // Suggest possible initialization (if any).
816 std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
817 if (Init.empty())
818 return false;
819
Richard Smith8d06f422012-01-12 23:53:29 +0000820 S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
821 << FixItHint::CreateInsertion(Loc, Init);
822 return true;
David Blaikiee5f9a9e2011-09-10 05:35:08 +0000823}
824
Richard Smith1bb8edb82012-05-26 06:20:46 +0000825/// Create a fixit to remove an if-like statement, on the assumption that its
826/// condition is CondVal.
827static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
828 const Stmt *Else, bool CondVal,
829 FixItHint &Fixit1, FixItHint &Fixit2) {
830 if (CondVal) {
831 // If condition is always true, remove all but the 'then'.
832 Fixit1 = FixItHint::CreateRemoval(
833 CharSourceRange::getCharRange(If->getLocStart(),
834 Then->getLocStart()));
835 if (Else) {
Craig Topper07fa1762015-11-15 02:31:46 +0000836 SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getLocEnd());
Richard Smith1bb8edb82012-05-26 06:20:46 +0000837 Fixit2 = FixItHint::CreateRemoval(
838 SourceRange(ElseKwLoc, Else->getLocEnd()));
839 }
840 } else {
841 // If condition is always false, remove all but the 'else'.
842 if (Else)
843 Fixit1 = FixItHint::CreateRemoval(
844 CharSourceRange::getCharRange(If->getLocStart(),
845 Else->getLocStart()));
846 else
847 Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
848 }
849}
850
851/// DiagUninitUse -- Helper function to produce a diagnostic for an
852/// uninitialized use of a variable.
853static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
854 bool IsCapturedByBlock) {
855 bool Diagnosed = false;
856
Richard Smithba8071e2013-09-12 18:49:10 +0000857 switch (Use.getKind()) {
858 case UninitUse::Always:
859 S.Diag(Use.getUser()->getLocStart(), diag::warn_uninit_var)
860 << VD->getDeclName() << IsCapturedByBlock
861 << Use.getUser()->getSourceRange();
862 return;
863
864 case UninitUse::AfterDecl:
865 case UninitUse::AfterCall:
866 S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
867 << VD->getDeclName() << IsCapturedByBlock
868 << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
869 << const_cast<DeclContext*>(VD->getLexicalDeclContext())
870 << VD->getSourceRange();
871 S.Diag(Use.getUser()->getLocStart(), diag::note_uninit_var_use)
872 << IsCapturedByBlock << Use.getUser()->getSourceRange();
873 return;
874
875 case UninitUse::Maybe:
876 case UninitUse::Sometimes:
877 // Carry on to report sometimes-uninitialized branches, if possible,
878 // or a 'may be used uninitialized' diagnostic otherwise.
879 break;
880 }
881
Richard Smith1bb8edb82012-05-26 06:20:46 +0000882 // Diagnose each branch which leads to a sometimes-uninitialized use.
Richard Smith4323bf82012-05-25 02:17:09 +0000883 for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
884 I != E; ++I) {
Richard Smith1bb8edb82012-05-26 06:20:46 +0000885 assert(Use.getKind() == UninitUse::Sometimes);
886
887 const Expr *User = Use.getUser();
Richard Smith4323bf82012-05-25 02:17:09 +0000888 const Stmt *Term = I->Terminator;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000889
890 // Information used when building the diagnostic.
Richard Smith4323bf82012-05-25 02:17:09 +0000891 unsigned DiagKind;
David Blaikie1d202a62012-10-08 01:11:04 +0000892 StringRef Str;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000893 SourceRange Range;
894
Stefanus Du Toitb3318502013-03-01 21:41:22 +0000895 // FixIts to suppress the diagnostic by removing the dead condition.
Richard Smith1bb8edb82012-05-26 06:20:46 +0000896 // For all binary terminators, branch 0 is taken if the condition is true,
897 // and branch 1 is taken if the condition is false.
898 int RemoveDiagKind = -1;
899 const char *FixitStr =
900 S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
901 : (I->Output ? "1" : "0");
902 FixItHint Fixit1, Fixit2;
903
Richard Smithba8071e2013-09-12 18:49:10 +0000904 switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
Richard Smith4323bf82012-05-25 02:17:09 +0000905 default:
Richard Smith1bb8edb82012-05-26 06:20:46 +0000906 // Don't know how to report this. Just fall back to 'may be used
Richard Smithba8071e2013-09-12 18:49:10 +0000907 // uninitialized'. FIXME: Can this happen?
Richard Smith4323bf82012-05-25 02:17:09 +0000908 continue;
909
910 // "condition is true / condition is false".
Richard Smith1bb8edb82012-05-26 06:20:46 +0000911 case Stmt::IfStmtClass: {
912 const IfStmt *IS = cast<IfStmt>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000913 DiagKind = 0;
914 Str = "if";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000915 Range = IS->getCond()->getSourceRange();
916 RemoveDiagKind = 0;
917 CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
918 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000919 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000920 }
921 case Stmt::ConditionalOperatorClass: {
922 const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
Richard Smith4323bf82012-05-25 02:17:09 +0000923 DiagKind = 0;
924 Str = "?:";
Richard Smith1bb8edb82012-05-26 06:20:46 +0000925 Range = CO->getCond()->getSourceRange();
926 RemoveDiagKind = 0;
927 CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
928 I->Output, Fixit1, Fixit2);
Richard Smith4323bf82012-05-25 02:17:09 +0000929 break;
Richard Smith1bb8edb82012-05-26 06:20:46 +0000930 }
Richard Smith4323bf82012-05-25 02:17:09 +0000931 case Stmt::BinaryOperatorClass: {
932 const BinaryOperator *BO = cast<BinaryOperator>(Term);
933 if (!BO->isLogicalOp())
934 continue;
935 DiagKind = 0;
936 Str = BO->getOpcodeStr();
937 Range = BO->getLHS()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000938 RemoveDiagKind = 0;
939 if ((BO->getOpcode() == BO_LAnd && I->Output) ||
940 (BO->getOpcode() == BO_LOr && !I->Output))
941 // true && y -> y, false || y -> y.
942 Fixit1 = FixItHint::CreateRemoval(SourceRange(BO->getLocStart(),
943 BO->getOperatorLoc()));
944 else
945 // false && y -> false, true || y -> true.
946 Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000947 break;
948 }
949
950 // "loop is entered / loop is exited".
951 case Stmt::WhileStmtClass:
952 DiagKind = 1;
953 Str = "while";
954 Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000955 RemoveDiagKind = 1;
956 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000957 break;
958 case Stmt::ForStmtClass:
959 DiagKind = 1;
960 Str = "for";
961 Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000962 RemoveDiagKind = 1;
963 if (I->Output)
964 Fixit1 = FixItHint::CreateRemoval(Range);
965 else
966 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000967 break;
Richard Smithba8071e2013-09-12 18:49:10 +0000968 case Stmt::CXXForRangeStmtClass:
969 if (I->Output == 1) {
970 // The use occurs if a range-based for loop's body never executes.
971 // That may be impossible, and there's no syntactic fix for this,
972 // so treat it as a 'may be uninitialized' case.
973 continue;
974 }
975 DiagKind = 1;
976 Str = "for";
977 Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
978 break;
Richard Smith4323bf82012-05-25 02:17:09 +0000979
980 // "condition is true / loop is exited".
981 case Stmt::DoStmtClass:
982 DiagKind = 2;
983 Str = "do";
984 Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
Richard Smith1bb8edb82012-05-26 06:20:46 +0000985 RemoveDiagKind = 1;
986 Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
Richard Smith4323bf82012-05-25 02:17:09 +0000987 break;
988
989 // "switch case is taken".
990 case Stmt::CaseStmtClass:
991 DiagKind = 3;
992 Str = "case";
993 Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
994 break;
995 case Stmt::DefaultStmtClass:
996 DiagKind = 3;
997 Str = "default";
998 Range = cast<DefaultStmt>(Term)->getDefaultLoc();
999 break;
1000 }
1001
Richard Smith1bb8edb82012-05-26 06:20:46 +00001002 S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
1003 << VD->getDeclName() << IsCapturedByBlock << DiagKind
1004 << Str << I->Output << Range;
1005 S.Diag(User->getLocStart(), diag::note_uninit_var_use)
1006 << IsCapturedByBlock << User->getSourceRange();
1007 if (RemoveDiagKind != -1)
1008 S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
1009 << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
1010
1011 Diagnosed = true;
Richard Smith4323bf82012-05-25 02:17:09 +00001012 }
Richard Smith1bb8edb82012-05-26 06:20:46 +00001013
1014 if (!Diagnosed)
Richard Smithba8071e2013-09-12 18:49:10 +00001015 S.Diag(Use.getUser()->getLocStart(), diag::warn_maybe_uninit_var)
Richard Smith1bb8edb82012-05-26 06:20:46 +00001016 << VD->getDeclName() << IsCapturedByBlock
1017 << Use.getUser()->getSourceRange();
Richard Smith4323bf82012-05-25 02:17:09 +00001018}
1019
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001020/// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
1021/// uninitialized variable. This manages the different forms of diagnostic
1022/// emitted for particular types of uses. Returns true if the use was diagnosed
Richard Smith4323bf82012-05-25 02:17:09 +00001023/// as a warning. If a particular use is one we omit warnings for, returns
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001024/// false.
1025static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
Richard Smith4323bf82012-05-25 02:17:09 +00001026 const UninitUse &Use,
Ted Kremenek596fa162011-10-13 18:50:06 +00001027 bool alwaysReportSelfInit = false) {
Richard Smith4323bf82012-05-25 02:17:09 +00001028 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
Richard Trieu43a2fc72012-05-09 21:08:22 +00001029 // Inspect the initializer of the variable declaration which is
1030 // being referenced prior to its initialization. We emit
1031 // specialized diagnostics for self-initialization, and we
1032 // specifically avoid warning about self references which take the
1033 // form of:
1034 //
1035 // int x = x;
1036 //
1037 // This is used to indicate to GCC that 'x' is intentionally left
1038 // uninitialized. Proven code paths which access 'x' in
1039 // an uninitialized state after this will still warn.
1040 if (const Expr *Initializer = VD->getInit()) {
1041 if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
1042 return false;
Chandler Carruth895904da2011-04-05 18:18:05 +00001043
Richard Trieu43a2fc72012-05-09 21:08:22 +00001044 ContainsReference CR(S.Context, DRE);
Scott Douglass503fc392015-06-10 13:53:15 +00001045 CR.Visit(Initializer);
Richard Trieu43a2fc72012-05-09 21:08:22 +00001046 if (CR.doesContainReference()) {
Chandler Carruth895904da2011-04-05 18:18:05 +00001047 S.Diag(DRE->getLocStart(),
1048 diag::warn_uninit_self_reference_in_init)
Richard Trieu43a2fc72012-05-09 21:08:22 +00001049 << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
1050 return true;
Chandler Carruth895904da2011-04-05 18:18:05 +00001051 }
Chandler Carruth895904da2011-04-05 18:18:05 +00001052 }
Richard Trieu43a2fc72012-05-09 21:08:22 +00001053
Richard Smith1bb8edb82012-05-26 06:20:46 +00001054 DiagUninitUse(S, VD, Use, false);
Chandler Carruth895904da2011-04-05 18:18:05 +00001055 } else {
Richard Smith4323bf82012-05-25 02:17:09 +00001056 const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
Richard Smith1bb8edb82012-05-26 06:20:46 +00001057 if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
1058 S.Diag(BE->getLocStart(),
1059 diag::warn_uninit_byref_blockvar_captured_by_block)
Fariborz Jahanian429fadb2012-03-08 00:22:50 +00001060 << VD->getDeclName();
Richard Smith1bb8edb82012-05-26 06:20:46 +00001061 else
1062 DiagUninitUse(S, VD, Use, true);
Chandler Carruth895904da2011-04-05 18:18:05 +00001063 }
1064
1065 // Report where the variable was declared when the use wasn't within
David Blaikiee5f9a9e2011-09-10 05:35:08 +00001066 // the initializer of that declaration & we didn't already suggest
1067 // an initialization fixit.
Richard Trieu43a2fc72012-05-09 21:08:22 +00001068 if (!SuggestInitializationFixit(S, VD))
Reid Klecknerf463a8a2016-04-29 00:37:43 +00001069 S.Diag(VD->getLocStart(), diag::note_var_declared_here)
Chandler Carruth895904da2011-04-05 18:18:05 +00001070 << VD->getDeclName();
1071
Chandler Carruthdd8f0d02011-04-05 18:27:05 +00001072 return true;
Chandler Carruth7a037202011-04-05 18:18:08 +00001073}
1074
Richard Smith84837d52012-05-03 18:27:39 +00001075namespace {
1076 class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
1077 public:
1078 FallthroughMapper(Sema &S)
1079 : FoundSwitchStatements(false),
1080 S(S) {
1081 }
1082
1083 bool foundSwitchStatements() const { return FoundSwitchStatements; }
1084
1085 void markFallthroughVisited(const AttributedStmt *Stmt) {
1086 bool Found = FallthroughStmts.erase(Stmt);
1087 assert(Found);
Kaelyn Uhrain29a8eeb2012-05-03 19:46:38 +00001088 (void)Found;
Richard Smith84837d52012-05-03 18:27:39 +00001089 }
1090
1091 typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
1092
1093 const AttrStmts &getFallthroughStmts() const {
1094 return FallthroughStmts;
1095 }
1096
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001097 void fillReachableBlocks(CFG *Cfg) {
1098 assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
1099 std::deque<const CFGBlock *> BlockQueue;
1100
1101 ReachableBlocks.insert(&Cfg->getEntry());
1102 BlockQueue.push_back(&Cfg->getEntry());
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001103 // Mark all case blocks reachable to avoid problems with switching on
1104 // constants, covered enums, etc.
1105 // These blocks can contain fall-through annotations, and we don't want to
1106 // issue a warn_fallthrough_attr_unreachable for them.
Aaron Ballmane5195222014-05-15 20:50:47 +00001107 for (const auto *B : *Cfg) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001108 const Stmt *L = B->getLabel();
David Blaikie82e95a32014-11-19 07:49:47 +00001109 if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001110 BlockQueue.push_back(B);
1111 }
1112
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001113 while (!BlockQueue.empty()) {
1114 const CFGBlock *P = BlockQueue.front();
1115 BlockQueue.pop_front();
1116 for (CFGBlock::const_succ_iterator I = P->succ_begin(),
1117 E = P->succ_end();
1118 I != E; ++I) {
David Blaikie82e95a32014-11-19 07:49:47 +00001119 if (*I && ReachableBlocks.insert(*I).second)
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001120 BlockQueue.push_back(*I);
1121 }
1122 }
1123 }
1124
Richard Smith7532d372017-03-22 01:49:19 +00001125 bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
1126 bool IsTemplateInstantiation) {
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001127 assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
1128
Richard Smith84837d52012-05-03 18:27:39 +00001129 int UnannotatedCnt = 0;
1130 AnnotatedCnt = 0;
1131
Aaron Ballmane5195222014-05-15 20:50:47 +00001132 std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
Richard Smith84837d52012-05-03 18:27:39 +00001133 while (!BlockQueue.empty()) {
1134 const CFGBlock *P = BlockQueue.front();
1135 BlockQueue.pop_front();
Nick Lewyckycdf11082014-02-27 02:43:25 +00001136 if (!P) continue;
Richard Smith84837d52012-05-03 18:27:39 +00001137
1138 const Stmt *Term = P->getTerminator();
1139 if (Term && isa<SwitchStmt>(Term))
1140 continue; // Switch statement, good.
1141
1142 const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
1143 if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
1144 continue; // Previous case label has no statements, good.
1145
Alexander Kornienko09f15f32013-01-25 20:44:56 +00001146 const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
1147 if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
1148 continue; // Case label is preceded with a normal label, good.
1149
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001150 if (!ReachableBlocks.count(P)) {
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001151 for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
1152 ElemEnd = P->rend();
1153 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001154 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
1155 if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
Richard Smith7532d372017-03-22 01:49:19 +00001156 // Don't issue a warning for an unreachable fallthrough
1157 // attribute in template instantiations as it may not be
1158 // unreachable in all instantiations of the template.
1159 if (!IsTemplateInstantiation)
1160 S.Diag(AS->getLocStart(),
1161 diag::warn_fallthrough_attr_unreachable);
Richard Smith84837d52012-05-03 18:27:39 +00001162 markFallthroughVisited(AS);
1163 ++AnnotatedCnt;
Alexander Kornienkoc121b9b2013-02-07 02:17:19 +00001164 break;
Richard Smith84837d52012-05-03 18:27:39 +00001165 }
1166 // Don't care about other unreachable statements.
1167 }
1168 }
1169 // If there are no unreachable statements, this may be a special
1170 // case in CFG:
1171 // case X: {
1172 // A a; // A has a destructor.
1173 // break;
1174 // }
1175 // // <<<< This place is represented by a 'hanging' CFG block.
1176 // case Y:
1177 continue;
1178 }
1179
1180 const Stmt *LastStmt = getLastStmt(*P);
1181 if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
1182 markFallthroughVisited(AS);
1183 ++AnnotatedCnt;
1184 continue; // Fallthrough annotation, good.
1185 }
1186
1187 if (!LastStmt) { // This block contains no executable statements.
1188 // Traverse its predecessors.
1189 std::copy(P->pred_begin(), P->pred_end(),
1190 std::back_inserter(BlockQueue));
1191 continue;
1192 }
1193
1194 ++UnannotatedCnt;
1195 }
1196 return !!UnannotatedCnt;
1197 }
1198
1199 // RecursiveASTVisitor setup.
1200 bool shouldWalkTypesOfTypeLocs() const { return false; }
1201
1202 bool VisitAttributedStmt(AttributedStmt *S) {
1203 if (asFallThroughAttr(S))
1204 FallthroughStmts.insert(S);
1205 return true;
1206 }
1207
1208 bool VisitSwitchStmt(SwitchStmt *S) {
1209 FoundSwitchStatements = true;
1210 return true;
1211 }
1212
Alexander Kornienkoa9c809f2013-04-02 15:20:32 +00001213 // We don't want to traverse local type declarations. We analyze their
1214 // methods separately.
1215 bool TraverseDecl(Decl *D) { return true; }
1216
Alexander Kornienkobf911642014-06-24 15:28:21 +00001217 // We analyze lambda bodies separately. Skip them here.
1218 bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
1219
Richard Smith84837d52012-05-03 18:27:39 +00001220 private:
1221
1222 static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
1223 if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
1224 if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
1225 return AS;
1226 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001227 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001228 }
1229
1230 static const Stmt *getLastStmt(const CFGBlock &B) {
1231 if (const Stmt *Term = B.getTerminator())
1232 return Term;
1233 for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
1234 ElemEnd = B.rend();
1235 ElemIt != ElemEnd; ++ElemIt) {
David Blaikie00be69a2013-02-23 00:29:34 +00001236 if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
1237 return CS->getStmt();
Richard Smith84837d52012-05-03 18:27:39 +00001238 }
1239 // Workaround to detect a statement thrown out by CFGBuilder:
1240 // case X: {} case Y:
1241 // case X: ; case Y:
1242 if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
1243 if (!isa<SwitchCase>(SW->getSubStmt()))
1244 return SW->getSubStmt();
1245
Craig Topperc3ec1492014-05-26 06:22:03 +00001246 return nullptr;
Richard Smith84837d52012-05-03 18:27:39 +00001247 }
1248
1249 bool FoundSwitchStatements;
1250 AttrStmts FallthroughStmts;
1251 Sema &S;
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001252 llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
Richard Smith84837d52012-05-03 18:27:39 +00001253 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00001254} // anonymous namespace
Richard Smith84837d52012-05-03 18:27:39 +00001255
Richard Smith4f902c72016-03-08 00:32:55 +00001256static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
1257 SourceLocation Loc) {
1258 TokenValue FallthroughTokens[] = {
1259 tok::l_square, tok::l_square,
1260 PP.getIdentifierInfo("fallthrough"),
1261 tok::r_square, tok::r_square
1262 };
1263
1264 TokenValue ClangFallthroughTokens[] = {
1265 tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
1266 tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
1267 tok::r_square, tok::r_square
1268 };
1269
1270 bool PreferClangAttr = !PP.getLangOpts().CPlusPlus1z;
1271
1272 StringRef MacroName;
1273 if (PreferClangAttr)
1274 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1275 if (MacroName.empty())
1276 MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
1277 if (MacroName.empty() && !PreferClangAttr)
1278 MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
1279 if (MacroName.empty())
1280 MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
1281 return MacroName;
1282}
1283
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001284static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
Alexis Hunt2178f142012-06-15 21:22:05 +00001285 bool PerFunction) {
Ted Kremenekda5919f2012-11-12 21:20:48 +00001286 // Only perform this analysis when using C++11. There is no good workflow
1287 // for this warning when not using C++11. There is no good way to silence
1288 // the warning (no attribute is available) unless we are using C++11's support
1289 // for generalized attributes. Once could use pragmas to silence the warning,
1290 // but as a general solution that is gross and not in the spirit of this
1291 // warning.
1292 //
1293 // NOTE: This an intermediate solution. There are on-going discussions on
1294 // how to properly support this warning outside of C++11 with an annotation.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001295 if (!AC.getASTContext().getLangOpts().CPlusPlus11)
Ted Kremenekda5919f2012-11-12 21:20:48 +00001296 return;
1297
Richard Smith84837d52012-05-03 18:27:39 +00001298 FallthroughMapper FM(S);
1299 FM.TraverseStmt(AC.getBody());
1300
1301 if (!FM.foundSwitchStatements())
1302 return;
1303
Alexis Hunt2178f142012-06-15 21:22:05 +00001304 if (PerFunction && FM.getFallthroughStmts().empty())
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001305 return;
1306
Richard Smith84837d52012-05-03 18:27:39 +00001307 CFG *Cfg = AC.getCFG();
1308
1309 if (!Cfg)
1310 return;
1311
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001312 FM.fillReachableBlocks(Cfg);
Richard Smith84837d52012-05-03 18:27:39 +00001313
Pete Cooper57d3f142015-07-30 17:22:52 +00001314 for (const CFGBlock *B : llvm::reverse(*Cfg)) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001315 const Stmt *Label = B->getLabel();
Richard Smith84837d52012-05-03 18:27:39 +00001316
1317 if (!Label || !isa<SwitchCase>(Label))
1318 continue;
1319
Alexander Kornienkoafed1dd2013-01-30 03:49:44 +00001320 int AnnotatedCnt;
1321
Richard Smith7532d372017-03-22 01:49:19 +00001322 bool IsTemplateInstantiation = false;
1323 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
1324 IsTemplateInstantiation = Function->isTemplateInstantiation();
1325 if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
1326 IsTemplateInstantiation))
Richard Smith84837d52012-05-03 18:27:39 +00001327 continue;
1328
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00001329 S.Diag(Label->getLocStart(),
Alexis Hunt2178f142012-06-15 21:22:05 +00001330 PerFunction ? diag::warn_unannotated_fallthrough_per_function
1331 : diag::warn_unannotated_fallthrough);
Richard Smith84837d52012-05-03 18:27:39 +00001332
1333 if (!AnnotatedCnt) {
1334 SourceLocation L = Label->getLocStart();
1335 if (L.isMacroID())
1336 continue;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001337 if (S.getLangOpts().CPlusPlus11) {
Alexander Kornienko55488792013-01-25 15:49:34 +00001338 const Stmt *Term = B->getTerminator();
1339 // Skip empty cases.
1340 while (B->empty() && !Term && B->succ_size() == 1) {
1341 B = *B->succ_begin();
1342 Term = B->getTerminator();
1343 }
1344 if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001345 Preprocessor &PP = S.getPreprocessor();
Richard Smith4f902c72016-03-08 00:32:55 +00001346 StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001347 SmallString<64> TextToInsert(AnnotationSpelling);
1348 TextToInsert += "; ";
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001349 S.Diag(L, diag::note_insert_fallthrough_fixit) <<
Alexander Kornienkoe61e5622012-09-28 22:24:03 +00001350 AnnotationSpelling <<
Dmitri Gribenko6743e042012-09-29 11:40:46 +00001351 FixItHint::CreateInsertion(L, TextToInsert);
Alexander Kornienko246e85d2012-05-26 00:49:15 +00001352 }
Richard Smith84837d52012-05-03 18:27:39 +00001353 }
1354 S.Diag(L, diag::note_insert_break_fixit) <<
1355 FixItHint::CreateInsertion(L, "break; ");
1356 }
1357 }
1358
Aaron Ballmane5195222014-05-15 20:50:47 +00001359 for (const auto *F : FM.getFallthroughStmts())
Richard Smith4f902c72016-03-08 00:32:55 +00001360 S.Diag(F->getLocStart(), diag::err_fallthrough_attr_invalid_placement);
Richard Smith84837d52012-05-03 18:27:39 +00001361}
1362
Jordan Rose25c0ea82012-10-29 17:46:47 +00001363static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
1364 const Stmt *S) {
Jordan Rose76831c62012-10-11 16:10:19 +00001365 assert(S);
1366
1367 do {
1368 switch (S->getStmtClass()) {
Jordan Rose76831c62012-10-11 16:10:19 +00001369 case Stmt::ForStmtClass:
1370 case Stmt::WhileStmtClass:
1371 case Stmt::CXXForRangeStmtClass:
1372 case Stmt::ObjCForCollectionStmtClass:
1373 return true;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001374 case Stmt::DoStmtClass: {
1375 const Expr *Cond = cast<DoStmt>(S)->getCond();
1376 llvm::APSInt Val;
1377 if (!Cond->EvaluateAsInt(Val, Ctx))
1378 return true;
1379 return Val.getBoolValue();
1380 }
Jordan Rose76831c62012-10-11 16:10:19 +00001381 default:
1382 break;
1383 }
1384 } while ((S = PM.getParent(S)));
1385
1386 return false;
1387}
1388
Jordan Rosed3934582012-09-28 22:21:30 +00001389static void diagnoseRepeatedUseOfWeak(Sema &S,
1390 const sema::FunctionScopeInfo *CurFn,
Jordan Rose76831c62012-10-11 16:10:19 +00001391 const Decl *D,
1392 const ParentMap &PM) {
Jordan Rosed3934582012-09-28 22:21:30 +00001393 typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
1394 typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
1395 typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001396 typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
1397 StmtUsesPair;
Jordan Rosed3934582012-09-28 22:21:30 +00001398
Jordan Rose25c0ea82012-10-29 17:46:47 +00001399 ASTContext &Ctx = S.getASTContext();
1400
Jordan Rosed3934582012-09-28 22:21:30 +00001401 const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
1402
1403 // Extract all weak objects that are referenced more than once.
1404 SmallVector<StmtUsesPair, 8> UsesByStmt;
1405 for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
1406 I != E; ++I) {
1407 const WeakUseVector &Uses = I->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001408
1409 // Find the first read of the weak object.
1410 WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
1411 for ( ; UI != UE; ++UI) {
1412 if (UI->isUnsafe())
1413 break;
1414 }
1415
1416 // If there were only writes to this object, don't warn.
1417 if (UI == UE)
1418 continue;
1419
Jordan Rose76831c62012-10-11 16:10:19 +00001420 // If there was only one read, followed by any number of writes, and the
Jordan Rose25c0ea82012-10-29 17:46:47 +00001421 // read is not within a loop, don't warn. Additionally, don't warn in a
1422 // loop if the base object is a local variable -- local variables are often
1423 // changed in loops.
Jordan Rose76831c62012-10-11 16:10:19 +00001424 if (UI == Uses.begin()) {
1425 WeakUseVector::const_iterator UI2 = UI;
1426 for (++UI2; UI2 != UE; ++UI2)
1427 if (UI2->isUnsafe())
1428 break;
1429
Jordan Rose25c0ea82012-10-29 17:46:47 +00001430 if (UI2 == UE) {
1431 if (!isInLoop(Ctx, PM, UI->getUseExpr()))
Jordan Rose76831c62012-10-11 16:10:19 +00001432 continue;
Jordan Rose25c0ea82012-10-29 17:46:47 +00001433
1434 const WeakObjectProfileTy &Profile = I->first;
1435 if (!Profile.isExactProfile())
1436 continue;
1437
1438 const NamedDecl *Base = Profile.getBase();
1439 if (!Base)
1440 Base = Profile.getProperty();
1441 assert(Base && "A profile always has a base or property.");
1442
1443 if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
1444 if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
1445 continue;
1446 }
Jordan Rose76831c62012-10-11 16:10:19 +00001447 }
1448
Jordan Rosed3934582012-09-28 22:21:30 +00001449 UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
1450 }
1451
1452 if (UsesByStmt.empty())
1453 return;
1454
1455 // Sort by first use so that we emit the warnings in a deterministic order.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001456 SourceManager &SM = S.getSourceManager();
Jordan Rosed3934582012-09-28 22:21:30 +00001457 std::sort(UsesByStmt.begin(), UsesByStmt.end(),
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001458 [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
1459 return SM.isBeforeInTranslationUnit(LHS.first->getLocStart(),
1460 RHS.first->getLocStart());
1461 });
Jordan Rosed3934582012-09-28 22:21:30 +00001462
1463 // Classify the current code body for better warning text.
1464 // This enum should stay in sync with the cases in
1465 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1466 // FIXME: Should we use a common classification enum and the same set of
1467 // possibilities all throughout Sema?
1468 enum {
1469 Function,
1470 Method,
1471 Block,
1472 Lambda
1473 } FunctionKind;
1474
1475 if (isa<sema::BlockScopeInfo>(CurFn))
1476 FunctionKind = Block;
1477 else if (isa<sema::LambdaScopeInfo>(CurFn))
1478 FunctionKind = Lambda;
1479 else if (isa<ObjCMethodDecl>(D))
1480 FunctionKind = Method;
1481 else
1482 FunctionKind = Function;
1483
1484 // Iterate through the sorted problems and emit warnings for each.
Aaron Ballmane5195222014-05-15 20:50:47 +00001485 for (const auto &P : UsesByStmt) {
1486 const Stmt *FirstRead = P.first;
1487 const WeakObjectProfileTy &Key = P.second->first;
1488 const WeakUseVector &Uses = P.second->second;
Jordan Rosed3934582012-09-28 22:21:30 +00001489
Jordan Rose657b5f42012-09-28 22:21:35 +00001490 // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
1491 // may not contain enough information to determine that these are different
1492 // properties. We can only be 100% sure of a repeated use in certain cases,
1493 // and we adjust the diagnostic kind accordingly so that the less certain
1494 // case can be turned off if it is too noisy.
Jordan Rosed3934582012-09-28 22:21:30 +00001495 unsigned DiagKind;
1496 if (Key.isExactProfile())
1497 DiagKind = diag::warn_arc_repeated_use_of_weak;
1498 else
1499 DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
1500
Jordan Rose657b5f42012-09-28 22:21:35 +00001501 // Classify the weak object being accessed for better warning text.
1502 // This enum should stay in sync with the cases in
1503 // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
1504 enum {
1505 Variable,
1506 Property,
1507 ImplicitProperty,
1508 Ivar
1509 } ObjectKind;
1510
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001511 const NamedDecl *KeyProp = Key.getProperty();
1512 if (isa<VarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001513 ObjectKind = Variable;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001514 else if (isa<ObjCPropertyDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001515 ObjectKind = Property;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001516 else if (isa<ObjCMethodDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001517 ObjectKind = ImplicitProperty;
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001518 else if (isa<ObjCIvarDecl>(KeyProp))
Jordan Rose657b5f42012-09-28 22:21:35 +00001519 ObjectKind = Ivar;
1520 else
1521 llvm_unreachable("Unexpected weak object kind!");
1522
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001523 // Do not warn about IBOutlet weak property receivers being set to null
1524 // since they are typically only used from the main thread.
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001525 if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
Bob Wilsonf4f54e32016-05-25 05:41:57 +00001526 if (Prop->hasAttr<IBOutletAttr>())
1527 continue;
1528
Jordan Rosed3934582012-09-28 22:21:30 +00001529 // Show the first time the object was read.
1530 S.Diag(FirstRead->getLocStart(), DiagKind)
Bob Wilson34cc8eb2016-05-25 05:42:00 +00001531 << int(ObjectKind) << KeyProp << int(FunctionKind)
Jordan Rosed3934582012-09-28 22:21:30 +00001532 << FirstRead->getSourceRange();
1533
1534 // Print all the other accesses as notes.
Aaron Ballmane5195222014-05-15 20:50:47 +00001535 for (const auto &Use : Uses) {
1536 if (Use.getUseExpr() == FirstRead)
Jordan Rosed3934582012-09-28 22:21:30 +00001537 continue;
Aaron Ballmane5195222014-05-15 20:50:47 +00001538 S.Diag(Use.getUseExpr()->getLocStart(),
Jordan Rosed3934582012-09-28 22:21:30 +00001539 diag::note_arc_weak_also_accessed_here)
Aaron Ballmane5195222014-05-15 20:50:47 +00001540 << Use.getUseExpr()->getSourceRange();
Jordan Rosed3934582012-09-28 22:21:30 +00001541 }
1542 }
1543}
1544
Jordan Rosed3934582012-09-28 22:21:30 +00001545namespace {
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001546class UninitValsDiagReporter : public UninitVariablesHandler {
1547 Sema &S;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001548 typedef SmallVector<UninitUse, 2> UsesVec;
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001549 typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001550 // Prefer using MapVector to DenseMap, so that iteration order will be
1551 // the same as insertion order. This is needed to obtain a deterministic
1552 // order of diagnostics when calling flushDiagnostics().
1553 typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001554 UsesMap uses;
Ted Kremenek39fa0562011-01-21 19:41:41 +00001555
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001556public:
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001557 UninitValsDiagReporter(Sema &S) : S(S) {}
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001558 ~UninitValsDiagReporter() override { flushDiagnostics(); }
Ted Kremenek596fa162011-10-13 18:50:06 +00001559
Enea Zaffanella2f40be72013-02-15 20:09:55 +00001560 MappedType &getUses(const VarDecl *vd) {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001561 MappedType &V = uses[vd];
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001562 if (!V.getPointer())
1563 V.setPointer(new UsesVec());
Ted Kremenek596fa162011-10-13 18:50:06 +00001564 return V;
1565 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001566
1567 void handleUseOfUninitVariable(const VarDecl *vd,
1568 const UninitUse &use) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001569 getUses(vd).getPointer()->push_back(use);
Ted Kremenek596fa162011-10-13 18:50:06 +00001570 }
1571
Craig Toppere14c0f82014-03-12 04:55:44 +00001572 void handleSelfInit(const VarDecl *vd) override {
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001573 getUses(vd).setInt(true);
Ted Kremenek39fa0562011-01-21 19:41:41 +00001574 }
1575
1576 void flushDiagnostics() {
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001577 for (const auto &P : uses) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001578 const VarDecl *vd = P.first;
1579 const MappedType &V = P.second;
Ted Kremenekb3dbe282011-02-02 23:35:53 +00001580
Benjamin Kramereb8c4462013-06-29 17:52:13 +00001581 UsesVec *vec = V.getPointer();
1582 bool hasSelfInit = V.getInt();
Ted Kremenek596fa162011-10-13 18:50:06 +00001583
1584 // Specially handle the case where we have uses of an uninitialized
1585 // variable, but the root cause is an idiomatic self-init. We want
1586 // to report the diagnostic at the self-init since that is the root cause.
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001587 if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
Richard Smith4323bf82012-05-25 02:17:09 +00001588 DiagnoseUninitializedUse(S, vd,
1589 UninitUse(vd->getInit()->IgnoreParenCasts(),
1590 /* isAlwaysUninit */ true),
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001591 /* alwaysReportSelfInit */ true);
Ted Kremenek596fa162011-10-13 18:50:06 +00001592 else {
1593 // Sort the uses by their SourceLocations. While not strictly
1594 // guaranteed to produce them in line/column order, this will provide
1595 // a stable ordering.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00001596 std::sort(vec->begin(), vec->end(),
1597 [](const UninitUse &a, const UninitUse &b) {
1598 // Prefer a more confident report over a less confident one.
1599 if (a.getKind() != b.getKind())
1600 return a.getKind() > b.getKind();
1601 return a.getUser()->getLocStart() < b.getUser()->getLocStart();
1602 });
1603
Aaron Ballmane5195222014-05-15 20:50:47 +00001604 for (const auto &U : *vec) {
Richard Smith4323bf82012-05-25 02:17:09 +00001605 // If we have self-init, downgrade all uses to 'may be uninitialized'.
Aaron Ballmane5195222014-05-15 20:50:47 +00001606 UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
Richard Smith4323bf82012-05-25 02:17:09 +00001607
1608 if (DiagnoseUninitializedUse(S, vd, Use))
Ted Kremenek596fa162011-10-13 18:50:06 +00001609 // Skip further diagnostics for this variable. We try to warn only
1610 // on the first point at which a variable is used uninitialized.
1611 break;
1612 }
Chandler Carruth7a037202011-04-05 18:18:08 +00001613 }
Ted Kremenek596fa162011-10-13 18:50:06 +00001614
1615 // Release the uses vector.
Ted Kremenek39fa0562011-01-21 19:41:41 +00001616 delete vec;
1617 }
George Burgess IV0fc4e8b2015-12-10 19:25:21 +00001618
1619 uses.clear();
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001620 }
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001621
1622private:
1623 static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
Aaron Ballmane5195222014-05-15 20:50:47 +00001624 return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
1625 return U.getKind() == UninitUse::Always ||
1626 U.getKind() == UninitUse::AfterCall ||
1627 U.getKind() == UninitUse::AfterDecl;
1628 });
Matt Beaumont-Gay4b489fa2011-10-19 18:53:03 +00001629 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001630};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001631} // anonymous namespace
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001632
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001633namespace clang {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001634namespace {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001635typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
Richard Smith92286672012-02-03 04:45:26 +00001636typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001637typedef std::list<DelayedDiag> DiagList;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001638
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001639struct SortDiagBySourceLocation {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001640 SourceManager &SM;
1641 SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001642
1643 bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
1644 // Although this call will be slow, this is only called when outputting
1645 // multiple warnings.
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001646 return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001647 }
1648};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001649} // anonymous namespace
1650} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001651
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001652//===----------------------------------------------------------------------===//
1653// -Wthread-safety
1654//===----------------------------------------------------------------------===//
1655namespace clang {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001656namespace threadSafety {
Benjamin Kramer539803c2015-03-19 14:23:45 +00001657namespace {
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00001658class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001659 Sema &S;
1660 DiagList Warnings;
Richard Smith92286672012-02-03 04:45:26 +00001661 SourceLocation FunLocation, FunEndLocation;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001662
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001663 const FunctionDecl *CurrentFunction;
1664 bool Verbose;
1665
Aaron Ballman71291bc2014-08-15 12:38:17 +00001666 OptionalNotes getNotes() const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001667 if (Verbose && CurrentFunction) {
1668 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001669 S.PDiag(diag::note_thread_warning_in_fun)
1670 << CurrentFunction->getNameAsString());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001671 return OptionalNotes(1, FNote);
1672 }
Aaron Ballman71291bc2014-08-15 12:38:17 +00001673 return OptionalNotes();
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001674 }
1675
Aaron Ballman71291bc2014-08-15 12:38:17 +00001676 OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001677 OptionalNotes ONS(1, Note);
1678 if (Verbose && CurrentFunction) {
1679 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001680 S.PDiag(diag::note_thread_warning_in_fun)
1681 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001682 ONS.push_back(std::move(FNote));
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001683 }
1684 return ONS;
1685 }
1686
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001687 OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
1688 const PartialDiagnosticAt &Note2) const {
1689 OptionalNotes ONS;
1690 ONS.push_back(Note1);
1691 ONS.push_back(Note2);
1692 if (Verbose && CurrentFunction) {
1693 PartialDiagnosticAt FNote(CurrentFunction->getBody()->getLocStart(),
1694 S.PDiag(diag::note_thread_warning_in_fun)
1695 << CurrentFunction->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001696 ONS.push_back(std::move(FNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001697 }
1698 return ONS;
1699 }
1700
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001701 // Helper functions
Aaron Ballmane0449042014-04-01 21:43:23 +00001702 void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
1703 SourceLocation Loc) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00001704 // Gracefully handle rare cases when the analysis can't get a more
1705 // precise source location.
1706 if (!Loc.isValid())
1707 Loc = FunLocation;
Aaron Ballmane0449042014-04-01 21:43:23 +00001708 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001709 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001710 }
1711
1712 public:
Richard Smith92286672012-02-03 04:45:26 +00001713 ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001714 : S(S), FunLocation(FL), FunEndLocation(FEL),
1715 CurrentFunction(nullptr), Verbose(false) {}
1716
1717 void setVerbose(bool b) { Verbose = b; }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001718
1719 /// \brief Emit all buffered diagnostics in order of sourcelocation.
1720 /// We need to output diagnostics produced while iterating through
1721 /// the lockset in deterministic order, so this function orders diagnostics
1722 /// and outputs them.
1723 void emitDiagnostics() {
Benjamin Kramer40b099b2012-03-26 14:05:40 +00001724 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001725 for (const auto &Diag : Warnings) {
1726 S.Diag(Diag.first.first, Diag.first.second);
1727 for (const auto &Note : Diag.second)
1728 S.Diag(Note.first, Note.second);
Richard Smith92286672012-02-03 04:45:26 +00001729 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001730 }
1731
Aaron Ballmane0449042014-04-01 21:43:23 +00001732 void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
1733 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
1734 << Loc);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001735 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowskiff2f3f82011-09-09 16:21:55 +00001736 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001737
Aaron Ballmane0449042014-04-01 21:43:23 +00001738 void handleUnmatchedUnlock(StringRef Kind, Name LockName,
1739 SourceLocation Loc) override {
1740 warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001741 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001742
Aaron Ballmane0449042014-04-01 21:43:23 +00001743 void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
1744 LockKind Expected, LockKind Received,
Aaron Ballmandf115d92014-03-21 14:48:48 +00001745 SourceLocation Loc) override {
1746 if (Loc.isInvalid())
1747 Loc = FunLocation;
1748 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
Aaron Ballmane0449042014-04-01 21:43:23 +00001749 << Kind << LockName << Received
1750 << Expected);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001751 Warnings.emplace_back(std::move(Warning), getNotes());
Aaron Ballmandf115d92014-03-21 14:48:48 +00001752 }
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001753
Aaron Ballmane0449042014-04-01 21:43:23 +00001754 void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
1755 warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001756 }
1757
Aaron Ballmane0449042014-04-01 21:43:23 +00001758 void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
1759 SourceLocation LocLocked,
Richard Smith92286672012-02-03 04:45:26 +00001760 SourceLocation LocEndOfScope,
Craig Toppere14c0f82014-03-12 04:55:44 +00001761 LockErrorKind LEK) override {
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001762 unsigned DiagID = 0;
1763 switch (LEK) {
1764 case LEK_LockedSomePredecessors:
Richard Smith92286672012-02-03 04:45:26 +00001765 DiagID = diag::warn_lock_some_predecessors;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001766 break;
1767 case LEK_LockedSomeLoopIterations:
1768 DiagID = diag::warn_expecting_lock_held_on_loop;
1769 break;
1770 case LEK_LockedAtEndOfFunction:
1771 DiagID = diag::warn_no_unlock;
1772 break;
DeLesley Hutchins6e6dbb72012-07-02 22:16:54 +00001773 case LEK_NotLockedAtEndOfFunction:
1774 DiagID = diag::warn_expecting_locked;
1775 break;
Caitlin Sadowskiaf9b7c52011-09-15 17:25:19 +00001776 }
Richard Smith92286672012-02-03 04:45:26 +00001777 if (LocEndOfScope.isInvalid())
1778 LocEndOfScope = FunEndLocation;
1779
Aaron Ballmane0449042014-04-01 21:43:23 +00001780 PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
1781 << LockName);
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001782 if (LocLocked.isValid()) {
Aaron Ballmane0449042014-04-01 21:43:23 +00001783 PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
1784 << Kind);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001785 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchinsfd374bb2013-04-08 20:11:11 +00001786 return;
1787 }
Benjamin Kramer3204b152015-05-29 19:42:19 +00001788 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001789 }
1790
Aaron Ballmane0449042014-04-01 21:43:23 +00001791 void handleExclusiveAndShared(StringRef Kind, Name LockName,
1792 SourceLocation Loc1,
Craig Toppere14c0f82014-03-12 04:55:44 +00001793 SourceLocation Loc2) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001794 PartialDiagnosticAt Warning(Loc1,
1795 S.PDiag(diag::warn_lock_exclusive_and_shared)
1796 << Kind << LockName);
1797 PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
1798 << Kind << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001799 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001800 }
1801
Aaron Ballmane0449042014-04-01 21:43:23 +00001802 void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
1803 ProtectedOperationKind POK, AccessKind AK,
1804 SourceLocation Loc) override {
1805 assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
1806 "Only works for variables");
Caitlin Sadowskie50d8c32011-09-14 20:09:09 +00001807 unsigned DiagID = POK == POK_VarAccess?
1808 diag::warn_variable_requires_any_lock:
1809 diag::warn_var_deref_requires_any_lock;
Richard Smith92286672012-02-03 04:45:26 +00001810 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
DeLesley Hutchinsa15e1b42012-09-19 19:18:29 +00001811 << D->getNameAsString() << getLockKindFromAccessKind(AK));
Benjamin Kramer3204b152015-05-29 19:42:19 +00001812 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001813 }
1814
Aaron Ballmane0449042014-04-01 21:43:23 +00001815 void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
1816 ProtectedOperationKind POK, Name LockName,
1817 LockKind LK, SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001818 Name *PossibleMatch) override {
Caitlin Sadowski427f42e2011-09-13 18:01:58 +00001819 unsigned DiagID = 0;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001820 if (PossibleMatch) {
1821 switch (POK) {
1822 case POK_VarAccess:
1823 DiagID = diag::warn_variable_requires_lock_precise;
1824 break;
1825 case POK_VarDereference:
1826 DiagID = diag::warn_var_deref_requires_lock_precise;
1827 break;
1828 case POK_FunctionCall:
1829 DiagID = diag::warn_fun_requires_lock_precise;
1830 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001831 case POK_PassByRef:
1832 DiagID = diag::warn_guarded_pass_by_reference;
1833 break;
1834 case POK_PtPassByRef:
1835 DiagID = diag::warn_pt_guarded_pass_by_reference;
1836 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001837 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001838 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1839 << D->getNameAsString()
1840 << LockName << LK);
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001841 PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
Aaron Ballmane0449042014-04-01 21:43:23 +00001842 << *PossibleMatch);
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001843 if (Verbose && POK == POK_VarAccess) {
1844 PartialDiagnosticAt VNote(D->getLocation(),
1845 S.PDiag(diag::note_guarded_by_declared_here)
1846 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001847 Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001848 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001849 Warnings.emplace_back(std::move(Warning), getNotes(Note));
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001850 } else {
1851 switch (POK) {
1852 case POK_VarAccess:
1853 DiagID = diag::warn_variable_requires_lock;
1854 break;
1855 case POK_VarDereference:
1856 DiagID = diag::warn_var_deref_requires_lock;
1857 break;
1858 case POK_FunctionCall:
1859 DiagID = diag::warn_fun_requires_lock;
1860 break;
DeLesley Hutchinsc60dc2c2014-09-18 23:02:26 +00001861 case POK_PassByRef:
1862 DiagID = diag::warn_guarded_pass_by_reference;
1863 break;
1864 case POK_PtPassByRef:
1865 DiagID = diag::warn_pt_guarded_pass_by_reference;
1866 break;
DeLesley Hutchins5ff16442012-09-10 19:58:23 +00001867 }
Aaron Ballmane0449042014-04-01 21:43:23 +00001868 PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
1869 << D->getNameAsString()
1870 << LockName << LK);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001871 if (Verbose && POK == POK_VarAccess) {
1872 PartialDiagnosticAt Note(D->getLocation(),
Aaron Ballman71291bc2014-08-15 12:38:17 +00001873 S.PDiag(diag::note_guarded_by_declared_here)
1874 << D->getNameAsString());
Benjamin Kramer3204b152015-05-29 19:42:19 +00001875 Warnings.emplace_back(std::move(Warning), getNotes(Note));
Aaron Ballman71291bc2014-08-15 12:38:17 +00001876 } else
Benjamin Kramer3204b152015-05-29 19:42:19 +00001877 Warnings.emplace_back(std::move(Warning), getNotes());
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001878 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001879 }
1880
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001881 void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
1882 SourceLocation Loc) override {
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001883 PartialDiagnosticAt Warning(Loc,
1884 S.PDiag(diag::warn_acquire_requires_negative_cap)
1885 << Kind << LockName << Neg);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001886 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchins3efd0492014-08-04 22:13:06 +00001887 }
1888
Aaron Ballmane0449042014-04-01 21:43:23 +00001889 void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
Craig Toppere14c0f82014-03-12 04:55:44 +00001890 SourceLocation Loc) override {
Aaron Ballmane0449042014-04-01 21:43:23 +00001891 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
1892 << Kind << FunName << LockName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001893 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001894 }
1895
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001896 void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
1897 SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001898 PartialDiagnosticAt Warning(Loc,
1899 S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001900 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001901 }
1902
Alexander Kornienko34eb2072015-04-11 02:00:23 +00001903 void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001904 PartialDiagnosticAt Warning(Loc,
1905 S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001906 Warnings.emplace_back(std::move(Warning), getNotes());
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001907 }
1908
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00001909 void enterFunction(const FunctionDecl* FD) override {
1910 CurrentFunction = FD;
1911 }
1912
1913 void leaveFunction(const FunctionDecl* FD) override {
Hans Wennborgdcfba332015-10-06 23:40:43 +00001914 CurrentFunction = nullptr;
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001915 }
1916};
Hans Wennborgdcfba332015-10-06 23:40:43 +00001917} // anonymous namespace
Benjamin Kramer539803c2015-03-19 14:23:45 +00001918} // namespace threadSafety
1919} // namespace clang
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00001920
Ted Kremenekb749a6d2011-01-15 02:58:47 +00001921//===----------------------------------------------------------------------===//
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001922// -Wconsumed
1923//===----------------------------------------------------------------------===//
1924
1925namespace clang {
1926namespace consumed {
1927namespace {
1928class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
1929
1930 Sema &S;
1931 DiagList Warnings;
1932
1933public:
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00001934
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001935 ConsumedWarningsHandler(Sema &S) : S(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001936
1937 void emitDiagnostics() override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001938 Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
Aaron Ballmane5195222014-05-15 20:50:47 +00001939 for (const auto &Diag : Warnings) {
1940 S.Diag(Diag.first.first, Diag.first.second);
1941 for (const auto &Note : Diag.second)
1942 S.Diag(Note.first, Note.second);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001943 }
1944 }
Craig Toppere14c0f82014-03-12 04:55:44 +00001945
1946 void warnLoopStateMismatch(SourceLocation Loc,
1947 StringRef VariableName) override {
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001948 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
1949 VariableName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001950
1951 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins3277a612013-10-09 18:30:24 +00001952 }
1953
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001954 void warnParamReturnTypestateMismatch(SourceLocation Loc,
1955 StringRef VariableName,
1956 StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001957 StringRef ObservedState) override {
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001958
1959 PartialDiagnosticAt Warning(Loc, S.PDiag(
1960 diag::warn_param_return_typestate_mismatch) << VariableName <<
1961 ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001962
1963 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins36ea1dd2013-10-17 22:53:04 +00001964 }
1965
DeLesley Hutchins69391772013-10-17 23:23:53 +00001966 void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001967 StringRef ObservedState) override {
DeLesley Hutchins69391772013-10-17 23:23:53 +00001968
1969 PartialDiagnosticAt Warning(Loc, S.PDiag(
1970 diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001971
1972 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins69391772013-10-17 23:23:53 +00001973 }
1974
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001975 void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
Craig Toppere14c0f82014-03-12 04:55:44 +00001976 StringRef TypeName) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001977 PartialDiagnosticAt Warning(Loc, S.PDiag(
1978 diag::warn_return_typestate_for_unconsumable_type) << TypeName);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001979
1980 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001981 }
1982
1983 void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
Craig Toppere14c0f82014-03-12 04:55:44 +00001984 StringRef ObservedState) override {
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001985
1986 PartialDiagnosticAt Warning(Loc, S.PDiag(
1987 diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001988
1989 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchinsfc368252013-09-03 20:11:38 +00001990 }
1991
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001992 void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
Craig Toppere14c0f82014-03-12 04:55:44 +00001993 SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001994
1995 PartialDiagnosticAt Warning(Loc, S.PDiag(
DeLesley Hutchins210791a2013-10-04 21:28:06 +00001996 diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00001997
1998 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00001999 }
2000
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002001 void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
Craig Toppere14c0f82014-03-12 04:55:44 +00002002 StringRef State, SourceLocation Loc) override {
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002003
DeLesley Hutchins210791a2013-10-04 21:28:06 +00002004 PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
2005 MethodName << VariableName << State);
Benjamin Kramer3204b152015-05-29 19:42:19 +00002006
2007 Warnings.emplace_back(std::move(Warning), OptionalNotes());
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002008 }
2009};
Hans Wennborgdcfba332015-10-06 23:40:43 +00002010} // anonymous namespace
2011} // namespace consumed
2012} // namespace clang
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002013
2014//===----------------------------------------------------------------------===//
Ted Kremenek918fe842010-03-20 21:06:02 +00002015// AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
2016// warnings on a function, method, or block.
2017//===----------------------------------------------------------------------===//
2018
Ted Kremenek0b405322010-03-23 00:13:23 +00002019clang::sema::AnalysisBasedWarnings::Policy::Policy() {
2020 enableCheckFallThrough = 1;
2021 enableCheckUnreachable = 0;
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002022 enableThreadSafetyAnalysis = 0;
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002023 enableConsumedAnalysis = 0;
Ted Kremenek0b405322010-03-23 00:13:23 +00002024}
2025
Ted Kremenekad8753c2014-03-15 05:47:06 +00002026static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002027 return (unsigned)!D.isIgnored(diag, SourceLocation());
Ted Kremenekad8753c2014-03-15 05:47:06 +00002028}
2029
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002030clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
2031 : S(s),
2032 NumFunctionsAnalyzed(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002033 NumFunctionsWithBadCFGs(0),
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002034 NumCFGBlocks(0),
Benjamin Kramer581f48f2011-07-08 20:38:53 +00002035 MaxCFGBlocksPerFunction(0),
2036 NumUninitAnalysisFunctions(0),
2037 NumUninitAnalysisVariables(0),
2038 MaxUninitAnalysisVariablesPerFunction(0),
2039 NumUninitAnalysisBlockVisits(0),
2040 MaxUninitAnalysisBlockVisitsPerFunction(0) {
Ted Kremenekad8753c2014-03-15 05:47:06 +00002041
2042 using namespace diag;
David Blaikie9c902b52011-09-25 23:23:43 +00002043 DiagnosticsEngine &D = S.getDiagnostics();
Ted Kremenekad8753c2014-03-15 05:47:06 +00002044
2045 DefaultPolicy.enableCheckUnreachable =
2046 isEnabled(D, warn_unreachable) ||
2047 isEnabled(D, warn_unreachable_break) ||
Ted Kremenek14210372014-03-21 06:02:36 +00002048 isEnabled(D, warn_unreachable_return) ||
2049 isEnabled(D, warn_unreachable_loop_increment);
Ted Kremenekad8753c2014-03-15 05:47:06 +00002050
2051 DefaultPolicy.enableThreadSafetyAnalysis =
2052 isEnabled(D, warn_double_lock);
2053
2054 DefaultPolicy.enableConsumedAnalysis =
2055 isEnabled(D, warn_use_in_invalid_state);
Ted Kremenek918fe842010-03-20 21:06:02 +00002056}
2057
Aaron Ballmane5195222014-05-15 20:50:47 +00002058static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
2059 for (const auto &D : fscope->PossiblyUnreachableDiags)
Ted Kremenek3427fac2011-02-23 01:52:04 +00002060 S.Diag(D.Loc, D.PD);
Ted Kremenek3427fac2011-02-23 01:52:04 +00002061}
2062
Ted Kremenek0b405322010-03-23 00:13:23 +00002063void clang::sema::
2064AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
Ted Kremenekcc7f1f82011-02-23 01:51:53 +00002065 sema::FunctionScopeInfo *fscope,
Ted Kremenek1767a272011-02-23 01:51:48 +00002066 const Decl *D, const BlockExpr *blkExpr) {
Ted Kremenekb45ebee2010-03-20 21:11:09 +00002067
Ted Kremenek918fe842010-03-20 21:06:02 +00002068 // We avoid doing analysis-based warnings when there are errors for
2069 // two reasons:
2070 // (1) The CFGs often can't be constructed (if the body is invalid), so
2071 // don't bother trying.
2072 // (2) The code already has problems; running the analysis just takes more
2073 // time.
David Blaikie9c902b52011-09-25 23:23:43 +00002074 DiagnosticsEngine &Diags = S.getDiagnostics();
Ted Kremenekb8021922010-04-30 21:49:25 +00002075
Ted Kremenek0b405322010-03-23 00:13:23 +00002076 // Do not do any analysis for declarations in system headers if we are
2077 // going to just ignore them.
Ted Kremenekb8021922010-04-30 21:49:25 +00002078 if (Diags.getSuppressSystemWarnings() &&
Ted Kremenek0b405322010-03-23 00:13:23 +00002079 S.SourceMgr.isInSystemHeader(D->getLocation()))
2080 return;
2081
John McCall1d570a72010-08-25 05:56:39 +00002082 // For code in dependent contexts, we'll do this at instantiation time.
David Blaikie0f2ae782012-01-24 04:51:48 +00002083 if (cast<DeclContext>(D)->isDependentContext())
2084 return;
Ted Kremenek918fe842010-03-20 21:06:02 +00002085
Argyrios Kyrtzidis70ec1c72016-07-13 20:35:26 +00002086 if (Diags.hasUncompilableErrorOccurred()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002087 // Flush out any possibly unreachable diagnostics.
2088 flushDiagnostics(S, fscope);
2089 return;
2090 }
2091
Ted Kremenek918fe842010-03-20 21:06:02 +00002092 const Stmt *Body = D->getBody();
2093 assert(Body);
2094
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002095 // Construct the analysis context with the specified CFG build options.
Craig Topperc3ec1492014-05-26 06:22:03 +00002096 AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
Ted Kremenek189ecec2011-07-21 05:22:47 +00002097
Ted Kremenek918fe842010-03-20 21:06:02 +00002098 // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
Benjamin Kramer60509af2013-09-09 14:48:42 +00002099 // explosion for destructors that can result and the compile time hit.
Ted Kremenek189ecec2011-07-21 05:22:47 +00002100 AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
2101 AC.getCFGBuildOptions().AddEHEdges = false;
2102 AC.getCFGBuildOptions().AddInitializers = true;
2103 AC.getCFGBuildOptions().AddImplicitDtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002104 AC.getCFGBuildOptions().AddTemporaryDtors = true;
Jordan Rosec9176072014-01-13 17:59:19 +00002105 AC.getCFGBuildOptions().AddCXXNewAllocator = false;
Enrico Pertosofaed8012015-06-03 10:12:40 +00002106 AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
Jordan Rose91f78402012-09-05 23:11:06 +00002107
Ted Kremenek9e100ea2011-07-19 14:18:48 +00002108 // Force that certain expressions appear as CFGElements in the CFG. This
2109 // is used to speed up various analyses.
2110 // FIXME: This isn't the right factoring. This is here for initial
2111 // prototyping, but we need a way for analyses to say what expressions they
2112 // expect to always be CFGElements and then fill in the BuildOptions
2113 // appropriately. This is essentially a layering violation.
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002114 if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
2115 P.enableConsumedAnalysis) {
DeLesley Hutchinsf7faa6a2011-12-08 20:23:06 +00002116 // Unreachable code analysis and thread safety require a linearized CFG.
Ted Kremenekbd913712011-08-23 23:05:11 +00002117 AC.getCFGBuildOptions().setAllAlwaysAdd();
2118 }
2119 else {
2120 AC.getCFGBuildOptions()
2121 .setAlwaysAdd(Stmt::BinaryOperatorClass)
Richard Smithb21dd022012-07-17 01:27:33 +00002122 .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
Ted Kremenekbd913712011-08-23 23:05:11 +00002123 .setAlwaysAdd(Stmt::BlockExprClass)
2124 .setAlwaysAdd(Stmt::CStyleCastExprClass)
2125 .setAlwaysAdd(Stmt::DeclRefExprClass)
2126 .setAlwaysAdd(Stmt::ImplicitCastExprClass)
Richard Smith84837d52012-05-03 18:27:39 +00002127 .setAlwaysAdd(Stmt::UnaryOperatorClass)
2128 .setAlwaysAdd(Stmt::AttributedStmtClass);
Ted Kremenekbd913712011-08-23 23:05:11 +00002129 }
Ted Kremenek918fe842010-03-20 21:06:02 +00002130
Richard Trieue9fa2662014-04-15 00:57:50 +00002131 // Install the logical handler for -Wtautological-overlap-compare
2132 std::unique_ptr<LogicalErrorHandler> LEH;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002133 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
2134 D->getLocStart())) {
Richard Trieue9fa2662014-04-15 00:57:50 +00002135 LEH.reset(new LogicalErrorHandler(S));
2136 AC.getCFGBuildOptions().Observer = LEH.get();
Richard Trieuf935b562014-04-05 05:17:01 +00002137 }
Ted Kremenekb3a38a92013-10-14 19:11:25 +00002138
Ted Kremenek3427fac2011-02-23 01:52:04 +00002139 // Emit delayed diagnostics.
David Blaikie0f2ae782012-01-24 04:51:48 +00002140 if (!fscope->PossiblyUnreachableDiags.empty()) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002141 bool analyzed = false;
Ted Kremeneka099c592011-03-10 03:50:34 +00002142
2143 // Register the expressions with the CFGBuilder.
Aaron Ballmane5195222014-05-15 20:50:47 +00002144 for (const auto &D : fscope->PossiblyUnreachableDiags) {
2145 if (D.stmt)
2146 AC.registerForcedBlockExpression(D.stmt);
Ted Kremeneka099c592011-03-10 03:50:34 +00002147 }
2148
2149 if (AC.getCFG()) {
2150 analyzed = true;
Aaron Ballmane5195222014-05-15 20:50:47 +00002151 for (const auto &D : fscope->PossiblyUnreachableDiags) {
Ted Kremeneka099c592011-03-10 03:50:34 +00002152 bool processed = false;
Aaron Ballmane5195222014-05-15 20:50:47 +00002153 if (D.stmt) {
2154 const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
Eli Friedmane0afc982012-01-21 01:01:51 +00002155 CFGReverseBlockReachabilityAnalysis *cra =
2156 AC.getCFGReachablityAnalysis();
2157 // FIXME: We should be able to assert that block is non-null, but
2158 // the CFG analysis can skip potentially-evaluated expressions in
2159 // edge cases; see test/Sema/vla-2.c.
2160 if (block && cra) {
Ted Kremenek3427fac2011-02-23 01:52:04 +00002161 // Can this block be reached from the entrance?
Ted Kremeneka099c592011-03-10 03:50:34 +00002162 if (cra->isReachable(&AC.getCFG()->getEntry(), block))
Ted Kremenek3427fac2011-02-23 01:52:04 +00002163 S.Diag(D.Loc, D.PD);
Ted Kremeneka099c592011-03-10 03:50:34 +00002164 processed = true;
Ted Kremenek3427fac2011-02-23 01:52:04 +00002165 }
2166 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002167 if (!processed) {
2168 // Emit the warning anyway if we cannot map to a basic block.
2169 S.Diag(D.Loc, D.PD);
2170 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002171 }
Ted Kremeneka099c592011-03-10 03:50:34 +00002172 }
Ted Kremenek3427fac2011-02-23 01:52:04 +00002173
2174 if (!analyzed)
2175 flushDiagnostics(S, fscope);
2176 }
2177
Ted Kremenek918fe842010-03-20 21:06:02 +00002178 // Warning: check missing 'return'
David Blaikie0f2ae782012-01-24 04:51:48 +00002179 if (P.enableCheckFallThrough) {
Ted Kremenek918fe842010-03-20 21:06:02 +00002180 const CheckFallThroughDiagnostics &CD =
Eric Fiselier709d1b32016-10-27 07:30:31 +00002181 (isa<BlockDecl>(D)
2182 ? CheckFallThroughDiagnostics::MakeForBlock()
2183 : (isa<CXXMethodDecl>(D) &&
2184 cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
2185 cast<CXXMethodDecl>(D)->getParent()->isLambda())
2186 ? CheckFallThroughDiagnostics::MakeForLambda()
Eric Fiselierda8f9b52017-05-25 02:16:53 +00002187 : (fscope->isCoroutine()
Eric Fiselier709d1b32016-10-27 07:30:31 +00002188 ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
2189 : CheckFallThroughDiagnostics::MakeForFunction(D)));
Ted Kremenek1767a272011-02-23 01:51:48 +00002190 CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
Ted Kremenek918fe842010-03-20 21:06:02 +00002191 }
2192
2193 // Warning: check for unreachable code
Ted Kremenek7f770032011-11-30 21:22:09 +00002194 if (P.enableCheckUnreachable) {
2195 // Only check for unreachable code on non-template instantiations.
2196 // Different template instantiations can effectively change the control-flow
2197 // and it is very difficult to prove that a snippet of code in a template
2198 // is unreachable for all instantiations.
Ted Kremenek85825ae2011-12-01 00:59:17 +00002199 bool isTemplateInstantiation = false;
2200 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
2201 isTemplateInstantiation = Function->isTemplateInstantiation();
2202 if (!isTemplateInstantiation)
Ted Kremenek7f770032011-11-30 21:22:09 +00002203 CheckUnreachable(S, AC);
2204 }
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002205
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002206 // Check for thread safety violations
David Blaikie0f2ae782012-01-24 04:51:48 +00002207 if (P.enableThreadSafetyAnalysis) {
DeLesley Hutchinsc2090512011-10-21 18:10:14 +00002208 SourceLocation FL = AC.getDecl()->getLocation();
Richard Smith92286672012-02-03 04:45:26 +00002209 SourceLocation FEL = AC.getDecl()->getLocEnd();
DeLesley Hutchinsea1f8332014-07-28 15:57:27 +00002210 threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002211 if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getLocStart()))
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002212 Reporter.setIssueBetaWarnings(true);
DeLesley Hutchinseb0ea5f2014-08-14 21:40:15 +00002213 if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getLocStart()))
2214 Reporter.setVerbose(true);
DeLesley Hutchins8edae132012-12-05 00:06:15 +00002215
DeLesley Hutchinsab1dc2d2015-02-03 22:11:04 +00002216 threadSafety::runThreadSafetyAnalysis(AC, Reporter,
2217 &S.ThreadSafetyDeclCache);
Caitlin Sadowski0b3501c2011-09-09 16:04:02 +00002218 Reporter.emitDiagnostics();
2219 }
Caitlin Sadowskiafbbd8e2011-08-23 18:46:34 +00002220
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002221 // Check for violations of consumed properties.
2222 if (P.enableConsumedAnalysis) {
2223 consumed::ConsumedWarningsHandler WarningHandler(S);
Reid Klecknere846dea2013-08-12 23:49:39 +00002224 consumed::ConsumedAnalyzer Analyzer(WarningHandler);
DeLesley Hutchins48a31762013-08-12 21:20:55 +00002225 Analyzer.run(AC);
2226 }
2227
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002228 if (!Diags.isIgnored(diag::warn_uninit_var, D->getLocStart()) ||
2229 !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getLocStart()) ||
2230 !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getLocStart())) {
Ted Kremenek2551fbe2011-03-17 05:29:57 +00002231 if (CFG *cfg = AC.getCFG()) {
Ted Kremenekb63931e2011-01-18 21:18:58 +00002232 UninitValsDiagReporter reporter(S);
Fariborz Jahanian8809a9d2011-07-16 18:31:33 +00002233 UninitVariablesAnalysisStats stats;
Benjamin Kramere492cb42011-07-16 20:13:06 +00002234 std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
Ted Kremenekbcf848f2011-01-25 19:13:48 +00002235 runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002236 reporter, stats);
2237
2238 if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
2239 ++NumUninitAnalysisFunctions;
2240 NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
2241 NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
2242 MaxUninitAnalysisVariablesPerFunction =
2243 std::max(MaxUninitAnalysisVariablesPerFunction,
2244 stats.NumVariablesAnalyzed);
2245 MaxUninitAnalysisBlockVisitsPerFunction =
2246 std::max(MaxUninitAnalysisBlockVisitsPerFunction,
2247 stats.NumBlockVisits);
2248 }
Ted Kremenekb749a6d2011-01-15 02:58:47 +00002249 }
2250 }
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002251
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002252 bool FallThroughDiagFull =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002253 !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getLocStart());
2254 bool FallThroughDiagPerFunction = !Diags.isIgnored(
2255 diag::warn_unannotated_fallthrough_per_function, D->getLocStart());
Richard Smith4f902c72016-03-08 00:32:55 +00002256 if (FallThroughDiagFull || FallThroughDiagPerFunction ||
2257 fscope->HasFallthroughStmt) {
Alexander Kornienko06caf7d2012-06-02 01:01:07 +00002258 DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
Richard Smith84837d52012-05-03 18:27:39 +00002259 }
2260
John McCall460ce582015-10-22 18:38:17 +00002261 if (S.getLangOpts().ObjCWeak &&
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002262 !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getLocStart()))
Jordan Rose76831c62012-10-11 16:10:19 +00002263 diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
Jordan Rosed3934582012-09-28 22:21:30 +00002264
Richard Trieu2f024f42013-12-21 02:33:43 +00002265
2266 // Check for infinite self-recursion in functions
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002267 if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
2268 D->getLocStart())) {
Richard Trieu2f024f42013-12-21 02:33:43 +00002269 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2270 checkRecursiveFunction(S, FD, Body, AC);
2271 }
2272 }
2273
Erich Keane89fe9c22017-06-23 20:22:19 +00002274 // Check for throw out of non-throwing function.
2275 if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getLocStart()))
2276 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
2277 if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
2278 checkThrowInNonThrowingFunc(S, FD, AC);
2279
Richard Trieue9fa2662014-04-15 00:57:50 +00002280 // If none of the previous checks caused a CFG build, trigger one here
2281 // for -Wtautological-overlap-compare
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002282 if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
Richard Trieue9fa2662014-04-15 00:57:50 +00002283 D->getLocStart())) {
2284 AC.getCFG();
2285 }
2286
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002287 // Collect statistics about the CFG if it was built.
2288 if (S.CollectStats && AC.isCFGBuilt()) {
2289 ++NumFunctionsAnalyzed;
2290 if (CFG *cfg = AC.getCFG()) {
2291 // If we successfully built a CFG for this context, record some more
2292 // detail information about it.
Chandler Carruth50020d92011-07-06 22:21:45 +00002293 NumCFGBlocks += cfg->getNumBlockIDs();
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002294 MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
Chandler Carruth50020d92011-07-06 22:21:45 +00002295 cfg->getNumBlockIDs());
Chandler Carruthb4836ea2011-07-06 16:21:37 +00002296 } else {
2297 ++NumFunctionsWithBadCFGs;
2298 }
2299 }
2300}
2301
2302void clang::sema::AnalysisBasedWarnings::PrintStats() const {
2303 llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
2304
2305 unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
2306 unsigned AvgCFGBlocksPerFunction =
2307 !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
2308 llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
2309 << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
2310 << " " << NumCFGBlocks << " CFG blocks built.\n"
2311 << " " << AvgCFGBlocksPerFunction
2312 << " average CFG blocks per function.\n"
2313 << " " << MaxCFGBlocksPerFunction
2314 << " max CFG blocks per function.\n";
2315
2316 unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
2317 : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
2318 unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
2319 : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
2320 llvm::errs() << NumUninitAnalysisFunctions
2321 << " functions analyzed for uninitialiazed variables\n"
2322 << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
2323 << " " << AvgUninitVariablesPerFunction
2324 << " average variables per function.\n"
2325 << " " << MaxUninitAnalysisVariablesPerFunction
2326 << " max variables per function.\n"
2327 << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
2328 << " " << AvgUninitBlockVisitsPerFunction
2329 << " average block visits per function.\n"
2330 << " " << MaxUninitAnalysisBlockVisitsPerFunction
2331 << " max block visits per function.\n";
Ted Kremenek918fe842010-03-20 21:06:02 +00002332}