AnalysisBasedWarnings.cpp 81 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268
  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. #include "clang/Sema/AnalysisBasedWarnings.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclObjC.h"
  18. #include "clang/AST/EvaluatedExprVisitor.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExprObjC.h"
  21. #include "clang/AST/ParentMap.h"
  22. #include "clang/AST/RecursiveASTVisitor.h"
  23. #include "clang/AST/StmtCXX.h"
  24. #include "clang/AST/StmtObjC.h"
  25. #include "clang/AST/StmtVisitor.h"
  26. #include "clang/Analysis/Analyses/CFGReachabilityAnalysis.h"
  27. #include "clang/Analysis/Analyses/Consumed.h"
  28. #include "clang/Analysis/Analyses/ReachableCode.h"
  29. #include "clang/Analysis/Analyses/ThreadSafety.h"
  30. #include "clang/Analysis/Analyses/UninitializedValues.h"
  31. #include "clang/Analysis/AnalysisDeclContext.h"
  32. #include "clang/Analysis/CFG.h"
  33. #include "clang/Analysis/CFGStmtMap.h"
  34. #include "clang/Basic/SourceLocation.h"
  35. #include "clang/Basic/SourceManager.h"
  36. #include "clang/Lex/Preprocessor.h"
  37. #include "clang/Sema/ScopeInfo.h"
  38. #include "clang/Sema/SemaInternal.h"
  39. #include "llvm/ADT/BitVector.h"
  40. #include "llvm/ADT/MapVector.h"
  41. #include "llvm/ADT/SmallString.h"
  42. #include "llvm/ADT/SmallVector.h"
  43. #include "llvm/ADT/StringRef.h"
  44. #include "llvm/Support/Casting.h"
  45. #include <algorithm>
  46. #include <deque>
  47. #include <iterator>
  48. using namespace clang;
  49. //===----------------------------------------------------------------------===//
  50. // Unreachable code analysis.
  51. //===----------------------------------------------------------------------===//
  52. namespace {
  53. class UnreachableCodeHandler : public reachable_code::Callback {
  54. Sema &S;
  55. SourceRange PreviousSilenceableCondVal;
  56. public:
  57. UnreachableCodeHandler(Sema &s) : S(s) {}
  58. void HandleUnreachable(reachable_code::UnreachableKind UK,
  59. SourceLocation L,
  60. SourceRange SilenceableCondVal,
  61. SourceRange R1,
  62. SourceRange R2) override {
  63. // Avoid reporting multiple unreachable code diagnostics that are
  64. // triggered by the same conditional value.
  65. if (PreviousSilenceableCondVal.isValid() &&
  66. SilenceableCondVal.isValid() &&
  67. PreviousSilenceableCondVal == SilenceableCondVal)
  68. return;
  69. PreviousSilenceableCondVal = SilenceableCondVal;
  70. unsigned diag = diag::warn_unreachable;
  71. switch (UK) {
  72. case reachable_code::UK_Break:
  73. diag = diag::warn_unreachable_break;
  74. break;
  75. case reachable_code::UK_Return:
  76. diag = diag::warn_unreachable_return;
  77. break;
  78. case reachable_code::UK_Loop_Increment:
  79. diag = diag::warn_unreachable_loop_increment;
  80. break;
  81. case reachable_code::UK_Other:
  82. break;
  83. }
  84. S.Diag(L, diag) << R1 << R2;
  85. SourceLocation Open = SilenceableCondVal.getBegin();
  86. if (Open.isValid()) {
  87. SourceLocation Close = SilenceableCondVal.getEnd();
  88. Close = S.getLocForEndOfToken(Close);
  89. if (Close.isValid()) {
  90. S.Diag(Open, diag::note_unreachable_silence)
  91. << FixItHint::CreateInsertion(Open, "/* DISABLES CODE */ (")
  92. << FixItHint::CreateInsertion(Close, ")");
  93. }
  94. }
  95. }
  96. };
  97. } // anonymous namespace
  98. /// CheckUnreachable - Check for unreachable code.
  99. static void CheckUnreachable(Sema &S, AnalysisDeclContext &AC) {
  100. // As a heuristic prune all diagnostics not in the main file. Currently
  101. // the majority of warnings in headers are false positives. These
  102. // are largely caused by configuration state, e.g. preprocessor
  103. // defined code, etc.
  104. //
  105. // Note that this is also a performance optimization. Analyzing
  106. // headers many times can be expensive.
  107. if (!S.getSourceManager().isInMainFile(AC.getDecl()->getBeginLoc()))
  108. return;
  109. UnreachableCodeHandler UC(S);
  110. reachable_code::FindUnreachableCode(AC, S.getPreprocessor(), UC);
  111. }
  112. namespace {
  113. /// Warn on logical operator errors in CFGBuilder
  114. class LogicalErrorHandler : public CFGCallback {
  115. Sema &S;
  116. public:
  117. LogicalErrorHandler(Sema &S) : CFGCallback(), S(S) {}
  118. static bool HasMacroID(const Expr *E) {
  119. if (E->getExprLoc().isMacroID())
  120. return true;
  121. // Recurse to children.
  122. for (const Stmt *SubStmt : E->children())
  123. if (const Expr *SubExpr = dyn_cast_or_null<Expr>(SubStmt))
  124. if (HasMacroID(SubExpr))
  125. return true;
  126. return false;
  127. }
  128. void compareAlwaysTrue(const BinaryOperator *B, bool isAlwaysTrue) override {
  129. if (HasMacroID(B))
  130. return;
  131. SourceRange DiagRange = B->getSourceRange();
  132. S.Diag(B->getExprLoc(), diag::warn_tautological_overlap_comparison)
  133. << DiagRange << isAlwaysTrue;
  134. }
  135. void compareBitwiseEquality(const BinaryOperator *B,
  136. bool isAlwaysTrue) override {
  137. if (HasMacroID(B))
  138. return;
  139. SourceRange DiagRange = B->getSourceRange();
  140. S.Diag(B->getExprLoc(), diag::warn_comparison_bitwise_always)
  141. << DiagRange << isAlwaysTrue;
  142. }
  143. };
  144. } // anonymous namespace
  145. //===----------------------------------------------------------------------===//
  146. // Check for infinite self-recursion in functions
  147. //===----------------------------------------------------------------------===//
  148. // Returns true if the function is called anywhere within the CFGBlock.
  149. // For member functions, the additional condition of being call from the
  150. // this pointer is required.
  151. static bool hasRecursiveCallInPath(const FunctionDecl *FD, CFGBlock &Block) {
  152. // Process all the Stmt's in this block to find any calls to FD.
  153. for (const auto &B : Block) {
  154. if (B.getKind() != CFGElement::Statement)
  155. continue;
  156. const CallExpr *CE = dyn_cast<CallExpr>(B.getAs<CFGStmt>()->getStmt());
  157. if (!CE || !CE->getCalleeDecl() ||
  158. CE->getCalleeDecl()->getCanonicalDecl() != FD)
  159. continue;
  160. // Skip function calls which are qualified with a templated class.
  161. if (const DeclRefExpr *DRE =
  162. dyn_cast<DeclRefExpr>(CE->getCallee()->IgnoreParenImpCasts())) {
  163. if (NestedNameSpecifier *NNS = DRE->getQualifier()) {
  164. if (NNS->getKind() == NestedNameSpecifier::TypeSpec &&
  165. isa<TemplateSpecializationType>(NNS->getAsType())) {
  166. continue;
  167. }
  168. }
  169. }
  170. const CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(CE);
  171. if (!MCE || isa<CXXThisExpr>(MCE->getImplicitObjectArgument()) ||
  172. !MCE->getMethodDecl()->isVirtual())
  173. return true;
  174. }
  175. return false;
  176. }
  177. // Returns true if every path from the entry block passes through a call to FD.
  178. static bool checkForRecursiveFunctionCall(const FunctionDecl *FD, CFG *cfg) {
  179. llvm::SmallPtrSet<CFGBlock *, 16> Visited;
  180. llvm::SmallVector<CFGBlock *, 16> WorkList;
  181. // Keep track of whether we found at least one recursive path.
  182. bool foundRecursion = false;
  183. const unsigned ExitID = cfg->getExit().getBlockID();
  184. // Seed the work list with the entry block.
  185. WorkList.push_back(&cfg->getEntry());
  186. while (!WorkList.empty()) {
  187. CFGBlock *Block = WorkList.pop_back_val();
  188. for (auto I = Block->succ_begin(), E = Block->succ_end(); I != E; ++I) {
  189. if (CFGBlock *SuccBlock = *I) {
  190. if (!Visited.insert(SuccBlock).second)
  191. continue;
  192. // Found a path to the exit node without a recursive call.
  193. if (ExitID == SuccBlock->getBlockID())
  194. return false;
  195. // If the successor block contains a recursive call, end analysis there.
  196. if (hasRecursiveCallInPath(FD, *SuccBlock)) {
  197. foundRecursion = true;
  198. continue;
  199. }
  200. WorkList.push_back(SuccBlock);
  201. }
  202. }
  203. }
  204. return foundRecursion;
  205. }
  206. static void checkRecursiveFunction(Sema &S, const FunctionDecl *FD,
  207. const Stmt *Body, AnalysisDeclContext &AC) {
  208. FD = FD->getCanonicalDecl();
  209. // Only run on non-templated functions and non-templated members of
  210. // templated classes.
  211. if (FD->getTemplatedKind() != FunctionDecl::TK_NonTemplate &&
  212. FD->getTemplatedKind() != FunctionDecl::TK_MemberSpecialization)
  213. return;
  214. CFG *cfg = AC.getCFG();
  215. if (!cfg) return;
  216. // Emit diagnostic if a recursive function call is detected for all paths.
  217. if (checkForRecursiveFunctionCall(FD, cfg))
  218. S.Diag(Body->getBeginLoc(), diag::warn_infinite_recursive_function);
  219. }
  220. //===----------------------------------------------------------------------===//
  221. // Check for throw in a non-throwing function.
  222. //===----------------------------------------------------------------------===//
  223. /// Determine whether an exception thrown by E, unwinding from ThrowBlock,
  224. /// can reach ExitBlock.
  225. static bool throwEscapes(Sema &S, const CXXThrowExpr *E, CFGBlock &ThrowBlock,
  226. CFG *Body) {
  227. SmallVector<CFGBlock *, 16> Stack;
  228. llvm::BitVector Queued(Body->getNumBlockIDs());
  229. Stack.push_back(&ThrowBlock);
  230. Queued[ThrowBlock.getBlockID()] = true;
  231. while (!Stack.empty()) {
  232. CFGBlock &UnwindBlock = *Stack.back();
  233. Stack.pop_back();
  234. for (auto &Succ : UnwindBlock.succs()) {
  235. if (!Succ.isReachable() || Queued[Succ->getBlockID()])
  236. continue;
  237. if (Succ->getBlockID() == Body->getExit().getBlockID())
  238. return true;
  239. if (auto *Catch =
  240. dyn_cast_or_null<CXXCatchStmt>(Succ->getLabel())) {
  241. QualType Caught = Catch->getCaughtType();
  242. if (Caught.isNull() || // catch (...) catches everything
  243. !E->getSubExpr() || // throw; is considered cuaght by any handler
  244. S.handlerCanCatch(Caught, E->getSubExpr()->getType()))
  245. // Exception doesn't escape via this path.
  246. break;
  247. } else {
  248. Stack.push_back(Succ);
  249. Queued[Succ->getBlockID()] = true;
  250. }
  251. }
  252. }
  253. return false;
  254. }
  255. static void visitReachableThrows(
  256. CFG *BodyCFG,
  257. llvm::function_ref<void(const CXXThrowExpr *, CFGBlock &)> Visit) {
  258. llvm::BitVector Reachable(BodyCFG->getNumBlockIDs());
  259. clang::reachable_code::ScanReachableFromBlock(&BodyCFG->getEntry(), Reachable);
  260. for (CFGBlock *B : *BodyCFG) {
  261. if (!Reachable[B->getBlockID()])
  262. continue;
  263. for (CFGElement &E : *B) {
  264. Optional<CFGStmt> S = E.getAs<CFGStmt>();
  265. if (!S)
  266. continue;
  267. if (auto *Throw = dyn_cast<CXXThrowExpr>(S->getStmt()))
  268. Visit(Throw, *B);
  269. }
  270. }
  271. }
  272. static void EmitDiagForCXXThrowInNonThrowingFunc(Sema &S, SourceLocation OpLoc,
  273. const FunctionDecl *FD) {
  274. if (!S.getSourceManager().isInSystemHeader(OpLoc) &&
  275. FD->getTypeSourceInfo()) {
  276. S.Diag(OpLoc, diag::warn_throw_in_noexcept_func) << FD;
  277. if (S.getLangOpts().CPlusPlus11 &&
  278. (isa<CXXDestructorDecl>(FD) ||
  279. FD->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
  280. FD->getDeclName().getCXXOverloadedOperator() == OO_Array_Delete)) {
  281. if (const auto *Ty = FD->getTypeSourceInfo()->getType()->
  282. getAs<FunctionProtoType>())
  283. S.Diag(FD->getLocation(), diag::note_throw_in_dtor)
  284. << !isa<CXXDestructorDecl>(FD) << !Ty->hasExceptionSpec()
  285. << FD->getExceptionSpecSourceRange();
  286. } else
  287. S.Diag(FD->getLocation(), diag::note_throw_in_function)
  288. << FD->getExceptionSpecSourceRange();
  289. }
  290. }
  291. static void checkThrowInNonThrowingFunc(Sema &S, const FunctionDecl *FD,
  292. AnalysisDeclContext &AC) {
  293. CFG *BodyCFG = AC.getCFG();
  294. if (!BodyCFG)
  295. return;
  296. if (BodyCFG->getExit().pred_empty())
  297. return;
  298. visitReachableThrows(BodyCFG, [&](const CXXThrowExpr *Throw, CFGBlock &Block) {
  299. if (throwEscapes(S, Throw, Block, BodyCFG))
  300. EmitDiagForCXXThrowInNonThrowingFunc(S, Throw->getThrowLoc(), FD);
  301. });
  302. }
  303. static bool isNoexcept(const FunctionDecl *FD) {
  304. const auto *FPT = FD->getType()->castAs<FunctionProtoType>();
  305. if (FPT->isNothrow() || FD->hasAttr<NoThrowAttr>())
  306. return true;
  307. return false;
  308. }
  309. //===----------------------------------------------------------------------===//
  310. // Check for missing return value.
  311. //===----------------------------------------------------------------------===//
  312. enum ControlFlowKind {
  313. UnknownFallThrough,
  314. NeverFallThrough,
  315. MaybeFallThrough,
  316. AlwaysFallThrough,
  317. NeverFallThroughOrReturn
  318. };
  319. /// CheckFallThrough - Check that we don't fall off the end of a
  320. /// Statement that should return a value.
  321. ///
  322. /// \returns AlwaysFallThrough iff we always fall off the end of the statement,
  323. /// MaybeFallThrough iff we might or might not fall off the end,
  324. /// NeverFallThroughOrReturn iff we never fall off the end of the statement or
  325. /// return. We assume NeverFallThrough iff we never fall off the end of the
  326. /// statement but we may return. We assume that functions not marked noreturn
  327. /// will return.
  328. static ControlFlowKind CheckFallThrough(AnalysisDeclContext &AC) {
  329. CFG *cfg = AC.getCFG();
  330. if (!cfg) return UnknownFallThrough;
  331. // The CFG leaves in dead things, and we don't want the dead code paths to
  332. // confuse us, so we mark all live things first.
  333. llvm::BitVector live(cfg->getNumBlockIDs());
  334. unsigned count = reachable_code::ScanReachableFromBlock(&cfg->getEntry(),
  335. live);
  336. bool AddEHEdges = AC.getAddEHEdges();
  337. if (!AddEHEdges && count != cfg->getNumBlockIDs())
  338. // When there are things remaining dead, and we didn't add EH edges
  339. // from CallExprs to the catch clauses, we have to go back and
  340. // mark them as live.
  341. for (const auto *B : *cfg) {
  342. if (!live[B->getBlockID()]) {
  343. if (B->pred_begin() == B->pred_end()) {
  344. if (B->getTerminator() && isa<CXXTryStmt>(B->getTerminator()))
  345. // When not adding EH edges from calls, catch clauses
  346. // can otherwise seem dead. Avoid noting them as dead.
  347. count += reachable_code::ScanReachableFromBlock(B, live);
  348. continue;
  349. }
  350. }
  351. }
  352. // Now we know what is live, we check the live precessors of the exit block
  353. // and look for fall through paths, being careful to ignore normal returns,
  354. // and exceptional paths.
  355. bool HasLiveReturn = false;
  356. bool HasFakeEdge = false;
  357. bool HasPlainEdge = false;
  358. bool HasAbnormalEdge = false;
  359. // Ignore default cases that aren't likely to be reachable because all
  360. // enums in a switch(X) have explicit case statements.
  361. CFGBlock::FilterOptions FO;
  362. FO.IgnoreDefaultsWithCoveredEnums = 1;
  363. for (CFGBlock::filtered_pred_iterator I =
  364. cfg->getExit().filtered_pred_start_end(FO);
  365. I.hasMore(); ++I) {
  366. const CFGBlock &B = **I;
  367. if (!live[B.getBlockID()])
  368. continue;
  369. // Skip blocks which contain an element marked as no-return. They don't
  370. // represent actually viable edges into the exit block, so mark them as
  371. // abnormal.
  372. if (B.hasNoReturnElement()) {
  373. HasAbnormalEdge = true;
  374. continue;
  375. }
  376. // Destructors can appear after the 'return' in the CFG. This is
  377. // normal. We need to look pass the destructors for the return
  378. // statement (if it exists).
  379. CFGBlock::const_reverse_iterator ri = B.rbegin(), re = B.rend();
  380. for ( ; ri != re ; ++ri)
  381. if (ri->getAs<CFGStmt>())
  382. break;
  383. // No more CFGElements in the block?
  384. if (ri == re) {
  385. if (B.getTerminator() && isa<CXXTryStmt>(B.getTerminator())) {
  386. HasAbnormalEdge = true;
  387. continue;
  388. }
  389. // A labeled empty statement, or the entry block...
  390. HasPlainEdge = true;
  391. continue;
  392. }
  393. CFGStmt CS = ri->castAs<CFGStmt>();
  394. const Stmt *S = CS.getStmt();
  395. if (isa<ReturnStmt>(S) || isa<CoreturnStmt>(S)) {
  396. HasLiveReturn = true;
  397. continue;
  398. }
  399. if (isa<ObjCAtThrowStmt>(S)) {
  400. HasFakeEdge = true;
  401. continue;
  402. }
  403. if (isa<CXXThrowExpr>(S)) {
  404. HasFakeEdge = true;
  405. continue;
  406. }
  407. if (isa<MSAsmStmt>(S)) {
  408. // TODO: Verify this is correct.
  409. HasFakeEdge = true;
  410. HasLiveReturn = true;
  411. continue;
  412. }
  413. if (isa<CXXTryStmt>(S)) {
  414. HasAbnormalEdge = true;
  415. continue;
  416. }
  417. if (std::find(B.succ_begin(), B.succ_end(), &cfg->getExit())
  418. == B.succ_end()) {
  419. HasAbnormalEdge = true;
  420. continue;
  421. }
  422. HasPlainEdge = true;
  423. }
  424. if (!HasPlainEdge) {
  425. if (HasLiveReturn)
  426. return NeverFallThrough;
  427. return NeverFallThroughOrReturn;
  428. }
  429. if (HasAbnormalEdge || HasFakeEdge || HasLiveReturn)
  430. return MaybeFallThrough;
  431. // This says AlwaysFallThrough for calls to functions that are not marked
  432. // noreturn, that don't return. If people would like this warning to be more
  433. // accurate, such functions should be marked as noreturn.
  434. return AlwaysFallThrough;
  435. }
  436. namespace {
  437. struct CheckFallThroughDiagnostics {
  438. unsigned diag_MaybeFallThrough_HasNoReturn;
  439. unsigned diag_MaybeFallThrough_ReturnsNonVoid;
  440. unsigned diag_AlwaysFallThrough_HasNoReturn;
  441. unsigned diag_AlwaysFallThrough_ReturnsNonVoid;
  442. unsigned diag_NeverFallThroughOrReturn;
  443. enum { Function, Block, Lambda, Coroutine } funMode;
  444. SourceLocation FuncLoc;
  445. static CheckFallThroughDiagnostics MakeForFunction(const Decl *Func) {
  446. CheckFallThroughDiagnostics D;
  447. D.FuncLoc = Func->getLocation();
  448. D.diag_MaybeFallThrough_HasNoReturn =
  449. diag::warn_falloff_noreturn_function;
  450. D.diag_MaybeFallThrough_ReturnsNonVoid =
  451. diag::warn_maybe_falloff_nonvoid_function;
  452. D.diag_AlwaysFallThrough_HasNoReturn =
  453. diag::warn_falloff_noreturn_function;
  454. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  455. diag::warn_falloff_nonvoid_function;
  456. // Don't suggest that virtual functions be marked "noreturn", since they
  457. // might be overridden by non-noreturn functions.
  458. bool isVirtualMethod = false;
  459. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Func))
  460. isVirtualMethod = Method->isVirtual();
  461. // Don't suggest that template instantiations be marked "noreturn"
  462. bool isTemplateInstantiation = false;
  463. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(Func))
  464. isTemplateInstantiation = Function->isTemplateInstantiation();
  465. if (!isVirtualMethod && !isTemplateInstantiation)
  466. D.diag_NeverFallThroughOrReturn =
  467. diag::warn_suggest_noreturn_function;
  468. else
  469. D.diag_NeverFallThroughOrReturn = 0;
  470. D.funMode = Function;
  471. return D;
  472. }
  473. static CheckFallThroughDiagnostics MakeForCoroutine(const Decl *Func) {
  474. CheckFallThroughDiagnostics D;
  475. D.FuncLoc = Func->getLocation();
  476. D.diag_MaybeFallThrough_HasNoReturn = 0;
  477. D.diag_MaybeFallThrough_ReturnsNonVoid =
  478. diag::warn_maybe_falloff_nonvoid_coroutine;
  479. D.diag_AlwaysFallThrough_HasNoReturn = 0;
  480. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  481. diag::warn_falloff_nonvoid_coroutine;
  482. D.funMode = Coroutine;
  483. return D;
  484. }
  485. static CheckFallThroughDiagnostics MakeForBlock() {
  486. CheckFallThroughDiagnostics D;
  487. D.diag_MaybeFallThrough_HasNoReturn =
  488. diag::err_noreturn_block_has_return_expr;
  489. D.diag_MaybeFallThrough_ReturnsNonVoid =
  490. diag::err_maybe_falloff_nonvoid_block;
  491. D.diag_AlwaysFallThrough_HasNoReturn =
  492. diag::err_noreturn_block_has_return_expr;
  493. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  494. diag::err_falloff_nonvoid_block;
  495. D.diag_NeverFallThroughOrReturn = 0;
  496. D.funMode = Block;
  497. return D;
  498. }
  499. static CheckFallThroughDiagnostics MakeForLambda() {
  500. CheckFallThroughDiagnostics D;
  501. D.diag_MaybeFallThrough_HasNoReturn =
  502. diag::err_noreturn_lambda_has_return_expr;
  503. D.diag_MaybeFallThrough_ReturnsNonVoid =
  504. diag::warn_maybe_falloff_nonvoid_lambda;
  505. D.diag_AlwaysFallThrough_HasNoReturn =
  506. diag::err_noreturn_lambda_has_return_expr;
  507. D.diag_AlwaysFallThrough_ReturnsNonVoid =
  508. diag::warn_falloff_nonvoid_lambda;
  509. D.diag_NeverFallThroughOrReturn = 0;
  510. D.funMode = Lambda;
  511. return D;
  512. }
  513. bool checkDiagnostics(DiagnosticsEngine &D, bool ReturnsVoid,
  514. bool HasNoReturn) const {
  515. if (funMode == Function) {
  516. return (ReturnsVoid ||
  517. D.isIgnored(diag::warn_maybe_falloff_nonvoid_function,
  518. FuncLoc)) &&
  519. (!HasNoReturn ||
  520. D.isIgnored(diag::warn_noreturn_function_has_return_expr,
  521. FuncLoc)) &&
  522. (!ReturnsVoid ||
  523. D.isIgnored(diag::warn_suggest_noreturn_block, FuncLoc));
  524. }
  525. if (funMode == Coroutine) {
  526. return (ReturnsVoid ||
  527. D.isIgnored(diag::warn_maybe_falloff_nonvoid_function, FuncLoc) ||
  528. D.isIgnored(diag::warn_maybe_falloff_nonvoid_coroutine,
  529. FuncLoc)) &&
  530. (!HasNoReturn);
  531. }
  532. // For blocks / lambdas.
  533. return ReturnsVoid && !HasNoReturn;
  534. }
  535. };
  536. } // anonymous namespace
  537. /// CheckFallThroughForBody - Check that we don't fall off the end of a
  538. /// function that should return a value. Check that we don't fall off the end
  539. /// of a noreturn function. We assume that functions and blocks not marked
  540. /// noreturn will return.
  541. static void CheckFallThroughForBody(Sema &S, const Decl *D, const Stmt *Body,
  542. const BlockExpr *blkExpr,
  543. const CheckFallThroughDiagnostics &CD,
  544. AnalysisDeclContext &AC,
  545. sema::FunctionScopeInfo *FSI) {
  546. bool ReturnsVoid = false;
  547. bool HasNoReturn = false;
  548. bool IsCoroutine = FSI->isCoroutine();
  549. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  550. if (const auto *CBody = dyn_cast<CoroutineBodyStmt>(Body))
  551. ReturnsVoid = CBody->getFallthroughHandler() != nullptr;
  552. else
  553. ReturnsVoid = FD->getReturnType()->isVoidType();
  554. HasNoReturn = FD->isNoReturn();
  555. }
  556. else if (const auto *MD = dyn_cast<ObjCMethodDecl>(D)) {
  557. ReturnsVoid = MD->getReturnType()->isVoidType();
  558. HasNoReturn = MD->hasAttr<NoReturnAttr>();
  559. }
  560. else if (isa<BlockDecl>(D)) {
  561. QualType BlockTy = blkExpr->getType();
  562. if (const FunctionType *FT =
  563. BlockTy->getPointeeType()->getAs<FunctionType>()) {
  564. if (FT->getReturnType()->isVoidType())
  565. ReturnsVoid = true;
  566. if (FT->getNoReturnAttr())
  567. HasNoReturn = true;
  568. }
  569. }
  570. DiagnosticsEngine &Diags = S.getDiagnostics();
  571. // Short circuit for compilation speed.
  572. if (CD.checkDiagnostics(Diags, ReturnsVoid, HasNoReturn))
  573. return;
  574. SourceLocation LBrace = Body->getBeginLoc(), RBrace = Body->getEndLoc();
  575. auto EmitDiag = [&](SourceLocation Loc, unsigned DiagID) {
  576. if (IsCoroutine)
  577. S.Diag(Loc, DiagID) << FSI->CoroutinePromise->getType();
  578. else
  579. S.Diag(Loc, DiagID);
  580. };
  581. // cpu_dispatch functions permit empty function bodies for ICC compatibility.
  582. if (D->getAsFunction() && D->getAsFunction()->isCPUDispatchMultiVersion())
  583. return;
  584. // Either in a function body compound statement, or a function-try-block.
  585. switch (CheckFallThrough(AC)) {
  586. case UnknownFallThrough:
  587. break;
  588. case MaybeFallThrough:
  589. if (HasNoReturn)
  590. EmitDiag(RBrace, CD.diag_MaybeFallThrough_HasNoReturn);
  591. else if (!ReturnsVoid)
  592. EmitDiag(RBrace, CD.diag_MaybeFallThrough_ReturnsNonVoid);
  593. break;
  594. case AlwaysFallThrough:
  595. if (HasNoReturn)
  596. EmitDiag(RBrace, CD.diag_AlwaysFallThrough_HasNoReturn);
  597. else if (!ReturnsVoid)
  598. EmitDiag(RBrace, CD.diag_AlwaysFallThrough_ReturnsNonVoid);
  599. break;
  600. case NeverFallThroughOrReturn:
  601. if (ReturnsVoid && !HasNoReturn && CD.diag_NeverFallThroughOrReturn) {
  602. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  603. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 0 << FD;
  604. } else if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
  605. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn) << 1 << MD;
  606. } else {
  607. S.Diag(LBrace, CD.diag_NeverFallThroughOrReturn);
  608. }
  609. }
  610. break;
  611. case NeverFallThrough:
  612. break;
  613. }
  614. }
  615. //===----------------------------------------------------------------------===//
  616. // -Wuninitialized
  617. //===----------------------------------------------------------------------===//
  618. namespace {
  619. /// ContainsReference - A visitor class to search for references to
  620. /// a particular declaration (the needle) within any evaluated component of an
  621. /// expression (recursively).
  622. class ContainsReference : public ConstEvaluatedExprVisitor<ContainsReference> {
  623. bool FoundReference;
  624. const DeclRefExpr *Needle;
  625. public:
  626. typedef ConstEvaluatedExprVisitor<ContainsReference> Inherited;
  627. ContainsReference(ASTContext &Context, const DeclRefExpr *Needle)
  628. : Inherited(Context), FoundReference(false), Needle(Needle) {}
  629. void VisitExpr(const Expr *E) {
  630. // Stop evaluating if we already have a reference.
  631. if (FoundReference)
  632. return;
  633. Inherited::VisitExpr(E);
  634. }
  635. void VisitDeclRefExpr(const DeclRefExpr *E) {
  636. if (E == Needle)
  637. FoundReference = true;
  638. else
  639. Inherited::VisitDeclRefExpr(E);
  640. }
  641. bool doesContainReference() const { return FoundReference; }
  642. };
  643. } // anonymous namespace
  644. static bool SuggestInitializationFixit(Sema &S, const VarDecl *VD) {
  645. QualType VariableTy = VD->getType().getCanonicalType();
  646. if (VariableTy->isBlockPointerType() &&
  647. !VD->hasAttr<BlocksAttr>()) {
  648. S.Diag(VD->getLocation(), diag::note_block_var_fixit_add_initialization)
  649. << VD->getDeclName()
  650. << FixItHint::CreateInsertion(VD->getLocation(), "__block ");
  651. return true;
  652. }
  653. // Don't issue a fixit if there is already an initializer.
  654. if (VD->getInit())
  655. return false;
  656. // Don't suggest a fixit inside macros.
  657. if (VD->getEndLoc().isMacroID())
  658. return false;
  659. SourceLocation Loc = S.getLocForEndOfToken(VD->getEndLoc());
  660. // Suggest possible initialization (if any).
  661. std::string Init = S.getFixItZeroInitializerForType(VariableTy, Loc);
  662. if (Init.empty())
  663. return false;
  664. S.Diag(Loc, diag::note_var_fixit_add_initialization) << VD->getDeclName()
  665. << FixItHint::CreateInsertion(Loc, Init);
  666. return true;
  667. }
  668. /// Create a fixit to remove an if-like statement, on the assumption that its
  669. /// condition is CondVal.
  670. static void CreateIfFixit(Sema &S, const Stmt *If, const Stmt *Then,
  671. const Stmt *Else, bool CondVal,
  672. FixItHint &Fixit1, FixItHint &Fixit2) {
  673. if (CondVal) {
  674. // If condition is always true, remove all but the 'then'.
  675. Fixit1 = FixItHint::CreateRemoval(
  676. CharSourceRange::getCharRange(If->getBeginLoc(), Then->getBeginLoc()));
  677. if (Else) {
  678. SourceLocation ElseKwLoc = S.getLocForEndOfToken(Then->getEndLoc());
  679. Fixit2 =
  680. FixItHint::CreateRemoval(SourceRange(ElseKwLoc, Else->getEndLoc()));
  681. }
  682. } else {
  683. // If condition is always false, remove all but the 'else'.
  684. if (Else)
  685. Fixit1 = FixItHint::CreateRemoval(CharSourceRange::getCharRange(
  686. If->getBeginLoc(), Else->getBeginLoc()));
  687. else
  688. Fixit1 = FixItHint::CreateRemoval(If->getSourceRange());
  689. }
  690. }
  691. /// DiagUninitUse -- Helper function to produce a diagnostic for an
  692. /// uninitialized use of a variable.
  693. static void DiagUninitUse(Sema &S, const VarDecl *VD, const UninitUse &Use,
  694. bool IsCapturedByBlock) {
  695. bool Diagnosed = false;
  696. switch (Use.getKind()) {
  697. case UninitUse::Always:
  698. S.Diag(Use.getUser()->getBeginLoc(), diag::warn_uninit_var)
  699. << VD->getDeclName() << IsCapturedByBlock
  700. << Use.getUser()->getSourceRange();
  701. return;
  702. case UninitUse::AfterDecl:
  703. case UninitUse::AfterCall:
  704. S.Diag(VD->getLocation(), diag::warn_sometimes_uninit_var)
  705. << VD->getDeclName() << IsCapturedByBlock
  706. << (Use.getKind() == UninitUse::AfterDecl ? 4 : 5)
  707. << const_cast<DeclContext*>(VD->getLexicalDeclContext())
  708. << VD->getSourceRange();
  709. S.Diag(Use.getUser()->getBeginLoc(), diag::note_uninit_var_use)
  710. << IsCapturedByBlock << Use.getUser()->getSourceRange();
  711. return;
  712. case UninitUse::Maybe:
  713. case UninitUse::Sometimes:
  714. // Carry on to report sometimes-uninitialized branches, if possible,
  715. // or a 'may be used uninitialized' diagnostic otherwise.
  716. break;
  717. }
  718. // Diagnose each branch which leads to a sometimes-uninitialized use.
  719. for (UninitUse::branch_iterator I = Use.branch_begin(), E = Use.branch_end();
  720. I != E; ++I) {
  721. assert(Use.getKind() == UninitUse::Sometimes);
  722. const Expr *User = Use.getUser();
  723. const Stmt *Term = I->Terminator;
  724. // Information used when building the diagnostic.
  725. unsigned DiagKind;
  726. StringRef Str;
  727. SourceRange Range;
  728. // FixIts to suppress the diagnostic by removing the dead condition.
  729. // For all binary terminators, branch 0 is taken if the condition is true,
  730. // and branch 1 is taken if the condition is false.
  731. int RemoveDiagKind = -1;
  732. const char *FixitStr =
  733. S.getLangOpts().CPlusPlus ? (I->Output ? "true" : "false")
  734. : (I->Output ? "1" : "0");
  735. FixItHint Fixit1, Fixit2;
  736. switch (Term ? Term->getStmtClass() : Stmt::DeclStmtClass) {
  737. default:
  738. // Don't know how to report this. Just fall back to 'may be used
  739. // uninitialized'. FIXME: Can this happen?
  740. continue;
  741. // "condition is true / condition is false".
  742. case Stmt::IfStmtClass: {
  743. const IfStmt *IS = cast<IfStmt>(Term);
  744. DiagKind = 0;
  745. Str = "if";
  746. Range = IS->getCond()->getSourceRange();
  747. RemoveDiagKind = 0;
  748. CreateIfFixit(S, IS, IS->getThen(), IS->getElse(),
  749. I->Output, Fixit1, Fixit2);
  750. break;
  751. }
  752. case Stmt::ConditionalOperatorClass: {
  753. const ConditionalOperator *CO = cast<ConditionalOperator>(Term);
  754. DiagKind = 0;
  755. Str = "?:";
  756. Range = CO->getCond()->getSourceRange();
  757. RemoveDiagKind = 0;
  758. CreateIfFixit(S, CO, CO->getTrueExpr(), CO->getFalseExpr(),
  759. I->Output, Fixit1, Fixit2);
  760. break;
  761. }
  762. case Stmt::BinaryOperatorClass: {
  763. const BinaryOperator *BO = cast<BinaryOperator>(Term);
  764. if (!BO->isLogicalOp())
  765. continue;
  766. DiagKind = 0;
  767. Str = BO->getOpcodeStr();
  768. Range = BO->getLHS()->getSourceRange();
  769. RemoveDiagKind = 0;
  770. if ((BO->getOpcode() == BO_LAnd && I->Output) ||
  771. (BO->getOpcode() == BO_LOr && !I->Output))
  772. // true && y -> y, false || y -> y.
  773. Fixit1 = FixItHint::CreateRemoval(
  774. SourceRange(BO->getBeginLoc(), BO->getOperatorLoc()));
  775. else
  776. // false && y -> false, true || y -> true.
  777. Fixit1 = FixItHint::CreateReplacement(BO->getSourceRange(), FixitStr);
  778. break;
  779. }
  780. // "loop is entered / loop is exited".
  781. case Stmt::WhileStmtClass:
  782. DiagKind = 1;
  783. Str = "while";
  784. Range = cast<WhileStmt>(Term)->getCond()->getSourceRange();
  785. RemoveDiagKind = 1;
  786. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  787. break;
  788. case Stmt::ForStmtClass:
  789. DiagKind = 1;
  790. Str = "for";
  791. Range = cast<ForStmt>(Term)->getCond()->getSourceRange();
  792. RemoveDiagKind = 1;
  793. if (I->Output)
  794. Fixit1 = FixItHint::CreateRemoval(Range);
  795. else
  796. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  797. break;
  798. case Stmt::CXXForRangeStmtClass:
  799. if (I->Output == 1) {
  800. // The use occurs if a range-based for loop's body never executes.
  801. // That may be impossible, and there's no syntactic fix for this,
  802. // so treat it as a 'may be uninitialized' case.
  803. continue;
  804. }
  805. DiagKind = 1;
  806. Str = "for";
  807. Range = cast<CXXForRangeStmt>(Term)->getRangeInit()->getSourceRange();
  808. break;
  809. // "condition is true / loop is exited".
  810. case Stmt::DoStmtClass:
  811. DiagKind = 2;
  812. Str = "do";
  813. Range = cast<DoStmt>(Term)->getCond()->getSourceRange();
  814. RemoveDiagKind = 1;
  815. Fixit1 = FixItHint::CreateReplacement(Range, FixitStr);
  816. break;
  817. // "switch case is taken".
  818. case Stmt::CaseStmtClass:
  819. DiagKind = 3;
  820. Str = "case";
  821. Range = cast<CaseStmt>(Term)->getLHS()->getSourceRange();
  822. break;
  823. case Stmt::DefaultStmtClass:
  824. DiagKind = 3;
  825. Str = "default";
  826. Range = cast<DefaultStmt>(Term)->getDefaultLoc();
  827. break;
  828. }
  829. S.Diag(Range.getBegin(), diag::warn_sometimes_uninit_var)
  830. << VD->getDeclName() << IsCapturedByBlock << DiagKind
  831. << Str << I->Output << Range;
  832. S.Diag(User->getBeginLoc(), diag::note_uninit_var_use)
  833. << IsCapturedByBlock << User->getSourceRange();
  834. if (RemoveDiagKind != -1)
  835. S.Diag(Fixit1.RemoveRange.getBegin(), diag::note_uninit_fixit_remove_cond)
  836. << RemoveDiagKind << Str << I->Output << Fixit1 << Fixit2;
  837. Diagnosed = true;
  838. }
  839. if (!Diagnosed)
  840. S.Diag(Use.getUser()->getBeginLoc(), diag::warn_maybe_uninit_var)
  841. << VD->getDeclName() << IsCapturedByBlock
  842. << Use.getUser()->getSourceRange();
  843. }
  844. /// DiagnoseUninitializedUse -- Helper function for diagnosing uses of an
  845. /// uninitialized variable. This manages the different forms of diagnostic
  846. /// emitted for particular types of uses. Returns true if the use was diagnosed
  847. /// as a warning. If a particular use is one we omit warnings for, returns
  848. /// false.
  849. static bool DiagnoseUninitializedUse(Sema &S, const VarDecl *VD,
  850. const UninitUse &Use,
  851. bool alwaysReportSelfInit = false) {
  852. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Use.getUser())) {
  853. // Inspect the initializer of the variable declaration which is
  854. // being referenced prior to its initialization. We emit
  855. // specialized diagnostics for self-initialization, and we
  856. // specifically avoid warning about self references which take the
  857. // form of:
  858. //
  859. // int x = x;
  860. //
  861. // This is used to indicate to GCC that 'x' is intentionally left
  862. // uninitialized. Proven code paths which access 'x' in
  863. // an uninitialized state after this will still warn.
  864. if (const Expr *Initializer = VD->getInit()) {
  865. if (!alwaysReportSelfInit && DRE == Initializer->IgnoreParenImpCasts())
  866. return false;
  867. ContainsReference CR(S.Context, DRE);
  868. CR.Visit(Initializer);
  869. if (CR.doesContainReference()) {
  870. S.Diag(DRE->getBeginLoc(), diag::warn_uninit_self_reference_in_init)
  871. << VD->getDeclName() << VD->getLocation() << DRE->getSourceRange();
  872. return true;
  873. }
  874. }
  875. DiagUninitUse(S, VD, Use, false);
  876. } else {
  877. const BlockExpr *BE = cast<BlockExpr>(Use.getUser());
  878. if (VD->getType()->isBlockPointerType() && !VD->hasAttr<BlocksAttr>())
  879. S.Diag(BE->getBeginLoc(),
  880. diag::warn_uninit_byref_blockvar_captured_by_block)
  881. << VD->getDeclName();
  882. else
  883. DiagUninitUse(S, VD, Use, true);
  884. }
  885. // Report where the variable was declared when the use wasn't within
  886. // the initializer of that declaration & we didn't already suggest
  887. // an initialization fixit.
  888. if (!SuggestInitializationFixit(S, VD))
  889. S.Diag(VD->getBeginLoc(), diag::note_var_declared_here)
  890. << VD->getDeclName();
  891. return true;
  892. }
  893. namespace {
  894. class FallthroughMapper : public RecursiveASTVisitor<FallthroughMapper> {
  895. public:
  896. FallthroughMapper(Sema &S)
  897. : FoundSwitchStatements(false),
  898. S(S) {
  899. }
  900. bool foundSwitchStatements() const { return FoundSwitchStatements; }
  901. void markFallthroughVisited(const AttributedStmt *Stmt) {
  902. bool Found = FallthroughStmts.erase(Stmt);
  903. assert(Found);
  904. (void)Found;
  905. }
  906. typedef llvm::SmallPtrSet<const AttributedStmt*, 8> AttrStmts;
  907. const AttrStmts &getFallthroughStmts() const {
  908. return FallthroughStmts;
  909. }
  910. void fillReachableBlocks(CFG *Cfg) {
  911. assert(ReachableBlocks.empty() && "ReachableBlocks already filled");
  912. std::deque<const CFGBlock *> BlockQueue;
  913. ReachableBlocks.insert(&Cfg->getEntry());
  914. BlockQueue.push_back(&Cfg->getEntry());
  915. // Mark all case blocks reachable to avoid problems with switching on
  916. // constants, covered enums, etc.
  917. // These blocks can contain fall-through annotations, and we don't want to
  918. // issue a warn_fallthrough_attr_unreachable for them.
  919. for (const auto *B : *Cfg) {
  920. const Stmt *L = B->getLabel();
  921. if (L && isa<SwitchCase>(L) && ReachableBlocks.insert(B).second)
  922. BlockQueue.push_back(B);
  923. }
  924. while (!BlockQueue.empty()) {
  925. const CFGBlock *P = BlockQueue.front();
  926. BlockQueue.pop_front();
  927. for (CFGBlock::const_succ_iterator I = P->succ_begin(),
  928. E = P->succ_end();
  929. I != E; ++I) {
  930. if (*I && ReachableBlocks.insert(*I).second)
  931. BlockQueue.push_back(*I);
  932. }
  933. }
  934. }
  935. bool checkFallThroughIntoBlock(const CFGBlock &B, int &AnnotatedCnt,
  936. bool IsTemplateInstantiation) {
  937. assert(!ReachableBlocks.empty() && "ReachableBlocks empty");
  938. int UnannotatedCnt = 0;
  939. AnnotatedCnt = 0;
  940. std::deque<const CFGBlock*> BlockQueue(B.pred_begin(), B.pred_end());
  941. while (!BlockQueue.empty()) {
  942. const CFGBlock *P = BlockQueue.front();
  943. BlockQueue.pop_front();
  944. if (!P) continue;
  945. const Stmt *Term = P->getTerminator();
  946. if (Term && isa<SwitchStmt>(Term))
  947. continue; // Switch statement, good.
  948. const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(P->getLabel());
  949. if (SW && SW->getSubStmt() == B.getLabel() && P->begin() == P->end())
  950. continue; // Previous case label has no statements, good.
  951. const LabelStmt *L = dyn_cast_or_null<LabelStmt>(P->getLabel());
  952. if (L && L->getSubStmt() == B.getLabel() && P->begin() == P->end())
  953. continue; // Case label is preceded with a normal label, good.
  954. if (!ReachableBlocks.count(P)) {
  955. for (CFGBlock::const_reverse_iterator ElemIt = P->rbegin(),
  956. ElemEnd = P->rend();
  957. ElemIt != ElemEnd; ++ElemIt) {
  958. if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>()) {
  959. if (const AttributedStmt *AS = asFallThroughAttr(CS->getStmt())) {
  960. // Don't issue a warning for an unreachable fallthrough
  961. // attribute in template instantiations as it may not be
  962. // unreachable in all instantiations of the template.
  963. if (!IsTemplateInstantiation)
  964. S.Diag(AS->getBeginLoc(),
  965. diag::warn_fallthrough_attr_unreachable);
  966. markFallthroughVisited(AS);
  967. ++AnnotatedCnt;
  968. break;
  969. }
  970. // Don't care about other unreachable statements.
  971. }
  972. }
  973. // If there are no unreachable statements, this may be a special
  974. // case in CFG:
  975. // case X: {
  976. // A a; // A has a destructor.
  977. // break;
  978. // }
  979. // // <<<< This place is represented by a 'hanging' CFG block.
  980. // case Y:
  981. continue;
  982. }
  983. const Stmt *LastStmt = getLastStmt(*P);
  984. if (const AttributedStmt *AS = asFallThroughAttr(LastStmt)) {
  985. markFallthroughVisited(AS);
  986. ++AnnotatedCnt;
  987. continue; // Fallthrough annotation, good.
  988. }
  989. if (!LastStmt) { // This block contains no executable statements.
  990. // Traverse its predecessors.
  991. std::copy(P->pred_begin(), P->pred_end(),
  992. std::back_inserter(BlockQueue));
  993. continue;
  994. }
  995. ++UnannotatedCnt;
  996. }
  997. return !!UnannotatedCnt;
  998. }
  999. // RecursiveASTVisitor setup.
  1000. bool shouldWalkTypesOfTypeLocs() const { return false; }
  1001. bool VisitAttributedStmt(AttributedStmt *S) {
  1002. if (asFallThroughAttr(S))
  1003. FallthroughStmts.insert(S);
  1004. return true;
  1005. }
  1006. bool VisitSwitchStmt(SwitchStmt *S) {
  1007. FoundSwitchStatements = true;
  1008. return true;
  1009. }
  1010. // We don't want to traverse local type declarations. We analyze their
  1011. // methods separately.
  1012. bool TraverseDecl(Decl *D) { return true; }
  1013. // We analyze lambda bodies separately. Skip them here.
  1014. bool TraverseLambdaBody(LambdaExpr *LE) { return true; }
  1015. private:
  1016. static const AttributedStmt *asFallThroughAttr(const Stmt *S) {
  1017. if (const AttributedStmt *AS = dyn_cast_or_null<AttributedStmt>(S)) {
  1018. if (hasSpecificAttr<FallThroughAttr>(AS->getAttrs()))
  1019. return AS;
  1020. }
  1021. return nullptr;
  1022. }
  1023. static const Stmt *getLastStmt(const CFGBlock &B) {
  1024. if (const Stmt *Term = B.getTerminator())
  1025. return Term;
  1026. for (CFGBlock::const_reverse_iterator ElemIt = B.rbegin(),
  1027. ElemEnd = B.rend();
  1028. ElemIt != ElemEnd; ++ElemIt) {
  1029. if (Optional<CFGStmt> CS = ElemIt->getAs<CFGStmt>())
  1030. return CS->getStmt();
  1031. }
  1032. // Workaround to detect a statement thrown out by CFGBuilder:
  1033. // case X: {} case Y:
  1034. // case X: ; case Y:
  1035. if (const SwitchCase *SW = dyn_cast_or_null<SwitchCase>(B.getLabel()))
  1036. if (!isa<SwitchCase>(SW->getSubStmt()))
  1037. return SW->getSubStmt();
  1038. return nullptr;
  1039. }
  1040. bool FoundSwitchStatements;
  1041. AttrStmts FallthroughStmts;
  1042. Sema &S;
  1043. llvm::SmallPtrSet<const CFGBlock *, 16> ReachableBlocks;
  1044. };
  1045. } // anonymous namespace
  1046. static StringRef getFallthroughAttrSpelling(Preprocessor &PP,
  1047. SourceLocation Loc) {
  1048. TokenValue FallthroughTokens[] = {
  1049. tok::l_square, tok::l_square,
  1050. PP.getIdentifierInfo("fallthrough"),
  1051. tok::r_square, tok::r_square
  1052. };
  1053. TokenValue ClangFallthroughTokens[] = {
  1054. tok::l_square, tok::l_square, PP.getIdentifierInfo("clang"),
  1055. tok::coloncolon, PP.getIdentifierInfo("fallthrough"),
  1056. tok::r_square, tok::r_square
  1057. };
  1058. bool PreferClangAttr = !PP.getLangOpts().CPlusPlus17;
  1059. StringRef MacroName;
  1060. if (PreferClangAttr)
  1061. MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
  1062. if (MacroName.empty())
  1063. MacroName = PP.getLastMacroWithSpelling(Loc, FallthroughTokens);
  1064. if (MacroName.empty() && !PreferClangAttr)
  1065. MacroName = PP.getLastMacroWithSpelling(Loc, ClangFallthroughTokens);
  1066. if (MacroName.empty())
  1067. MacroName = PreferClangAttr ? "[[clang::fallthrough]]" : "[[fallthrough]]";
  1068. return MacroName;
  1069. }
  1070. static void DiagnoseSwitchLabelsFallthrough(Sema &S, AnalysisDeclContext &AC,
  1071. bool PerFunction) {
  1072. // Only perform this analysis when using [[]] attributes. There is no good
  1073. // workflow for this warning when not using C++11. There is no good way to
  1074. // silence the warning (no attribute is available) unless we are using
  1075. // [[]] attributes. One could use pragmas to silence the warning, but as a
  1076. // general solution that is gross and not in the spirit of this warning.
  1077. //
  1078. // NOTE: This an intermediate solution. There are on-going discussions on
  1079. // how to properly support this warning outside of C++11 with an annotation.
  1080. if (!AC.getASTContext().getLangOpts().DoubleSquareBracketAttributes)
  1081. return;
  1082. FallthroughMapper FM(S);
  1083. FM.TraverseStmt(AC.getBody());
  1084. if (!FM.foundSwitchStatements())
  1085. return;
  1086. if (PerFunction && FM.getFallthroughStmts().empty())
  1087. return;
  1088. CFG *Cfg = AC.getCFG();
  1089. if (!Cfg)
  1090. return;
  1091. FM.fillReachableBlocks(Cfg);
  1092. for (const CFGBlock *B : llvm::reverse(*Cfg)) {
  1093. const Stmt *Label = B->getLabel();
  1094. if (!Label || !isa<SwitchCase>(Label))
  1095. continue;
  1096. int AnnotatedCnt;
  1097. bool IsTemplateInstantiation = false;
  1098. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(AC.getDecl()))
  1099. IsTemplateInstantiation = Function->isTemplateInstantiation();
  1100. if (!FM.checkFallThroughIntoBlock(*B, AnnotatedCnt,
  1101. IsTemplateInstantiation))
  1102. continue;
  1103. S.Diag(Label->getBeginLoc(),
  1104. PerFunction ? diag::warn_unannotated_fallthrough_per_function
  1105. : diag::warn_unannotated_fallthrough);
  1106. if (!AnnotatedCnt) {
  1107. SourceLocation L = Label->getBeginLoc();
  1108. if (L.isMacroID())
  1109. continue;
  1110. if (S.getLangOpts().CPlusPlus11) {
  1111. const Stmt *Term = B->getTerminator();
  1112. // Skip empty cases.
  1113. while (B->empty() && !Term && B->succ_size() == 1) {
  1114. B = *B->succ_begin();
  1115. Term = B->getTerminator();
  1116. }
  1117. if (!(B->empty() && Term && isa<BreakStmt>(Term))) {
  1118. Preprocessor &PP = S.getPreprocessor();
  1119. StringRef AnnotationSpelling = getFallthroughAttrSpelling(PP, L);
  1120. SmallString<64> TextToInsert(AnnotationSpelling);
  1121. TextToInsert += "; ";
  1122. S.Diag(L, diag::note_insert_fallthrough_fixit) <<
  1123. AnnotationSpelling <<
  1124. FixItHint::CreateInsertion(L, TextToInsert);
  1125. }
  1126. }
  1127. S.Diag(L, diag::note_insert_break_fixit) <<
  1128. FixItHint::CreateInsertion(L, "break; ");
  1129. }
  1130. }
  1131. for (const auto *F : FM.getFallthroughStmts())
  1132. S.Diag(F->getBeginLoc(), diag::err_fallthrough_attr_invalid_placement);
  1133. }
  1134. static bool isInLoop(const ASTContext &Ctx, const ParentMap &PM,
  1135. const Stmt *S) {
  1136. assert(S);
  1137. do {
  1138. switch (S->getStmtClass()) {
  1139. case Stmt::ForStmtClass:
  1140. case Stmt::WhileStmtClass:
  1141. case Stmt::CXXForRangeStmtClass:
  1142. case Stmt::ObjCForCollectionStmtClass:
  1143. return true;
  1144. case Stmt::DoStmtClass: {
  1145. const Expr *Cond = cast<DoStmt>(S)->getCond();
  1146. llvm::APSInt Val;
  1147. if (!Cond->EvaluateAsInt(Val, Ctx))
  1148. return true;
  1149. return Val.getBoolValue();
  1150. }
  1151. default:
  1152. break;
  1153. }
  1154. } while ((S = PM.getParent(S)));
  1155. return false;
  1156. }
  1157. static void diagnoseRepeatedUseOfWeak(Sema &S,
  1158. const sema::FunctionScopeInfo *CurFn,
  1159. const Decl *D,
  1160. const ParentMap &PM) {
  1161. typedef sema::FunctionScopeInfo::WeakObjectProfileTy WeakObjectProfileTy;
  1162. typedef sema::FunctionScopeInfo::WeakObjectUseMap WeakObjectUseMap;
  1163. typedef sema::FunctionScopeInfo::WeakUseVector WeakUseVector;
  1164. typedef std::pair<const Stmt *, WeakObjectUseMap::const_iterator>
  1165. StmtUsesPair;
  1166. ASTContext &Ctx = S.getASTContext();
  1167. const WeakObjectUseMap &WeakMap = CurFn->getWeakObjectUses();
  1168. // Extract all weak objects that are referenced more than once.
  1169. SmallVector<StmtUsesPair, 8> UsesByStmt;
  1170. for (WeakObjectUseMap::const_iterator I = WeakMap.begin(), E = WeakMap.end();
  1171. I != E; ++I) {
  1172. const WeakUseVector &Uses = I->second;
  1173. // Find the first read of the weak object.
  1174. WeakUseVector::const_iterator UI = Uses.begin(), UE = Uses.end();
  1175. for ( ; UI != UE; ++UI) {
  1176. if (UI->isUnsafe())
  1177. break;
  1178. }
  1179. // If there were only writes to this object, don't warn.
  1180. if (UI == UE)
  1181. continue;
  1182. // If there was only one read, followed by any number of writes, and the
  1183. // read is not within a loop, don't warn. Additionally, don't warn in a
  1184. // loop if the base object is a local variable -- local variables are often
  1185. // changed in loops.
  1186. if (UI == Uses.begin()) {
  1187. WeakUseVector::const_iterator UI2 = UI;
  1188. for (++UI2; UI2 != UE; ++UI2)
  1189. if (UI2->isUnsafe())
  1190. break;
  1191. if (UI2 == UE) {
  1192. if (!isInLoop(Ctx, PM, UI->getUseExpr()))
  1193. continue;
  1194. const WeakObjectProfileTy &Profile = I->first;
  1195. if (!Profile.isExactProfile())
  1196. continue;
  1197. const NamedDecl *Base = Profile.getBase();
  1198. if (!Base)
  1199. Base = Profile.getProperty();
  1200. assert(Base && "A profile always has a base or property.");
  1201. if (const VarDecl *BaseVar = dyn_cast<VarDecl>(Base))
  1202. if (BaseVar->hasLocalStorage() && !isa<ParmVarDecl>(Base))
  1203. continue;
  1204. }
  1205. }
  1206. UsesByStmt.push_back(StmtUsesPair(UI->getUseExpr(), I));
  1207. }
  1208. if (UsesByStmt.empty())
  1209. return;
  1210. // Sort by first use so that we emit the warnings in a deterministic order.
  1211. SourceManager &SM = S.getSourceManager();
  1212. llvm::sort(UsesByStmt,
  1213. [&SM](const StmtUsesPair &LHS, const StmtUsesPair &RHS) {
  1214. return SM.isBeforeInTranslationUnit(LHS.first->getBeginLoc(),
  1215. RHS.first->getBeginLoc());
  1216. });
  1217. // Classify the current code body for better warning text.
  1218. // This enum should stay in sync with the cases in
  1219. // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
  1220. // FIXME: Should we use a common classification enum and the same set of
  1221. // possibilities all throughout Sema?
  1222. enum {
  1223. Function,
  1224. Method,
  1225. Block,
  1226. Lambda
  1227. } FunctionKind;
  1228. if (isa<sema::BlockScopeInfo>(CurFn))
  1229. FunctionKind = Block;
  1230. else if (isa<sema::LambdaScopeInfo>(CurFn))
  1231. FunctionKind = Lambda;
  1232. else if (isa<ObjCMethodDecl>(D))
  1233. FunctionKind = Method;
  1234. else
  1235. FunctionKind = Function;
  1236. // Iterate through the sorted problems and emit warnings for each.
  1237. for (const auto &P : UsesByStmt) {
  1238. const Stmt *FirstRead = P.first;
  1239. const WeakObjectProfileTy &Key = P.second->first;
  1240. const WeakUseVector &Uses = P.second->second;
  1241. // For complicated expressions like 'a.b.c' and 'x.b.c', WeakObjectProfileTy
  1242. // may not contain enough information to determine that these are different
  1243. // properties. We can only be 100% sure of a repeated use in certain cases,
  1244. // and we adjust the diagnostic kind accordingly so that the less certain
  1245. // case can be turned off if it is too noisy.
  1246. unsigned DiagKind;
  1247. if (Key.isExactProfile())
  1248. DiagKind = diag::warn_arc_repeated_use_of_weak;
  1249. else
  1250. DiagKind = diag::warn_arc_possible_repeated_use_of_weak;
  1251. // Classify the weak object being accessed for better warning text.
  1252. // This enum should stay in sync with the cases in
  1253. // warn_arc_repeated_use_of_weak and warn_arc_possible_repeated_use_of_weak.
  1254. enum {
  1255. Variable,
  1256. Property,
  1257. ImplicitProperty,
  1258. Ivar
  1259. } ObjectKind;
  1260. const NamedDecl *KeyProp = Key.getProperty();
  1261. if (isa<VarDecl>(KeyProp))
  1262. ObjectKind = Variable;
  1263. else if (isa<ObjCPropertyDecl>(KeyProp))
  1264. ObjectKind = Property;
  1265. else if (isa<ObjCMethodDecl>(KeyProp))
  1266. ObjectKind = ImplicitProperty;
  1267. else if (isa<ObjCIvarDecl>(KeyProp))
  1268. ObjectKind = Ivar;
  1269. else
  1270. llvm_unreachable("Unexpected weak object kind!");
  1271. // Do not warn about IBOutlet weak property receivers being set to null
  1272. // since they are typically only used from the main thread.
  1273. if (const ObjCPropertyDecl *Prop = dyn_cast<ObjCPropertyDecl>(KeyProp))
  1274. if (Prop->hasAttr<IBOutletAttr>())
  1275. continue;
  1276. // Show the first time the object was read.
  1277. S.Diag(FirstRead->getBeginLoc(), DiagKind)
  1278. << int(ObjectKind) << KeyProp << int(FunctionKind)
  1279. << FirstRead->getSourceRange();
  1280. // Print all the other accesses as notes.
  1281. for (const auto &Use : Uses) {
  1282. if (Use.getUseExpr() == FirstRead)
  1283. continue;
  1284. S.Diag(Use.getUseExpr()->getBeginLoc(),
  1285. diag::note_arc_weak_also_accessed_here)
  1286. << Use.getUseExpr()->getSourceRange();
  1287. }
  1288. }
  1289. }
  1290. namespace {
  1291. class UninitValsDiagReporter : public UninitVariablesHandler {
  1292. Sema &S;
  1293. typedef SmallVector<UninitUse, 2> UsesVec;
  1294. typedef llvm::PointerIntPair<UsesVec *, 1, bool> MappedType;
  1295. // Prefer using MapVector to DenseMap, so that iteration order will be
  1296. // the same as insertion order. This is needed to obtain a deterministic
  1297. // order of diagnostics when calling flushDiagnostics().
  1298. typedef llvm::MapVector<const VarDecl *, MappedType> UsesMap;
  1299. UsesMap uses;
  1300. public:
  1301. UninitValsDiagReporter(Sema &S) : S(S) {}
  1302. ~UninitValsDiagReporter() override { flushDiagnostics(); }
  1303. MappedType &getUses(const VarDecl *vd) {
  1304. MappedType &V = uses[vd];
  1305. if (!V.getPointer())
  1306. V.setPointer(new UsesVec());
  1307. return V;
  1308. }
  1309. void handleUseOfUninitVariable(const VarDecl *vd,
  1310. const UninitUse &use) override {
  1311. getUses(vd).getPointer()->push_back(use);
  1312. }
  1313. void handleSelfInit(const VarDecl *vd) override {
  1314. getUses(vd).setInt(true);
  1315. }
  1316. void flushDiagnostics() {
  1317. for (const auto &P : uses) {
  1318. const VarDecl *vd = P.first;
  1319. const MappedType &V = P.second;
  1320. UsesVec *vec = V.getPointer();
  1321. bool hasSelfInit = V.getInt();
  1322. // Specially handle the case where we have uses of an uninitialized
  1323. // variable, but the root cause is an idiomatic self-init. We want
  1324. // to report the diagnostic at the self-init since that is the root cause.
  1325. if (!vec->empty() && hasSelfInit && hasAlwaysUninitializedUse(vec))
  1326. DiagnoseUninitializedUse(S, vd,
  1327. UninitUse(vd->getInit()->IgnoreParenCasts(),
  1328. /* isAlwaysUninit */ true),
  1329. /* alwaysReportSelfInit */ true);
  1330. else {
  1331. // Sort the uses by their SourceLocations. While not strictly
  1332. // guaranteed to produce them in line/column order, this will provide
  1333. // a stable ordering.
  1334. llvm::sort(vec->begin(), vec->end(),
  1335. [](const UninitUse &a, const UninitUse &b) {
  1336. // Prefer a more confident report over a less confident one.
  1337. if (a.getKind() != b.getKind())
  1338. return a.getKind() > b.getKind();
  1339. return a.getUser()->getBeginLoc() < b.getUser()->getBeginLoc();
  1340. });
  1341. for (const auto &U : *vec) {
  1342. // If we have self-init, downgrade all uses to 'may be uninitialized'.
  1343. UninitUse Use = hasSelfInit ? UninitUse(U.getUser(), false) : U;
  1344. if (DiagnoseUninitializedUse(S, vd, Use))
  1345. // Skip further diagnostics for this variable. We try to warn only
  1346. // on the first point at which a variable is used uninitialized.
  1347. break;
  1348. }
  1349. }
  1350. // Release the uses vector.
  1351. delete vec;
  1352. }
  1353. uses.clear();
  1354. }
  1355. private:
  1356. static bool hasAlwaysUninitializedUse(const UsesVec* vec) {
  1357. return std::any_of(vec->begin(), vec->end(), [](const UninitUse &U) {
  1358. return U.getKind() == UninitUse::Always ||
  1359. U.getKind() == UninitUse::AfterCall ||
  1360. U.getKind() == UninitUse::AfterDecl;
  1361. });
  1362. }
  1363. };
  1364. } // anonymous namespace
  1365. namespace clang {
  1366. namespace {
  1367. typedef SmallVector<PartialDiagnosticAt, 1> OptionalNotes;
  1368. typedef std::pair<PartialDiagnosticAt, OptionalNotes> DelayedDiag;
  1369. typedef std::list<DelayedDiag> DiagList;
  1370. struct SortDiagBySourceLocation {
  1371. SourceManager &SM;
  1372. SortDiagBySourceLocation(SourceManager &SM) : SM(SM) {}
  1373. bool operator()(const DelayedDiag &left, const DelayedDiag &right) {
  1374. // Although this call will be slow, this is only called when outputting
  1375. // multiple warnings.
  1376. return SM.isBeforeInTranslationUnit(left.first.first, right.first.first);
  1377. }
  1378. };
  1379. } // anonymous namespace
  1380. } // namespace clang
  1381. //===----------------------------------------------------------------------===//
  1382. // -Wthread-safety
  1383. //===----------------------------------------------------------------------===//
  1384. namespace clang {
  1385. namespace threadSafety {
  1386. namespace {
  1387. class ThreadSafetyReporter : public clang::threadSafety::ThreadSafetyHandler {
  1388. Sema &S;
  1389. DiagList Warnings;
  1390. SourceLocation FunLocation, FunEndLocation;
  1391. const FunctionDecl *CurrentFunction;
  1392. bool Verbose;
  1393. OptionalNotes getNotes() const {
  1394. if (Verbose && CurrentFunction) {
  1395. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
  1396. S.PDiag(diag::note_thread_warning_in_fun)
  1397. << CurrentFunction);
  1398. return OptionalNotes(1, FNote);
  1399. }
  1400. return OptionalNotes();
  1401. }
  1402. OptionalNotes getNotes(const PartialDiagnosticAt &Note) const {
  1403. OptionalNotes ONS(1, Note);
  1404. if (Verbose && CurrentFunction) {
  1405. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
  1406. S.PDiag(diag::note_thread_warning_in_fun)
  1407. << CurrentFunction);
  1408. ONS.push_back(std::move(FNote));
  1409. }
  1410. return ONS;
  1411. }
  1412. OptionalNotes getNotes(const PartialDiagnosticAt &Note1,
  1413. const PartialDiagnosticAt &Note2) const {
  1414. OptionalNotes ONS;
  1415. ONS.push_back(Note1);
  1416. ONS.push_back(Note2);
  1417. if (Verbose && CurrentFunction) {
  1418. PartialDiagnosticAt FNote(CurrentFunction->getBody()->getBeginLoc(),
  1419. S.PDiag(diag::note_thread_warning_in_fun)
  1420. << CurrentFunction);
  1421. ONS.push_back(std::move(FNote));
  1422. }
  1423. return ONS;
  1424. }
  1425. // Helper functions
  1426. void warnLockMismatch(unsigned DiagID, StringRef Kind, Name LockName,
  1427. SourceLocation Loc) {
  1428. // Gracefully handle rare cases when the analysis can't get a more
  1429. // precise source location.
  1430. if (!Loc.isValid())
  1431. Loc = FunLocation;
  1432. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind << LockName);
  1433. Warnings.emplace_back(std::move(Warning), getNotes());
  1434. }
  1435. public:
  1436. ThreadSafetyReporter(Sema &S, SourceLocation FL, SourceLocation FEL)
  1437. : S(S), FunLocation(FL), FunEndLocation(FEL),
  1438. CurrentFunction(nullptr), Verbose(false) {}
  1439. void setVerbose(bool b) { Verbose = b; }
  1440. /// Emit all buffered diagnostics in order of sourcelocation.
  1441. /// We need to output diagnostics produced while iterating through
  1442. /// the lockset in deterministic order, so this function orders diagnostics
  1443. /// and outputs them.
  1444. void emitDiagnostics() {
  1445. Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
  1446. for (const auto &Diag : Warnings) {
  1447. S.Diag(Diag.first.first, Diag.first.second);
  1448. for (const auto &Note : Diag.second)
  1449. S.Diag(Note.first, Note.second);
  1450. }
  1451. }
  1452. void handleInvalidLockExp(StringRef Kind, SourceLocation Loc) override {
  1453. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_cannot_resolve_lock)
  1454. << Loc);
  1455. Warnings.emplace_back(std::move(Warning), getNotes());
  1456. }
  1457. void handleUnmatchedUnlock(StringRef Kind, Name LockName,
  1458. SourceLocation Loc) override {
  1459. warnLockMismatch(diag::warn_unlock_but_no_lock, Kind, LockName, Loc);
  1460. }
  1461. void handleIncorrectUnlockKind(StringRef Kind, Name LockName,
  1462. LockKind Expected, LockKind Received,
  1463. SourceLocation Loc) override {
  1464. if (Loc.isInvalid())
  1465. Loc = FunLocation;
  1466. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_unlock_kind_mismatch)
  1467. << Kind << LockName << Received
  1468. << Expected);
  1469. Warnings.emplace_back(std::move(Warning), getNotes());
  1470. }
  1471. void handleDoubleLock(StringRef Kind, Name LockName, SourceLocation Loc) override {
  1472. warnLockMismatch(diag::warn_double_lock, Kind, LockName, Loc);
  1473. }
  1474. void handleMutexHeldEndOfScope(StringRef Kind, Name LockName,
  1475. SourceLocation LocLocked,
  1476. SourceLocation LocEndOfScope,
  1477. LockErrorKind LEK) override {
  1478. unsigned DiagID = 0;
  1479. switch (LEK) {
  1480. case LEK_LockedSomePredecessors:
  1481. DiagID = diag::warn_lock_some_predecessors;
  1482. break;
  1483. case LEK_LockedSomeLoopIterations:
  1484. DiagID = diag::warn_expecting_lock_held_on_loop;
  1485. break;
  1486. case LEK_LockedAtEndOfFunction:
  1487. DiagID = diag::warn_no_unlock;
  1488. break;
  1489. case LEK_NotLockedAtEndOfFunction:
  1490. DiagID = diag::warn_expecting_locked;
  1491. break;
  1492. }
  1493. if (LocEndOfScope.isInvalid())
  1494. LocEndOfScope = FunEndLocation;
  1495. PartialDiagnosticAt Warning(LocEndOfScope, S.PDiag(DiagID) << Kind
  1496. << LockName);
  1497. if (LocLocked.isValid()) {
  1498. PartialDiagnosticAt Note(LocLocked, S.PDiag(diag::note_locked_here)
  1499. << Kind);
  1500. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1501. return;
  1502. }
  1503. Warnings.emplace_back(std::move(Warning), getNotes());
  1504. }
  1505. void handleExclusiveAndShared(StringRef Kind, Name LockName,
  1506. SourceLocation Loc1,
  1507. SourceLocation Loc2) override {
  1508. PartialDiagnosticAt Warning(Loc1,
  1509. S.PDiag(diag::warn_lock_exclusive_and_shared)
  1510. << Kind << LockName);
  1511. PartialDiagnosticAt Note(Loc2, S.PDiag(diag::note_lock_exclusive_and_shared)
  1512. << Kind << LockName);
  1513. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1514. }
  1515. void handleNoMutexHeld(StringRef Kind, const NamedDecl *D,
  1516. ProtectedOperationKind POK, AccessKind AK,
  1517. SourceLocation Loc) override {
  1518. assert((POK == POK_VarAccess || POK == POK_VarDereference) &&
  1519. "Only works for variables");
  1520. unsigned DiagID = POK == POK_VarAccess?
  1521. diag::warn_variable_requires_any_lock:
  1522. diag::warn_var_deref_requires_any_lock;
  1523. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID)
  1524. << D << getLockKindFromAccessKind(AK));
  1525. Warnings.emplace_back(std::move(Warning), getNotes());
  1526. }
  1527. void handleMutexNotHeld(StringRef Kind, const NamedDecl *D,
  1528. ProtectedOperationKind POK, Name LockName,
  1529. LockKind LK, SourceLocation Loc,
  1530. Name *PossibleMatch) override {
  1531. unsigned DiagID = 0;
  1532. if (PossibleMatch) {
  1533. switch (POK) {
  1534. case POK_VarAccess:
  1535. DiagID = diag::warn_variable_requires_lock_precise;
  1536. break;
  1537. case POK_VarDereference:
  1538. DiagID = diag::warn_var_deref_requires_lock_precise;
  1539. break;
  1540. case POK_FunctionCall:
  1541. DiagID = diag::warn_fun_requires_lock_precise;
  1542. break;
  1543. case POK_PassByRef:
  1544. DiagID = diag::warn_guarded_pass_by_reference;
  1545. break;
  1546. case POK_PtPassByRef:
  1547. DiagID = diag::warn_pt_guarded_pass_by_reference;
  1548. break;
  1549. }
  1550. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
  1551. << D
  1552. << LockName << LK);
  1553. PartialDiagnosticAt Note(Loc, S.PDiag(diag::note_found_mutex_near_match)
  1554. << *PossibleMatch);
  1555. if (Verbose && POK == POK_VarAccess) {
  1556. PartialDiagnosticAt VNote(D->getLocation(),
  1557. S.PDiag(diag::note_guarded_by_declared_here)
  1558. << D->getNameAsString());
  1559. Warnings.emplace_back(std::move(Warning), getNotes(Note, VNote));
  1560. } else
  1561. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1562. } else {
  1563. switch (POK) {
  1564. case POK_VarAccess:
  1565. DiagID = diag::warn_variable_requires_lock;
  1566. break;
  1567. case POK_VarDereference:
  1568. DiagID = diag::warn_var_deref_requires_lock;
  1569. break;
  1570. case POK_FunctionCall:
  1571. DiagID = diag::warn_fun_requires_lock;
  1572. break;
  1573. case POK_PassByRef:
  1574. DiagID = diag::warn_guarded_pass_by_reference;
  1575. break;
  1576. case POK_PtPassByRef:
  1577. DiagID = diag::warn_pt_guarded_pass_by_reference;
  1578. break;
  1579. }
  1580. PartialDiagnosticAt Warning(Loc, S.PDiag(DiagID) << Kind
  1581. << D
  1582. << LockName << LK);
  1583. if (Verbose && POK == POK_VarAccess) {
  1584. PartialDiagnosticAt Note(D->getLocation(),
  1585. S.PDiag(diag::note_guarded_by_declared_here));
  1586. Warnings.emplace_back(std::move(Warning), getNotes(Note));
  1587. } else
  1588. Warnings.emplace_back(std::move(Warning), getNotes());
  1589. }
  1590. }
  1591. void handleNegativeNotHeld(StringRef Kind, Name LockName, Name Neg,
  1592. SourceLocation Loc) override {
  1593. PartialDiagnosticAt Warning(Loc,
  1594. S.PDiag(diag::warn_acquire_requires_negative_cap)
  1595. << Kind << LockName << Neg);
  1596. Warnings.emplace_back(std::move(Warning), getNotes());
  1597. }
  1598. void handleFunExcludesLock(StringRef Kind, Name FunName, Name LockName,
  1599. SourceLocation Loc) override {
  1600. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_fun_excludes_mutex)
  1601. << Kind << FunName << LockName);
  1602. Warnings.emplace_back(std::move(Warning), getNotes());
  1603. }
  1604. void handleLockAcquiredBefore(StringRef Kind, Name L1Name, Name L2Name,
  1605. SourceLocation Loc) override {
  1606. PartialDiagnosticAt Warning(Loc,
  1607. S.PDiag(diag::warn_acquired_before) << Kind << L1Name << L2Name);
  1608. Warnings.emplace_back(std::move(Warning), getNotes());
  1609. }
  1610. void handleBeforeAfterCycle(Name L1Name, SourceLocation Loc) override {
  1611. PartialDiagnosticAt Warning(Loc,
  1612. S.PDiag(diag::warn_acquired_before_after_cycle) << L1Name);
  1613. Warnings.emplace_back(std::move(Warning), getNotes());
  1614. }
  1615. void enterFunction(const FunctionDecl* FD) override {
  1616. CurrentFunction = FD;
  1617. }
  1618. void leaveFunction(const FunctionDecl* FD) override {
  1619. CurrentFunction = nullptr;
  1620. }
  1621. };
  1622. } // anonymous namespace
  1623. } // namespace threadSafety
  1624. } // namespace clang
  1625. //===----------------------------------------------------------------------===//
  1626. // -Wconsumed
  1627. //===----------------------------------------------------------------------===//
  1628. namespace clang {
  1629. namespace consumed {
  1630. namespace {
  1631. class ConsumedWarningsHandler : public ConsumedWarningsHandlerBase {
  1632. Sema &S;
  1633. DiagList Warnings;
  1634. public:
  1635. ConsumedWarningsHandler(Sema &S) : S(S) {}
  1636. void emitDiagnostics() override {
  1637. Warnings.sort(SortDiagBySourceLocation(S.getSourceManager()));
  1638. for (const auto &Diag : Warnings) {
  1639. S.Diag(Diag.first.first, Diag.first.second);
  1640. for (const auto &Note : Diag.second)
  1641. S.Diag(Note.first, Note.second);
  1642. }
  1643. }
  1644. void warnLoopStateMismatch(SourceLocation Loc,
  1645. StringRef VariableName) override {
  1646. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_loop_state_mismatch) <<
  1647. VariableName);
  1648. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1649. }
  1650. void warnParamReturnTypestateMismatch(SourceLocation Loc,
  1651. StringRef VariableName,
  1652. StringRef ExpectedState,
  1653. StringRef ObservedState) override {
  1654. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1655. diag::warn_param_return_typestate_mismatch) << VariableName <<
  1656. ExpectedState << ObservedState);
  1657. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1658. }
  1659. void warnParamTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
  1660. StringRef ObservedState) override {
  1661. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1662. diag::warn_param_typestate_mismatch) << ExpectedState << ObservedState);
  1663. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1664. }
  1665. void warnReturnTypestateForUnconsumableType(SourceLocation Loc,
  1666. StringRef TypeName) override {
  1667. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1668. diag::warn_return_typestate_for_unconsumable_type) << TypeName);
  1669. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1670. }
  1671. void warnReturnTypestateMismatch(SourceLocation Loc, StringRef ExpectedState,
  1672. StringRef ObservedState) override {
  1673. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1674. diag::warn_return_typestate_mismatch) << ExpectedState << ObservedState);
  1675. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1676. }
  1677. void warnUseOfTempInInvalidState(StringRef MethodName, StringRef State,
  1678. SourceLocation Loc) override {
  1679. PartialDiagnosticAt Warning(Loc, S.PDiag(
  1680. diag::warn_use_of_temp_in_invalid_state) << MethodName << State);
  1681. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1682. }
  1683. void warnUseInInvalidState(StringRef MethodName, StringRef VariableName,
  1684. StringRef State, SourceLocation Loc) override {
  1685. PartialDiagnosticAt Warning(Loc, S.PDiag(diag::warn_use_in_invalid_state) <<
  1686. MethodName << VariableName << State);
  1687. Warnings.emplace_back(std::move(Warning), OptionalNotes());
  1688. }
  1689. };
  1690. } // anonymous namespace
  1691. } // namespace consumed
  1692. } // namespace clang
  1693. //===----------------------------------------------------------------------===//
  1694. // AnalysisBasedWarnings - Worker object used by Sema to execute analysis-based
  1695. // warnings on a function, method, or block.
  1696. //===----------------------------------------------------------------------===//
  1697. clang::sema::AnalysisBasedWarnings::Policy::Policy() {
  1698. enableCheckFallThrough = 1;
  1699. enableCheckUnreachable = 0;
  1700. enableThreadSafetyAnalysis = 0;
  1701. enableConsumedAnalysis = 0;
  1702. }
  1703. static unsigned isEnabled(DiagnosticsEngine &D, unsigned diag) {
  1704. return (unsigned)!D.isIgnored(diag, SourceLocation());
  1705. }
  1706. clang::sema::AnalysisBasedWarnings::AnalysisBasedWarnings(Sema &s)
  1707. : S(s),
  1708. NumFunctionsAnalyzed(0),
  1709. NumFunctionsWithBadCFGs(0),
  1710. NumCFGBlocks(0),
  1711. MaxCFGBlocksPerFunction(0),
  1712. NumUninitAnalysisFunctions(0),
  1713. NumUninitAnalysisVariables(0),
  1714. MaxUninitAnalysisVariablesPerFunction(0),
  1715. NumUninitAnalysisBlockVisits(0),
  1716. MaxUninitAnalysisBlockVisitsPerFunction(0) {
  1717. using namespace diag;
  1718. DiagnosticsEngine &D = S.getDiagnostics();
  1719. DefaultPolicy.enableCheckUnreachable =
  1720. isEnabled(D, warn_unreachable) ||
  1721. isEnabled(D, warn_unreachable_break) ||
  1722. isEnabled(D, warn_unreachable_return) ||
  1723. isEnabled(D, warn_unreachable_loop_increment);
  1724. DefaultPolicy.enableThreadSafetyAnalysis =
  1725. isEnabled(D, warn_double_lock);
  1726. DefaultPolicy.enableConsumedAnalysis =
  1727. isEnabled(D, warn_use_in_invalid_state);
  1728. }
  1729. static void flushDiagnostics(Sema &S, const sema::FunctionScopeInfo *fscope) {
  1730. for (const auto &D : fscope->PossiblyUnreachableDiags)
  1731. S.Diag(D.Loc, D.PD);
  1732. }
  1733. void clang::sema::
  1734. AnalysisBasedWarnings::IssueWarnings(sema::AnalysisBasedWarnings::Policy P,
  1735. sema::FunctionScopeInfo *fscope,
  1736. const Decl *D, const BlockExpr *blkExpr) {
  1737. // We avoid doing analysis-based warnings when there are errors for
  1738. // two reasons:
  1739. // (1) The CFGs often can't be constructed (if the body is invalid), so
  1740. // don't bother trying.
  1741. // (2) The code already has problems; running the analysis just takes more
  1742. // time.
  1743. DiagnosticsEngine &Diags = S.getDiagnostics();
  1744. // Do not do any analysis if we are going to just ignore them.
  1745. if (Diags.getIgnoreAllWarnings() ||
  1746. (Diags.getSuppressSystemWarnings() &&
  1747. S.SourceMgr.isInSystemHeader(D->getLocation())))
  1748. return;
  1749. // For code in dependent contexts, we'll do this at instantiation time.
  1750. if (cast<DeclContext>(D)->isDependentContext())
  1751. return;
  1752. if (Diags.hasUncompilableErrorOccurred()) {
  1753. // Flush out any possibly unreachable diagnostics.
  1754. flushDiagnostics(S, fscope);
  1755. return;
  1756. }
  1757. const Stmt *Body = D->getBody();
  1758. assert(Body);
  1759. // Construct the analysis context with the specified CFG build options.
  1760. AnalysisDeclContext AC(/* AnalysisDeclContextManager */ nullptr, D);
  1761. // Don't generate EH edges for CallExprs as we'd like to avoid the n^2
  1762. // explosion for destructors that can result and the compile time hit.
  1763. AC.getCFGBuildOptions().PruneTriviallyFalseEdges = true;
  1764. AC.getCFGBuildOptions().AddEHEdges = false;
  1765. AC.getCFGBuildOptions().AddInitializers = true;
  1766. AC.getCFGBuildOptions().AddImplicitDtors = true;
  1767. AC.getCFGBuildOptions().AddTemporaryDtors = true;
  1768. AC.getCFGBuildOptions().AddCXXNewAllocator = false;
  1769. AC.getCFGBuildOptions().AddCXXDefaultInitExprInCtors = true;
  1770. // Force that certain expressions appear as CFGElements in the CFG. This
  1771. // is used to speed up various analyses.
  1772. // FIXME: This isn't the right factoring. This is here for initial
  1773. // prototyping, but we need a way for analyses to say what expressions they
  1774. // expect to always be CFGElements and then fill in the BuildOptions
  1775. // appropriately. This is essentially a layering violation.
  1776. if (P.enableCheckUnreachable || P.enableThreadSafetyAnalysis ||
  1777. P.enableConsumedAnalysis) {
  1778. // Unreachable code analysis and thread safety require a linearized CFG.
  1779. AC.getCFGBuildOptions().setAllAlwaysAdd();
  1780. }
  1781. else {
  1782. AC.getCFGBuildOptions()
  1783. .setAlwaysAdd(Stmt::BinaryOperatorClass)
  1784. .setAlwaysAdd(Stmt::CompoundAssignOperatorClass)
  1785. .setAlwaysAdd(Stmt::BlockExprClass)
  1786. .setAlwaysAdd(Stmt::CStyleCastExprClass)
  1787. .setAlwaysAdd(Stmt::DeclRefExprClass)
  1788. .setAlwaysAdd(Stmt::ImplicitCastExprClass)
  1789. .setAlwaysAdd(Stmt::UnaryOperatorClass)
  1790. .setAlwaysAdd(Stmt::AttributedStmtClass);
  1791. }
  1792. // Install the logical handler for -Wtautological-overlap-compare
  1793. llvm::Optional<LogicalErrorHandler> LEH;
  1794. if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
  1795. D->getBeginLoc())) {
  1796. LEH.emplace(S);
  1797. AC.getCFGBuildOptions().Observer = &*LEH;
  1798. }
  1799. // Emit delayed diagnostics.
  1800. if (!fscope->PossiblyUnreachableDiags.empty()) {
  1801. bool analyzed = false;
  1802. // Register the expressions with the CFGBuilder.
  1803. for (const auto &D : fscope->PossiblyUnreachableDiags) {
  1804. if (D.stmt)
  1805. AC.registerForcedBlockExpression(D.stmt);
  1806. }
  1807. if (AC.getCFG()) {
  1808. analyzed = true;
  1809. for (const auto &D : fscope->PossiblyUnreachableDiags) {
  1810. bool processed = false;
  1811. if (D.stmt) {
  1812. const CFGBlock *block = AC.getBlockForRegisteredExpression(D.stmt);
  1813. CFGReverseBlockReachabilityAnalysis *cra =
  1814. AC.getCFGReachablityAnalysis();
  1815. // FIXME: We should be able to assert that block is non-null, but
  1816. // the CFG analysis can skip potentially-evaluated expressions in
  1817. // edge cases; see test/Sema/vla-2.c.
  1818. if (block && cra) {
  1819. // Can this block be reached from the entrance?
  1820. if (cra->isReachable(&AC.getCFG()->getEntry(), block))
  1821. S.Diag(D.Loc, D.PD);
  1822. processed = true;
  1823. }
  1824. }
  1825. if (!processed) {
  1826. // Emit the warning anyway if we cannot map to a basic block.
  1827. S.Diag(D.Loc, D.PD);
  1828. }
  1829. }
  1830. }
  1831. if (!analyzed)
  1832. flushDiagnostics(S, fscope);
  1833. }
  1834. // Warning: check missing 'return'
  1835. if (P.enableCheckFallThrough) {
  1836. const CheckFallThroughDiagnostics &CD =
  1837. (isa<BlockDecl>(D)
  1838. ? CheckFallThroughDiagnostics::MakeForBlock()
  1839. : (isa<CXXMethodDecl>(D) &&
  1840. cast<CXXMethodDecl>(D)->getOverloadedOperator() == OO_Call &&
  1841. cast<CXXMethodDecl>(D)->getParent()->isLambda())
  1842. ? CheckFallThroughDiagnostics::MakeForLambda()
  1843. : (fscope->isCoroutine()
  1844. ? CheckFallThroughDiagnostics::MakeForCoroutine(D)
  1845. : CheckFallThroughDiagnostics::MakeForFunction(D)));
  1846. CheckFallThroughForBody(S, D, Body, blkExpr, CD, AC, fscope);
  1847. }
  1848. // Warning: check for unreachable code
  1849. if (P.enableCheckUnreachable) {
  1850. // Only check for unreachable code on non-template instantiations.
  1851. // Different template instantiations can effectively change the control-flow
  1852. // and it is very difficult to prove that a snippet of code in a template
  1853. // is unreachable for all instantiations.
  1854. bool isTemplateInstantiation = false;
  1855. if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D))
  1856. isTemplateInstantiation = Function->isTemplateInstantiation();
  1857. if (!isTemplateInstantiation)
  1858. CheckUnreachable(S, AC);
  1859. }
  1860. // Check for thread safety violations
  1861. if (P.enableThreadSafetyAnalysis) {
  1862. SourceLocation FL = AC.getDecl()->getLocation();
  1863. SourceLocation FEL = AC.getDecl()->getEndLoc();
  1864. threadSafety::ThreadSafetyReporter Reporter(S, FL, FEL);
  1865. if (!Diags.isIgnored(diag::warn_thread_safety_beta, D->getBeginLoc()))
  1866. Reporter.setIssueBetaWarnings(true);
  1867. if (!Diags.isIgnored(diag::warn_thread_safety_verbose, D->getBeginLoc()))
  1868. Reporter.setVerbose(true);
  1869. threadSafety::runThreadSafetyAnalysis(AC, Reporter,
  1870. &S.ThreadSafetyDeclCache);
  1871. Reporter.emitDiagnostics();
  1872. }
  1873. // Check for violations of consumed properties.
  1874. if (P.enableConsumedAnalysis) {
  1875. consumed::ConsumedWarningsHandler WarningHandler(S);
  1876. consumed::ConsumedAnalyzer Analyzer(WarningHandler);
  1877. Analyzer.run(AC);
  1878. }
  1879. if (!Diags.isIgnored(diag::warn_uninit_var, D->getBeginLoc()) ||
  1880. !Diags.isIgnored(diag::warn_sometimes_uninit_var, D->getBeginLoc()) ||
  1881. !Diags.isIgnored(diag::warn_maybe_uninit_var, D->getBeginLoc())) {
  1882. if (CFG *cfg = AC.getCFG()) {
  1883. UninitValsDiagReporter reporter(S);
  1884. UninitVariablesAnalysisStats stats;
  1885. std::memset(&stats, 0, sizeof(UninitVariablesAnalysisStats));
  1886. runUninitializedVariablesAnalysis(*cast<DeclContext>(D), *cfg, AC,
  1887. reporter, stats);
  1888. if (S.CollectStats && stats.NumVariablesAnalyzed > 0) {
  1889. ++NumUninitAnalysisFunctions;
  1890. NumUninitAnalysisVariables += stats.NumVariablesAnalyzed;
  1891. NumUninitAnalysisBlockVisits += stats.NumBlockVisits;
  1892. MaxUninitAnalysisVariablesPerFunction =
  1893. std::max(MaxUninitAnalysisVariablesPerFunction,
  1894. stats.NumVariablesAnalyzed);
  1895. MaxUninitAnalysisBlockVisitsPerFunction =
  1896. std::max(MaxUninitAnalysisBlockVisitsPerFunction,
  1897. stats.NumBlockVisits);
  1898. }
  1899. }
  1900. }
  1901. bool FallThroughDiagFull =
  1902. !Diags.isIgnored(diag::warn_unannotated_fallthrough, D->getBeginLoc());
  1903. bool FallThroughDiagPerFunction = !Diags.isIgnored(
  1904. diag::warn_unannotated_fallthrough_per_function, D->getBeginLoc());
  1905. if (FallThroughDiagFull || FallThroughDiagPerFunction ||
  1906. fscope->HasFallthroughStmt) {
  1907. DiagnoseSwitchLabelsFallthrough(S, AC, !FallThroughDiagFull);
  1908. }
  1909. if (S.getLangOpts().ObjCWeak &&
  1910. !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, D->getBeginLoc()))
  1911. diagnoseRepeatedUseOfWeak(S, fscope, D, AC.getParentMap());
  1912. // Check for infinite self-recursion in functions
  1913. if (!Diags.isIgnored(diag::warn_infinite_recursive_function,
  1914. D->getBeginLoc())) {
  1915. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
  1916. checkRecursiveFunction(S, FD, Body, AC);
  1917. }
  1918. }
  1919. // Check for throw out of non-throwing function.
  1920. if (!Diags.isIgnored(diag::warn_throw_in_noexcept_func, D->getBeginLoc()))
  1921. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
  1922. if (S.getLangOpts().CPlusPlus && isNoexcept(FD))
  1923. checkThrowInNonThrowingFunc(S, FD, AC);
  1924. // If none of the previous checks caused a CFG build, trigger one here
  1925. // for -Wtautological-overlap-compare
  1926. if (!Diags.isIgnored(diag::warn_tautological_overlap_comparison,
  1927. D->getBeginLoc())) {
  1928. AC.getCFG();
  1929. }
  1930. // Collect statistics about the CFG if it was built.
  1931. if (S.CollectStats && AC.isCFGBuilt()) {
  1932. ++NumFunctionsAnalyzed;
  1933. if (CFG *cfg = AC.getCFG()) {
  1934. // If we successfully built a CFG for this context, record some more
  1935. // detail information about it.
  1936. NumCFGBlocks += cfg->getNumBlockIDs();
  1937. MaxCFGBlocksPerFunction = std::max(MaxCFGBlocksPerFunction,
  1938. cfg->getNumBlockIDs());
  1939. } else {
  1940. ++NumFunctionsWithBadCFGs;
  1941. }
  1942. }
  1943. }
  1944. void clang::sema::AnalysisBasedWarnings::PrintStats() const {
  1945. llvm::errs() << "\n*** Analysis Based Warnings Stats:\n";
  1946. unsigned NumCFGsBuilt = NumFunctionsAnalyzed - NumFunctionsWithBadCFGs;
  1947. unsigned AvgCFGBlocksPerFunction =
  1948. !NumCFGsBuilt ? 0 : NumCFGBlocks/NumCFGsBuilt;
  1949. llvm::errs() << NumFunctionsAnalyzed << " functions analyzed ("
  1950. << NumFunctionsWithBadCFGs << " w/o CFGs).\n"
  1951. << " " << NumCFGBlocks << " CFG blocks built.\n"
  1952. << " " << AvgCFGBlocksPerFunction
  1953. << " average CFG blocks per function.\n"
  1954. << " " << MaxCFGBlocksPerFunction
  1955. << " max CFG blocks per function.\n";
  1956. unsigned AvgUninitVariablesPerFunction = !NumUninitAnalysisFunctions ? 0
  1957. : NumUninitAnalysisVariables/NumUninitAnalysisFunctions;
  1958. unsigned AvgUninitBlockVisitsPerFunction = !NumUninitAnalysisFunctions ? 0
  1959. : NumUninitAnalysisBlockVisits/NumUninitAnalysisFunctions;
  1960. llvm::errs() << NumUninitAnalysisFunctions
  1961. << " functions analyzed for uninitialiazed variables\n"
  1962. << " " << NumUninitAnalysisVariables << " variables analyzed.\n"
  1963. << " " << AvgUninitVariablesPerFunction
  1964. << " average variables per function.\n"
  1965. << " " << MaxUninitAnalysisVariablesPerFunction
  1966. << " max variables per function.\n"
  1967. << " " << NumUninitAnalysisBlockVisits << " block visits.\n"
  1968. << " " << AvgUninitBlockVisitsPerFunction
  1969. << " average block visits per function.\n"
  1970. << " " << MaxUninitAnalysisBlockVisitsPerFunction
  1971. << " max block visits per function.\n";
  1972. }