1 //=- 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 
16 #include "clang/Sema/AnalysisBasedWarnings.h"
17 #include "clang/Sema/SemaInternal.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/SourceLocation.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/ExprObjC.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/StmtObjC.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/AST/EvaluatedExprVisitor.h"
29 #include "clang/AST/StmtVisitor.h"
30 #include "clang/Analysis/AnalysisContext.h"
31 #include "clang/Analysis/CFG.h"
32 #include "clang/Analysis/Analyses/ReachableCode.h"
33 #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
34 #include "clang/Analysis/Analyses/ThreadSafety.h"
35 #include "clang/Analysis/CFGStmtMap.h"
36 #include "clang/Analysis/Analyses/UninitializedValues.h"
37 #include "llvm/ADT/BitVector.h"
38 #include "llvm/ADT/FoldingSet.h"
39 #include "llvm/ADT/ImmutableMap.h"
40 #include "llvm/ADT/PostOrderIterator.h"
41 #include "llvm/ADT/SmallVector.h"
42 #include "llvm/ADT/StringRef.h"
43 #include "llvm/Support/Casting.h"
44 #include <algorithm>
45 #include <vector>
46 
47 using namespace clang;
48 
49 //===----------------------------------------------------------------------===//
50 // Unreachable code analysis.
51 //===----------------------------------------------------------------------===//
52 
53 namespace {
54   class UnreachableCodeHandler : public reachable_code::Callback {
55     Sema &S;
56   public:
57     UnreachableCodeHandler(Sema &s) : S(s) {}
58 
59     void HandleUnreachable(SourceLocation L, SourceRange R1, SourceRange R2) {
60       S.Diag(L, diag::warn_unreachable) << R1 << R2;
61     }
62   };
63 }
64 
65 /// CheckUnreachable - Check for unreachable code.
66 static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
67   UnreachableCodeHandler UC(S);
68   reachable_code::FindUnreachableCode(AC, UC);
69 }
70 
71 //===----------------------------------------------------------------------===//
72 // Check for missing return value.
73 //===----------------------------------------------------------------------===//
74 
75 enum ControlFlowKind {
76   UnknownFallThrough,
77   NeverFallThrough,
78   MaybeFallThrough,
79   AlwaysFallThrough,
80   NeverFallThroughOrReturn
81 };
82 
83 /// CheckFallThrough - Check that we don't fall off the end of a
84 /// Statement that should return a value.
85 ///
86 /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
87 /// MaybeFallThrough iff we might or might not fall off the end,
88 /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
89 /// return.  We assume NeverFallThrough iff we never fall off the end of the
90 /// statement but we may return.  We assume that functions not marked noreturn
91 /// will return.
92 static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
93   CFG *cfg = AC.getCFG();
94   if (cfg == 0) return UnknownFallThrough;
95 
96   // The CFG leaves in dead things, and we don't want the dead code paths to
97   // confuse us, so we mark all live things first.
98   llvm::BitVector live(cfg->getNumBlockIDs());
99   unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
100                                                           live);
101 
102   bool AddEHEdges = AC.getAddEHEdges();
103   if (!AddEHEdges && count != cfg->getNumBlockIDs())
104     // When there are things remaining dead, and we didn't add EH edges
105     // from CallExprs to the catch clauses, we have to go back and
106     // mark them as live.
107     for (CFG::iterator I = cfg->begin(), E = cfg->end(); I != E; ++I) {
108       CFGBlock &b = **I;
109       if (!live[b.getBlockID()]) {
110         if (b.pred_begin() == b.pred_end()) {
111           if (b.getTerminator() && isa<CXXTryStmt>(b.getTerminator()))
112             // When not adding EH edges from calls, catch clauses
113             // can otherwise seem dead.  Avoid noting them as dead.
114             count += reachable_code::ScanReachableFromBlock(&b, live);
115           continue;
116         }
117       }
118     }
119 
120   // Now we know what is live, we check the live precessors of the exit block
121   // and look for fall through paths, being careful to ignore normal returns,
122   // and exceptional paths.
123   bool HasLiveReturn = false;
124   bool HasFakeEdge = false;
125   bool HasPlainEdge = false;
126   bool HasAbnormalEdge = false;
127 
128   // Ignore default cases that aren't likely to be reachable because all
129   // enums in a switch(X) have explicit case statements.
130   CFGBlock::FilterOptions FO;
131   FO.IgnoreDefaultsWithCoveredEnums = 1;
132 
133   for (CFGBlock::filtered_pred_iterator
134 	 I = cfg->getExit().filtered_pred_start_end(FO); I.hasMore(); ++I) {
135     const CFGBlock& B = **I;
136     if (!live[B.getBlockID()])
137       continue;
138 
139     // Skip blocks which contain an element marked as no-return. They don't
140     // represent actually viable edges into the exit block, so mark them as
141     // abnormal.
142     if (B.hasNoReturnElement()) {
143       HasAbnormalEdge = true;
144       continue;
145     }
146 
147     // Destructors can appear after the 'return' in the CFG.  This is
148     // normal.  We need to look pass the destructors for the return
149     // statement (if it exists).
150     CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
151 
152     for ( ; ri != re ; ++ri)
153       if (isa<CFGStmt>(*ri))
154         break;
155 
156     // No more CFGElements in the block?
157     if (ri == re) {
158       if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
159         HasAbnormalEdge = true;
160         continue;
161       }
162       // A labeled empty statement, or the entry block...
163       HasPlainEdge = true;
164       continue;
165     }
166 
167     CFGStmt CS = cast<CFGStmt>(*ri);
168     const Stmt *S = CS.getStmt();
169     if (isa<ReturnStmt>(S)) {
170       HasLiveReturn = true;
171       continue;
172     }
173     if (isa<ObjCAtThrowStmt>(S)) {
174       HasFakeEdge = true;
175       continue;
176     }
177     if (isa<CXXThrowExpr>(S)) {
178       HasFakeEdge = true;
179       continue;
180     }
181     if (const AsmStmt *AS = dyn_cast<AsmStmt>(S)) {
182       if (AS->isMSAsm()) {
183         HasFakeEdge = true;
184         HasLiveReturn = true;
185         continue;
186       }
187     }
188     if (isa<CXXTryStmt>(S)) {
189       HasAbnormalEdge = true;
190       continue;
191     }
192     if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
193         == B.succ_end()) {
194       HasAbnormalEdge = true;
195       continue;
196     }
197 
198     HasPlainEdge = true;
199   }
200   if (!HasPlainEdge) {
201     if (HasLiveReturn)
202       return NeverFallThrough;
203     return NeverFallThroughOrReturn;
204   }
205   if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
206     return MaybeFallThrough;
207   // This says AlwaysFallThrough for calls to functions that are not marked
208   // noreturn, that don't return.  If people would like this warning to be more
209   // accurate, such functions should be marked as noreturn.
210   return AlwaysFallThrough;
211 }
212 
213 namespace {
214 
215 struct CheckFallThroughDiagnostics {
216   unsigned diag_MaybeFallThrough_HasNoReturn;
217   unsigned diag_MaybeFallThrough_ReturnsNonVoid;
218   unsigned diag_AlwaysFallThrough_HasNoReturn;
219   unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
220   unsigned diag_NeverFallThroughOrReturn;
221   enum { Function, Block, Lambda } funMode;
222   SourceLocation FuncLoc;
223 
224   static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
225     CheckFallThroughDiagnostics D;
226     D.FuncLoc = Func->getLocation();
227     D.diag_MaybeFallThrough_HasNoReturn =
228       diag::warn_falloff_noreturn_function;
229     D.diag_MaybeFallThrough_ReturnsNonVoid =
230       diag::warn_maybe_falloff_nonvoid_function;
231     D.diag_AlwaysFallThrough_HasNoReturn =
232       diag::warn_falloff_noreturn_function;
233     D.diag_AlwaysFallThrough_ReturnsNonVoid =
234       diag::warn_falloff_nonvoid_function;
235 
236     // Don't suggest that virtual functions be marked "noreturn", since they
237     // might be overridden by non-noreturn functions.
238     bool isVirtualMethod = false;
239     if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
240       isVirtualMethod = Method->isVirtual();
241 
242     // Don't suggest that template instantiations be marked "noreturn"
243     bool isTemplateInstantiation = false;
244     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
245       isTemplateInstantiation = Function->isTemplateInstantiation();
246 
247     if (!isVirtualMethod && !isTemplateInstantiation)
248       D.diag_NeverFallThroughOrReturn =
249         diag::warn_suggest_noreturn_function;
250     else
251       D.diag_NeverFallThroughOrReturn = 0;
252 
253     D.funMode = Function;
254     return D;
255   }
256 
257   static CheckFallThroughDiagnostics MakeForBlock() {
258     CheckFallThroughDiagnostics D;
259     D.diag_MaybeFallThrough_HasNoReturn =
260       diag::err_noreturn_block_has_return_expr;
261     D.diag_MaybeFallThrough_ReturnsNonVoid =
262       diag::err_maybe_falloff_nonvoid_block;
263     D.diag_AlwaysFallThrough_HasNoReturn =
264       diag::err_noreturn_block_has_return_expr;
265     D.diag_AlwaysFallThrough_ReturnsNonVoid =
266       diag::err_falloff_nonvoid_block;
267     D.diag_NeverFallThroughOrReturn =
268       diag::warn_suggest_noreturn_block;
269     D.funMode = Block;
270     return D;
271   }
272 
273   static CheckFallThroughDiagnostics MakeForLambda() {
274     CheckFallThroughDiagnostics D;
275     D.diag_MaybeFallThrough_HasNoReturn =
276       diag::err_noreturn_lambda_has_return_expr;
277     D.diag_MaybeFallThrough_ReturnsNonVoid =
278       diag::warn_maybe_falloff_nonvoid_lambda;
279     D.diag_AlwaysFallThrough_HasNoReturn =
280       diag::err_noreturn_lambda_has_return_expr;
281     D.diag_AlwaysFallThrough_ReturnsNonVoid =
282       diag::warn_falloff_nonvoid_lambda;
283     D.diag_NeverFallThroughOrReturn = 0;
284     D.funMode = Lambda;
285     return D;
286   }
287 
288   bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
289                         bool HasNoReturn) const {
290     if (funMode == Function) {
291       return (ReturnsVoid ||
292               D.getDiagnosticLevel(diag::warn_maybe_falloff_nonvoid_function,
293                                    FuncLoc) == DiagnosticsEngine::Ignored)
294         && (!HasNoReturn ||
295             D.getDiagnosticLevel(diag::warn_noreturn_function_has_return_expr,
296                                  FuncLoc) == DiagnosticsEngine::Ignored)
297         && (!ReturnsVoid ||
298             D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
299               == DiagnosticsEngine::Ignored);
300     }
301 
302     // For blocks / lambdas.
303     return ReturnsVoid && !HasNoReturn
304             && ((funMode == Lambda) ||
305                 D.getDiagnosticLevel(diag::warn_suggest_noreturn_block, FuncLoc)
306                   == DiagnosticsEngine::Ignored);
307   }
308 };
309 
310 }
311 
312 /// CheckFallThroughForFunctionDef - Check that we don't fall off the end of a
313 /// function that should return a value.  Check that we don't fall off the end
314 /// of a noreturn function.  We assume that functions and blocks not marked
315 /// noreturn will return.
316 static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
317                                     const BlockExpr *blkExpr,
318                                     const CheckFallThroughDiagnostics& CD,
319                                     AnalysisDeclContext &AC) {
320 
321   bool ReturnsVoid = false;
322   bool HasNoReturn = false;
323 
324   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
325     ReturnsVoid = FD->getResultType()->isVoidType();
326     HasNoReturn = FD->hasAttr<NoReturnAttr>() ||
327        FD->getType()->getAs<FunctionType>()->getNoReturnAttr();
328   }
329   else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
330     ReturnsVoid = MD->getResultType()->isVoidType();
331     HasNoReturn = MD->hasAttr<NoReturnAttr>();
332   }
333   else if (isa<BlockDecl>(D)) {
334     QualType BlockTy = blkExpr->getType();
335     if (const FunctionType *FT =
336           BlockTy->getPointeeType()->getAs<FunctionType>()) {
337       if (FT->getResultType()->isVoidType())
338         ReturnsVoid = true;
339       if (FT->getNoReturnAttr())
340         HasNoReturn = true;
341     }
342   }
343 
344   DiagnosticsEngine &Diags = S.getDiagnostics();
345 
346   // Short circuit for compilation speed.
347   if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
348       return;
349 
350   // FIXME: Function try block
351   if (const CompoundStmt *Compound = dyn_cast<CompoundStmt>(Body)) {
352     switch (CheckFallThrough(AC)) {
353       case UnknownFallThrough:
354         break;
355 
356       case MaybeFallThrough:
357         if (HasNoReturn)
358           S.Diag(Compound->getRBracLoc(),
359                  CD.diag_MaybeFallThrough_HasNoReturn);
360         else if (!ReturnsVoid)
361           S.Diag(Compound->getRBracLoc(),
362                  CD.diag_MaybeFallThrough_ReturnsNonVoid);
363         break;
364       case AlwaysFallThrough:
365         if (HasNoReturn)
366           S.Diag(Compound->getRBracLoc(),
367                  CD.diag_AlwaysFallThrough_HasNoReturn);
368         else if (!ReturnsVoid)
369           S.Diag(Compound->getRBracLoc(),
370                  CD.diag_AlwaysFallThrough_ReturnsNonVoid);
371         break;
372       case NeverFallThroughOrReturn:
373         if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
374           if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
375             S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
376               << 0 << FD;
377           } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
378             S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn)
379               << 1 << MD;
380           } else {
381             S.Diag(Compound->getLBracLoc(), CD.diag_NeverFallThroughOrReturn);
382           }
383         }
384         break;
385       case NeverFallThrough:
386         break;
387     }
388   }
389 }
390 
391 //===----------------------------------------------------------------------===//
392 // -Wuninitialized
393 //===----------------------------------------------------------------------===//
394 
395 namespace {
396 /// ContainsReference - A visitor class to search for references to
397 /// a particular declaration (the needle) within any evaluated component of an
398 /// expression (recursively).
399 class ContainsReference : public EvaluatedExprVisitor<ContainsReference> {
400   bool FoundReference;
401   const DeclRefExpr *Needle;
402 
403 public:
404   ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
405     : EvaluatedExprVisitor<ContainsReference>(Context),
406       FoundReference(false), Needle(Needle) {}
407 
408   void VisitExpr(Expr *E) {
409     // Stop evaluating if we already have a reference.
410     if (FoundReference)
411       return;
412 
413     EvaluatedExprVisitor<ContainsReference>::VisitExpr(E);
414   }
415 
416   void VisitDeclRefExpr(DeclRefExpr *E) {
417     if (E == Needle)
418       FoundReference = true;
419     else
420       EvaluatedExprVisitor<ContainsReference>::VisitDeclRefExpr(E);
421   }
422 
423   bool doesContainReference() const { return FoundReference; }
424 };
425 }
426 
427 static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
428   // Don't issue a fixit if there is already an initializer.
429   if (VD->getInit())
430     return false;
431 
432   // Suggest possible initialization (if any).
433   QualType VariableTy = VD->getType().getCanonicalType();
434   const char *Init = S.getFixItZeroInitializerForType(VariableTy);
435   if (!Init)
436     return false;
437 
438   SourceLocation Loc = S.PP.getLocForEndOfToken(VD->getLocEnd());
439   S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
440     << FixItHint::CreateInsertion(Loc, Init);
441   return true;
442 }
443 
444 /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
445 /// uninitialized variable. This manages the different forms of diagnostic
446 /// emitted for particular types of uses. Returns true if the use was diagnosed
447 /// as a warning. If a pariticular use is one we omit warnings for, returns
448 /// false.
449 static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
450                                      const Expr *E, bool isAlwaysUninit,
451                                      bool alwaysReportSelfInit = false) {
452   bool isSelfInit = false;
453 
454   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
455     if (isAlwaysUninit) {
456       // Inspect the initializer of the variable declaration which is
457       // being referenced prior to its initialization. We emit
458       // specialized diagnostics for self-initialization, and we
459       // specifically avoid warning about self references which take the
460       // form of:
461       //
462       //   int x = x;
463       //
464       // This is used to indicate to GCC that 'x' is intentionally left
465       // uninitialized. Proven code paths which access 'x' in
466       // an uninitialized state after this will still warn.
467       //
468       // TODO: Should we suppress maybe-uninitialized warnings for
469       // variables initialized in this way?
470       if (const Expr *Initializer = VD->getInit()) {
471         if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
472           return false;
473 
474         ContainsReference CR(S.Context, DRE);
475         CR.Visit(const_cast<Expr*>(Initializer));
476         isSelfInit = CR.doesContainReference();
477       }
478       if (isSelfInit) {
479         S.Diag(DRE->getLocStart(),
480                diag::warn_uninit_self_reference_in_init)
481         << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
482       } else {
483         S.Diag(DRE->getLocStart(), diag::warn_uninit_var)
484           << VD->getDeclName() << DRE->getSourceRange();
485       }
486     } else {
487       S.Diag(DRE->getLocStart(), diag::warn_maybe_uninit_var)
488         << VD->getDeclName() << DRE->getSourceRange();
489     }
490   } else {
491     const BlockExpr *BE = cast<BlockExpr>(E);
492     S.Diag(BE->getLocStart(),
493            isAlwaysUninit ? diag::warn_uninit_var_captured_by_block
494                           : diag::warn_maybe_uninit_var_captured_by_block)
495       << VD->getDeclName();
496   }
497 
498   // Report where the variable was declared when the use wasn't within
499   // the initializer of that declaration & we didn't already suggest
500   // an initialization fixit.
501   if (!isSelfInit && !SuggestInitializationFixit(S, VD))
502     S.Diag(VD->getLocStart(), diag::note_uninit_var_def)
503       << VD->getDeclName();
504 
505   return true;
506 }
507 
508 typedef std::pair<const Expr*, bool> UninitUse;
509 
510 namespace {
511 struct SLocSort {
512   bool operator()(const UninitUse &a, const UninitUse &b) {
513     SourceLocation aLoc = a.first->getLocStart();
514     SourceLocation bLoc = b.first->getLocStart();
515     return aLoc.getRawEncoding() < bLoc.getRawEncoding();
516   }
517 };
518 
519 class UninitValsDiagReporter : public UninitVariablesHandler {
520   Sema &S;
521   typedef SmallVector<UninitUse, 2> UsesVec;
522   typedef llvm::DenseMap<const VarDecl *, std::pair<UsesVec*, bool> > UsesMap;
523   UsesMap *uses;
524 
525 public:
526   UninitValsDiagReporter(Sema &S) : S(S), uses(0) {}
527   ~UninitValsDiagReporter() {
528     flushDiagnostics();
529   }
530 
531   std::pair<UsesVec*, bool> &getUses(const VarDecl *vd) {
532     if (!uses)
533       uses = new UsesMap();
534 
535     UsesMap::mapped_type &V = (*uses)[vd];
536     UsesVec *&vec = V.first;
537     if (!vec)
538       vec = new UsesVec();
539 
540     return V;
541   }
542 
543   void handleUseOfUninitVariable(const Expr *ex, const VarDecl *vd,
544                                  bool isAlwaysUninit) {
545     getUses(vd).first->push_back(std::make_pair(ex, isAlwaysUninit));
546   }
547 
548   void handleSelfInit(const VarDecl *vd) {
549     getUses(vd).second = true;
550   }
551 
552   void flushDiagnostics() {
553     if (!uses)
554       return;
555 
556     for (UsesMap::iterator i = uses->begin(), e = uses->end(); i != e; ++i) {
557       const VarDecl *vd = i->first;
558       const UsesMap::mapped_type &V = i->second;
559 
560       UsesVec *vec = V.first;
561       bool hasSelfInit = V.second;
562 
563       // Specially handle the case where we have uses of an uninitialized
564       // variable, but the root cause is an idiomatic self-init.  We want
565       // to report the diagnostic at the self-init since that is the root cause.
566       if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
567         DiagnoseUninitializedUse(S, vd, vd->getInit()->IgnoreParenCasts(),
568                                  /* isAlwaysUninit */ true,
569                                  /* alwaysReportSelfInit */ true);
570       else {
571         // Sort the uses by their SourceLocations.  While not strictly
572         // guaranteed to produce them in line/column order, this will provide
573         // a stable ordering.
574         std::sort(vec->begin(), vec->end(), SLocSort());
575 
576         for (UsesVec::iterator vi = vec->begin(), ve = vec->end(); vi != ve;
577              ++vi) {
578           if (DiagnoseUninitializedUse(S, vd, vi->first,
579                                         /*isAlwaysUninit=*/vi->second))
580             // Skip further diagnostics for this variable. We try to warn only
581             // on the first point at which a variable is used uninitialized.
582             break;
583         }
584       }
585 
586       // Release the uses vector.
587       delete vec;
588     }
589     delete uses;
590   }
591 
592 private:
593   static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
594   for (UsesVec::const_iterator i = vec->begin(), e = vec->end(); i != e; ++i) {
595     if (i->second) {
596       return true;
597     }
598   }
599   return false;
600 }
601 };
602 }
603 
604 
605 //===----------------------------------------------------------------------===//
606 // -Wthread-safety
607 //===----------------------------------------------------------------------===//
608 namespace clang {
609 namespace thread_safety {
610 typedef llvm::SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
611 typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
612 typedef llvm::SmallVector<DelayedDiag, 4> DiagList;
613 
614 struct SortDiagBySourceLocation {
615   Sema &S;
616   SortDiagBySourceLocation(Sema &S) : S(S) {}
617 
618   bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
619     // Although this call will be slow, this is only called when outputting
620     // multiple warnings.
621     return S.getSourceManager().isBeforeInTranslationUnit(left.first.first,
622                                                           right.first.first);
623   }
624 };
625 
626 namespace {
627 class ThreadSafetyReporter : public clang::thread_safety::ThreadSafetyHandler {
628   Sema &S;
629   DiagList Warnings;
630   SourceLocation FunLocation, FunEndLocation;
631 
632   // Helper functions
633   void warnLockMismatch(unsigned DiagID, Name LockName, SourceLocation Loc) {
634     // Gracefully handle rare cases when the analysis can't get a more
635     // precise source location.
636     if (!Loc.isValid())
637       Loc = FunLocation;
638     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << LockName);
639     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
640   }
641 
642  public:
643   ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
644     : S(S), FunLocation(FL), FunEndLocation(FEL) {}
645 
646   /// \brief Emit all buffered diagnostics in order of sourcelocation.
647   /// We need to output diagnostics produced while iterating through
648   /// the lockset in deterministic order, so this function orders diagnostics
649   /// and outputs them.
650   void emitDiagnostics() {
651     SortDiagBySourceLocation SortDiagBySL(S);
652     sort(Warnings.begin(), Warnings.end(), SortDiagBySL);
653     for (DiagList::iterator I = Warnings.begin(), E = Warnings.end();
654          I != E; ++I) {
655       S.Diag(I->first.first, I->first.second);
656       const OptionalNotes &Notes = I->second;
657       for (unsigned NoteI = 0, NoteN = Notes.size(); NoteI != NoteN; ++NoteI)
658         S.Diag(Notes[NoteI].first, Notes[NoteI].second);
659     }
660   }
661 
662   void handleInvalidLockExp(SourceLocation Loc) {
663     PartialDiagnosticAt Warning(Loc,
664                                 S.PDiag(diag::warn_cannot_resolve_lock) << Loc);
665     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
666   }
667   void handleUnmatchedUnlock(Name LockName, SourceLocation Loc) {
668     warnLockMismatch(diag::warn_unlock_but_no_lock, LockName, Loc);
669   }
670 
671   void handleDoubleLock(Name LockName, SourceLocation Loc) {
672     warnLockMismatch(diag::warn_double_lock, LockName, Loc);
673   }
674 
675   void handleMutexHeldEndOfScope(Name LockName, SourceLocation LocLocked,
676                                  SourceLocation LocEndOfScope,
677                                  LockErrorKind LEK){
678     unsigned DiagID = 0;
679     switch (LEK) {
680       case LEK_LockedSomePredecessors:
681         DiagID = diag::warn_lock_some_predecessors;
682         break;
683       case LEK_LockedSomeLoopIterations:
684         DiagID = diag::warn_expecting_lock_held_on_loop;
685         break;
686       case LEK_LockedAtEndOfFunction:
687         DiagID = diag::warn_no_unlock;
688         break;
689     }
690     if (LocEndOfScope.isInvalid())
691       LocEndOfScope = FunEndLocation;
692 
693     PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << LockName);
694     PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here));
695     Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
696   }
697 
698 
699   void handleExclusiveAndShared(Name LockName, SourceLocation Loc1,
700                                 SourceLocation Loc2) {
701     PartialDiagnosticAt Warning(
702       Loc1, S.PDiag(diag::warn_lock_exclusive_and_shared) << LockName);
703     PartialDiagnosticAt Note(
704       Loc2, S.PDiag(diag::note_lock_exclusive_and_shared) << LockName);
705     Warnings.push_back(DelayedDiag(Warning, OptionalNotes(1, Note)));
706   }
707 
708   void handleNoMutexHeld(const NamedDecl *D, ProtectedOperationKind POK,
709                          AccessKind AK, SourceLocation Loc) {
710     assert((POK == POK_VarAccess || POK == POK_VarDereference)
711              && "Only works for variables");
712     unsigned DiagID = POK == POK_VarAccess?
713                         diag::warn_variable_requires_any_lock:
714                         diag::warn_var_deref_requires_any_lock;
715     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
716       << D->getName() << getLockKindFromAccessKind(AK));
717     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
718   }
719 
720   void handleMutexNotHeld(const NamedDecl *D, ProtectedOperationKind POK,
721                           Name LockName, LockKind LK, SourceLocation Loc) {
722     unsigned DiagID = 0;
723     switch (POK) {
724       case POK_VarAccess:
725         DiagID = diag::warn_variable_requires_lock;
726         break;
727       case POK_VarDereference:
728         DiagID = diag::warn_var_deref_requires_lock;
729         break;
730       case POK_FunctionCall:
731         DiagID = diag::warn_fun_requires_lock;
732         break;
733     }
734     PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
735       << D->getName() << LockName << LK);
736     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
737   }
738 
739   void handleFunExcludesLock(Name FunName, Name LockName, SourceLocation Loc) {
740     PartialDiagnosticAt Warning(Loc,
741       S.PDiag(diag::warn_fun_excludes_mutex) << FunName << LockName);
742     Warnings.push_back(DelayedDiag(Warning, OptionalNotes()));
743   }
744 };
745 }
746 }
747 }
748 
749 //===----------------------------------------------------------------------===//
750 // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
751 //  warnings on a function, method, or block.
752 //===----------------------------------------------------------------------===//
753 
754 clang::sema::AnalysisBasedWarnings::Policy::Policy() {
755   enableCheckFallThrough = 1;
756   enableCheckUnreachable = 0;
757   enableThreadSafetyAnalysis = 0;
758 }
759 
760 clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
761   : S(s),
762     NumFunctionsAnalyzed(0),
763     NumFunctionsWithBadCFGs(0),
764     NumCFGBlocks(0),
765     MaxCFGBlocksPerFunction(0),
766     NumUninitAnalysisFunctions(0),
767     NumUninitAnalysisVariables(0),
768     MaxUninitAnalysisVariablesPerFunction(0),
769     NumUninitAnalysisBlockVisits(0),
770     MaxUninitAnalysisBlockVisitsPerFunction(0) {
771   DiagnosticsEngine &D = S.getDiagnostics();
772   DefaultPolicy.enableCheckUnreachable = (unsigned)
773     (D.getDiagnosticLevel(diag::warn_unreachable, SourceLocation()) !=
774         DiagnosticsEngine::Ignored);
775   DefaultPolicy.enableThreadSafetyAnalysis = (unsigned)
776     (D.getDiagnosticLevel(diag::warn_double_lock, SourceLocation()) !=
777      DiagnosticsEngine::Ignored);
778 
779 }
780 
781 static void flushDiagnostics(Sema &S, sema::FunctionScopeInfo *fscope) {
782   for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
783        i = fscope->PossiblyUnreachableDiags.begin(),
784        e = fscope->PossiblyUnreachableDiags.end();
785        i != e; ++i) {
786     const sema::PossiblyUnreachableDiag &D = *i;
787     S.Diag(D.Loc, D.PD);
788   }
789 }
790 
791 void clang::sema::
792 AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
793                                      sema::FunctionScopeInfo *fscope,
794                                      const Decl *D, const BlockExpr *blkExpr) {
795 
796   // We avoid doing analysis-based warnings when there are errors for
797   // two reasons:
798   // (1) The CFGs often can't be constructed (if the body is invalid), so
799   //     don't bother trying.
800   // (2) The code already has problems; running the analysis just takes more
801   //     time.
802   DiagnosticsEngine &Diags = S.getDiagnostics();
803 
804   // Do not do any analysis for declarations in system headers if we are
805   // going to just ignore them.
806   if (Diags.getSuppressSystemWarnings() &&
807       S.SourceMgr.isInSystemHeader(D->getLocation()))
808     return;
809 
810   // For code in dependent contexts, we'll do this at instantiation time.
811   if (cast<DeclContext>(D)->isDependentContext())
812     return;
813 
814   if (Diags.hasErrorOccurred() || Diags.hasFatalErrorOccurred()) {
815     // Flush out any possibly unreachable diagnostics.
816     flushDiagnostics(S, fscope);
817     return;
818   }
819 
820   const Stmt *Body = D->getBody();
821   assert(Body);
822 
823   AnalysisDeclContext AC(/* AnalysisDeclContextManager */ 0,  D, 0);
824 
825   // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
826   // explosion for destrutors that can result and the compile time hit.
827   AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
828   AC.getCFGBuildOptions().AddEHEdges = false;
829   AC.getCFGBuildOptions().AddInitializers = true;
830   AC.getCFGBuildOptions().AddImplicitDtors = true;
831 
832   // Force that certain expressions appear as CFGElements in the CFG.  This
833   // is used to speed up various analyses.
834   // FIXME: This isn't the right factoring.  This is here for initial
835   // prototyping, but we need a way for analyses to say what expressions they
836   // expect to always be CFGElements and then fill in the BuildOptions
837   // appropriately.  This is essentially a layering violation.
838   if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis) {
839     // Unreachable code analysis and thread safety require a linearized CFG.
840     AC.getCFGBuildOptions().setAllAlwaysAdd();
841   }
842   else {
843     AC.getCFGBuildOptions()
844       .setAlwaysAdd(Stmt::BinaryOperatorClass)
845       .setAlwaysAdd(Stmt::BlockExprClass)
846       .setAlwaysAdd(Stmt::CStyleCastExprClass)
847       .setAlwaysAdd(Stmt::DeclRefExprClass)
848       .setAlwaysAdd(Stmt::ImplicitCastExprClass)
849       .setAlwaysAdd(Stmt::UnaryOperatorClass);
850   }
851 
852   // Construct the analysis context with the specified CFG build options.
853 
854   // Emit delayed diagnostics.
855   if (!fscope->PossiblyUnreachableDiags.empty()) {
856     bool analyzed = false;
857 
858     // Register the expressions with the CFGBuilder.
859     for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
860          i = fscope->PossiblyUnreachableDiags.begin(),
861          e = fscope->PossiblyUnreachableDiags.end();
862          i != e; ++i) {
863       if (const Stmt *stmt = i->stmt)
864         AC.registerForcedBlockExpression(stmt);
865     }
866 
867     if (AC.getCFG()) {
868       analyzed = true;
869       for (SmallVectorImpl<sema::PossiblyUnreachableDiag>::iterator
870             i = fscope->PossiblyUnreachableDiags.begin(),
871             e = fscope->PossiblyUnreachableDiags.end();
872             i != e; ++i)
873       {
874         const sema::PossiblyUnreachableDiag &D = *i;
875         bool processed = false;
876         if (const Stmt *stmt = i->stmt) {
877           const CFGBlock *block = AC.getBlockForRegisteredExpression(stmt);
878           CFGReverseBlockReachabilityAnalysis *cra =
879               AC.getCFGReachablityAnalysis();
880           // FIXME: We should be able to assert that block is non-null, but
881           // the CFG analysis can skip potentially-evaluated expressions in
882           // edge cases; see test/Sema/vla-2.c.
883           if (block && cra) {
884             // Can this block be reached from the entrance?
885             if (cra->isReachable(&AC.getCFG()->getEntry(), block))
886               S.Diag(D.Loc, D.PD);
887             processed = true;
888           }
889         }
890         if (!processed) {
891           // Emit the warning anyway if we cannot map to a basic block.
892           S.Diag(D.Loc, D.PD);
893         }
894       }
895     }
896 
897     if (!analyzed)
898       flushDiagnostics(S, fscope);
899   }
900 
901 
902   // Warning: check missing 'return'
903   if (P.enableCheckFallThrough) {
904     const CheckFallThroughDiagnostics &CD =
905       (isa<BlockDecl>(D) ? CheckFallThroughDiagnostics::MakeForBlock()
906        : (isa<CXXMethodDecl>(D) &&
907           cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
908           cast<CXXMethodDecl>(D)->getParent()->isLambda())
909             ? CheckFallThroughDiagnostics::MakeForLambda()
910             : CheckFallThroughDiagnostics::MakeForFunction(D));
911     CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC);
912   }
913 
914   // Warning: check for unreachable code
915   if (P.enableCheckUnreachable) {
916     // Only check for unreachable code on non-template instantiations.
917     // Different template instantiations can effectively change the control-flow
918     // and it is very difficult to prove that a snippet of code in a template
919     // is unreachable for all instantiations.
920     bool isTemplateInstantiation = false;
921     if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
922       isTemplateInstantiation = Function->isTemplateInstantiation();
923     if (!isTemplateInstantiation)
924       CheckUnreachable(S, AC);
925   }
926 
927   // Check for thread safety violations
928   if (P.enableThreadSafetyAnalysis) {
929     SourceLocation FL = AC.getDecl()->getLocation();
930     SourceLocation FEL = AC.getDecl()->getLocEnd();
931     thread_safety::ThreadSafetyReporter Reporter(S, FL, FEL);
932     thread_safety::runThreadSafetyAnalysis(AC, Reporter);
933     Reporter.emitDiagnostics();
934   }
935 
936   if (Diags.getDiagnosticLevel(diag::warn_uninit_var, D->getLocStart())
937       != DiagnosticsEngine::Ignored ||
938       Diags.getDiagnosticLevel(diag::warn_maybe_uninit_var, D->getLocStart())
939       != DiagnosticsEngine::Ignored) {
940     if (CFG *cfg = AC.getCFG()) {
941       UninitValsDiagReporter reporter(S);
942       UninitVariablesAnalysisStats stats;
943       std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
944       runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
945                                         reporter, stats);
946 
947       if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
948         ++NumUninitAnalysisFunctions;
949         NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
950         NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
951         MaxUninitAnalysisVariablesPerFunction =
952             std::max(MaxUninitAnalysisVariablesPerFunction,
953                      stats.NumVariablesAnalyzed);
954         MaxUninitAnalysisBlockVisitsPerFunction =
955             std::max(MaxUninitAnalysisBlockVisitsPerFunction,
956                      stats.NumBlockVisits);
957       }
958     }
959   }
960 
961   // Collect statistics about the CFG if it was built.
962   if (S.CollectStats && AC.isCFGBuilt()) {
963     ++NumFunctionsAnalyzed;
964     if (CFG *cfg = AC.getCFG()) {
965       // If we successfully built a CFG for this context, record some more
966       // detail information about it.
967       NumCFGBlocks += cfg->getNumBlockIDs();
968       MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
969                                          cfg->getNumBlockIDs());
970     } else {
971       ++NumFunctionsWithBadCFGs;
972     }
973   }
974 }
975 
976 void clang::sema::AnalysisBasedWarnings::PrintStats() const {
977   llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
978 
979   unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
980   unsigned AvgCFGBlocksPerFunction =
981       !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
982   llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
983                << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
984                << "  " << NumCFGBlocks << " CFG blocks built.\n"
985                << "  " << AvgCFGBlocksPerFunction
986                << " average CFG blocks per function.\n"
987                << "  " << MaxCFGBlocksPerFunction
988                << " max CFG blocks per function.\n";
989 
990   unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
991       : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
992   unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
993       : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
994   llvm::errs() << NumUninitAnalysisFunctions
995                << " functions analyzed for uninitialiazed variables\n"
996                << "  " << NumUninitAnalysisVariables << " variables analyzed.\n"
997                << "  " << AvgUninitVariablesPerFunction
998                << " average variables per function.\n"
999                << "  " << MaxUninitAnalysisVariablesPerFunction
1000                << " max variables per function.\n"
1001                << "  " << NumUninitAnalysisBlockVisits << " block visits.\n"
1002                << "  " << AvgUninitBlockVisitsPerFunction
1003                << " average block visits per function.\n"
1004                << "  " << MaxUninitAnalysisBlockVisitsPerFunction
1005                << " max block visits per function.\n";
1006 }
1007