BugReporter.cpp 105 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142
  1. //===- BugReporter.cpp - Generate PathDiagnostics for bugs ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines BugReporter, a utility class for generating
  10. // PathDiagnostics.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
  14. #include "clang/AST/Decl.h"
  15. #include "clang/AST/DeclBase.h"
  16. #include "clang/AST/DeclObjC.h"
  17. #include "clang/AST/Expr.h"
  18. #include "clang/AST/ExprCXX.h"
  19. #include "clang/AST/ParentMap.h"
  20. #include "clang/AST/Stmt.h"
  21. #include "clang/AST/StmtCXX.h"
  22. #include "clang/AST/StmtObjC.h"
  23. #include "clang/Analysis/AnalysisDeclContext.h"
  24. #include "clang/Analysis/CFG.h"
  25. #include "clang/Analysis/CFGStmtMap.h"
  26. #include "clang/Analysis/ProgramPoint.h"
  27. #include "clang/Basic/LLVM.h"
  28. #include "clang/Basic/SourceLocation.h"
  29. #include "clang/Basic/SourceManager.h"
  30. #include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
  31. #include "clang/StaticAnalyzer/Core/BugReporter/BugReporterVisitors.h"
  32. #include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
  33. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  34. #include "clang/StaticAnalyzer/Core/Checker.h"
  35. #include "clang/StaticAnalyzer/Core/CheckerManager.h"
  36. #include "clang/StaticAnalyzer/Core/PathSensitive/ExplodedGraph.h"
  37. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  38. #include "clang/StaticAnalyzer/Core/PathSensitive/MemRegion.h"
  39. #include "clang/StaticAnalyzer/Core/PathSensitive/ProgramState.h"
  40. #include "clang/StaticAnalyzer/Core/PathSensitive/SVals.h"
  41. #include "clang/StaticAnalyzer/Core/PathSensitive/SymbolManager.h"
  42. #include "llvm/ADT/ArrayRef.h"
  43. #include "llvm/ADT/DenseMap.h"
  44. #include "llvm/ADT/DenseSet.h"
  45. #include "llvm/ADT/FoldingSet.h"
  46. #include "llvm/ADT/None.h"
  47. #include "llvm/ADT/Optional.h"
  48. #include "llvm/ADT/STLExtras.h"
  49. #include "llvm/ADT/SmallPtrSet.h"
  50. #include "llvm/ADT/SmallString.h"
  51. #include "llvm/ADT/SmallVector.h"
  52. #include "llvm/ADT/Statistic.h"
  53. #include "llvm/ADT/StringRef.h"
  54. #include "llvm/ADT/iterator_range.h"
  55. #include "llvm/Support/Casting.h"
  56. #include "llvm/Support/Compiler.h"
  57. #include "llvm/Support/ErrorHandling.h"
  58. #include "llvm/Support/MemoryBuffer.h"
  59. #include "llvm/Support/raw_ostream.h"
  60. #include <algorithm>
  61. #include <cassert>
  62. #include <cstddef>
  63. #include <iterator>
  64. #include <memory>
  65. #include <queue>
  66. #include <string>
  67. #include <tuple>
  68. #include <utility>
  69. #include <vector>
  70. using namespace clang;
  71. using namespace ento;
  72. #define DEBUG_TYPE "BugReporter"
  73. STATISTIC(MaxBugClassSize,
  74. "The maximum number of bug reports in the same equivalence class");
  75. STATISTIC(MaxValidBugClassSize,
  76. "The maximum number of bug reports in the same equivalence class "
  77. "where at least one report is valid (not suppressed)");
  78. BugReporterVisitor::~BugReporterVisitor() = default;
  79. void BugReporterContext::anchor() {}
  80. //===----------------------------------------------------------------------===//
  81. // Helper routines for walking the ExplodedGraph and fetching statements.
  82. //===----------------------------------------------------------------------===//
  83. static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
  84. for (N = N->getFirstPred(); N; N = N->getFirstPred())
  85. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  86. return S;
  87. return nullptr;
  88. }
  89. static inline const Stmt*
  90. GetCurrentOrPreviousStmt(const ExplodedNode *N) {
  91. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  92. return S;
  93. return GetPreviousStmt(N);
  94. }
  95. //===----------------------------------------------------------------------===//
  96. // Diagnostic cleanup.
  97. //===----------------------------------------------------------------------===//
  98. static PathDiagnosticEventPiece *
  99. eventsDescribeSameCondition(PathDiagnosticEventPiece *X,
  100. PathDiagnosticEventPiece *Y) {
  101. // Prefer diagnostics that come from ConditionBRVisitor over
  102. // those that came from TrackConstraintBRVisitor,
  103. // unless the one from ConditionBRVisitor is
  104. // its generic fallback diagnostic.
  105. const void *tagPreferred = ConditionBRVisitor::getTag();
  106. const void *tagLesser = TrackConstraintBRVisitor::getTag();
  107. if (X->getLocation() != Y->getLocation())
  108. return nullptr;
  109. if (X->getTag() == tagPreferred && Y->getTag() == tagLesser)
  110. return ConditionBRVisitor::isPieceMessageGeneric(X) ? Y : X;
  111. if (Y->getTag() == tagPreferred && X->getTag() == tagLesser)
  112. return ConditionBRVisitor::isPieceMessageGeneric(Y) ? X : Y;
  113. return nullptr;
  114. }
  115. /// An optimization pass over PathPieces that removes redundant diagnostics
  116. /// generated by both ConditionBRVisitor and TrackConstraintBRVisitor. Both
  117. /// BugReporterVisitors use different methods to generate diagnostics, with
  118. /// one capable of emitting diagnostics in some cases but not in others. This
  119. /// can lead to redundant diagnostic pieces at the same point in a path.
  120. static void removeRedundantMsgs(PathPieces &path) {
  121. unsigned N = path.size();
  122. if (N < 2)
  123. return;
  124. // NOTE: this loop intentionally is not using an iterator. Instead, we
  125. // are streaming the path and modifying it in place. This is done by
  126. // grabbing the front, processing it, and if we decide to keep it append
  127. // it to the end of the path. The entire path is processed in this way.
  128. for (unsigned i = 0; i < N; ++i) {
  129. auto piece = std::move(path.front());
  130. path.pop_front();
  131. switch (piece->getKind()) {
  132. case PathDiagnosticPiece::Call:
  133. removeRedundantMsgs(cast<PathDiagnosticCallPiece>(*piece).path);
  134. break;
  135. case PathDiagnosticPiece::Macro:
  136. removeRedundantMsgs(cast<PathDiagnosticMacroPiece>(*piece).subPieces);
  137. break;
  138. case PathDiagnosticPiece::ControlFlow:
  139. break;
  140. case PathDiagnosticPiece::Event: {
  141. if (i == N-1)
  142. break;
  143. if (auto *nextEvent =
  144. dyn_cast<PathDiagnosticEventPiece>(path.front().get())) {
  145. auto *event = cast<PathDiagnosticEventPiece>(piece.get());
  146. // Check to see if we should keep one of the two pieces. If we
  147. // come up with a preference, record which piece to keep, and consume
  148. // another piece from the path.
  149. if (auto *pieceToKeep =
  150. eventsDescribeSameCondition(event, nextEvent)) {
  151. piece = std::move(pieceToKeep == event ? piece : path.front());
  152. path.pop_front();
  153. ++i;
  154. }
  155. }
  156. break;
  157. }
  158. case PathDiagnosticPiece::Note:
  159. break;
  160. }
  161. path.push_back(std::move(piece));
  162. }
  163. }
  164. /// A map from PathDiagnosticPiece to the LocationContext of the inlined
  165. /// function call it represents.
  166. using LocationContextMap =
  167. llvm::DenseMap<const PathPieces *, const LocationContext *>;
  168. /// Recursively scan through a path and prune out calls and macros pieces
  169. /// that aren't needed. Return true if afterwards the path contains
  170. /// "interesting stuff" which means it shouldn't be pruned from the parent path.
  171. static bool removeUnneededCalls(PathPieces &pieces, BugReport *R,
  172. LocationContextMap &LCM,
  173. bool IsInteresting = false) {
  174. bool containsSomethingInteresting = IsInteresting;
  175. const unsigned N = pieces.size();
  176. for (unsigned i = 0 ; i < N ; ++i) {
  177. // Remove the front piece from the path. If it is still something we
  178. // want to keep once we are done, we will push it back on the end.
  179. auto piece = std::move(pieces.front());
  180. pieces.pop_front();
  181. switch (piece->getKind()) {
  182. case PathDiagnosticPiece::Call: {
  183. auto &call = cast<PathDiagnosticCallPiece>(*piece);
  184. // Check if the location context is interesting.
  185. assert(LCM.count(&call.path));
  186. if (!removeUnneededCalls(call.path, R, LCM,
  187. R->isInteresting(LCM[&call.path])))
  188. continue;
  189. containsSomethingInteresting = true;
  190. break;
  191. }
  192. case PathDiagnosticPiece::Macro: {
  193. auto &macro = cast<PathDiagnosticMacroPiece>(*piece);
  194. if (!removeUnneededCalls(macro.subPieces, R, LCM, IsInteresting))
  195. continue;
  196. containsSomethingInteresting = true;
  197. break;
  198. }
  199. case PathDiagnosticPiece::Event: {
  200. auto &event = cast<PathDiagnosticEventPiece>(*piece);
  201. // We never throw away an event, but we do throw it away wholesale
  202. // as part of a path if we throw the entire path away.
  203. containsSomethingInteresting |= !event.isPrunable();
  204. break;
  205. }
  206. case PathDiagnosticPiece::ControlFlow:
  207. break;
  208. case PathDiagnosticPiece::Note:
  209. break;
  210. }
  211. pieces.push_back(std::move(piece));
  212. }
  213. return containsSomethingInteresting;
  214. }
  215. /// Returns true if the given decl has been implicitly given a body, either by
  216. /// the analyzer or by the compiler proper.
  217. static bool hasImplicitBody(const Decl *D) {
  218. assert(D);
  219. return D->isImplicit() || !D->hasBody();
  220. }
  221. /// Recursively scan through a path and make sure that all call pieces have
  222. /// valid locations.
  223. static void
  224. adjustCallLocations(PathPieces &Pieces,
  225. PathDiagnosticLocation *LastCallLocation = nullptr) {
  226. for (const auto &I : Pieces) {
  227. auto *Call = dyn_cast<PathDiagnosticCallPiece>(I.get());
  228. if (!Call)
  229. continue;
  230. if (LastCallLocation) {
  231. bool CallerIsImplicit = hasImplicitBody(Call->getCaller());
  232. if (CallerIsImplicit || !Call->callEnter.asLocation().isValid())
  233. Call->callEnter = *LastCallLocation;
  234. if (CallerIsImplicit || !Call->callReturn.asLocation().isValid())
  235. Call->callReturn = *LastCallLocation;
  236. }
  237. // Recursively clean out the subclass. Keep this call around if
  238. // it contains any informative diagnostics.
  239. PathDiagnosticLocation *ThisCallLocation;
  240. if (Call->callEnterWithin.asLocation().isValid() &&
  241. !hasImplicitBody(Call->getCallee()))
  242. ThisCallLocation = &Call->callEnterWithin;
  243. else
  244. ThisCallLocation = &Call->callEnter;
  245. assert(ThisCallLocation && "Outermost call has an invalid location");
  246. adjustCallLocations(Call->path, ThisCallLocation);
  247. }
  248. }
  249. /// Remove edges in and out of C++ default initializer expressions. These are
  250. /// for fields that have in-class initializers, as opposed to being initialized
  251. /// explicitly in a constructor or braced list.
  252. static void removeEdgesToDefaultInitializers(PathPieces &Pieces) {
  253. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  254. if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
  255. removeEdgesToDefaultInitializers(C->path);
  256. if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
  257. removeEdgesToDefaultInitializers(M->subPieces);
  258. if (auto *CF = dyn_cast<PathDiagnosticControlFlowPiece>(I->get())) {
  259. const Stmt *Start = CF->getStartLocation().asStmt();
  260. const Stmt *End = CF->getEndLocation().asStmt();
  261. if (Start && isa<CXXDefaultInitExpr>(Start)) {
  262. I = Pieces.erase(I);
  263. continue;
  264. } else if (End && isa<CXXDefaultInitExpr>(End)) {
  265. PathPieces::iterator Next = std::next(I);
  266. if (Next != E) {
  267. if (auto *NextCF =
  268. dyn_cast<PathDiagnosticControlFlowPiece>(Next->get())) {
  269. NextCF->setStartLocation(CF->getStartLocation());
  270. }
  271. }
  272. I = Pieces.erase(I);
  273. continue;
  274. }
  275. }
  276. I++;
  277. }
  278. }
  279. /// Remove all pieces with invalid locations as these cannot be serialized.
  280. /// We might have pieces with invalid locations as a result of inlining Body
  281. /// Farm generated functions.
  282. static void removePiecesWithInvalidLocations(PathPieces &Pieces) {
  283. for (PathPieces::iterator I = Pieces.begin(), E = Pieces.end(); I != E;) {
  284. if (auto *C = dyn_cast<PathDiagnosticCallPiece>(I->get()))
  285. removePiecesWithInvalidLocations(C->path);
  286. if (auto *M = dyn_cast<PathDiagnosticMacroPiece>(I->get()))
  287. removePiecesWithInvalidLocations(M->subPieces);
  288. if (!(*I)->getLocation().isValid() ||
  289. !(*I)->getLocation().asLocation().isValid()) {
  290. I = Pieces.erase(I);
  291. continue;
  292. }
  293. I++;
  294. }
  295. }
  296. //===----------------------------------------------------------------------===//
  297. // PathDiagnosticBuilder and its associated routines and helper objects.
  298. //===----------------------------------------------------------------------===//
  299. namespace {
  300. class PathDiagnosticBuilder : public BugReporterContext {
  301. BugReport *R;
  302. PathDiagnosticConsumer *PDC;
  303. public:
  304. const LocationContext *LC;
  305. PathDiagnosticBuilder(GRBugReporter &br,
  306. BugReport *r, InterExplodedGraphMap &Backmap,
  307. PathDiagnosticConsumer *pdc)
  308. : BugReporterContext(br, Backmap), R(r), PDC(pdc),
  309. LC(r->getErrorNode()->getLocationContext()) {}
  310. PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
  311. PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
  312. const ExplodedNode *N);
  313. BugReport *getBugReport() { return R; }
  314. Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
  315. ParentMap& getParentMap() { return LC->getParentMap(); }
  316. const Stmt *getParent(const Stmt *S) {
  317. return getParentMap().getParent(S);
  318. }
  319. PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
  320. PathDiagnosticConsumer::PathGenerationScheme getGenerationScheme() const {
  321. return PDC ? PDC->getGenerationScheme() : PathDiagnosticConsumer::Minimal;
  322. }
  323. bool supportsLogicalOpControlFlow() const {
  324. return PDC ? PDC->supportsLogicalOpControlFlow() : true;
  325. }
  326. };
  327. } // namespace
  328. PathDiagnosticLocation
  329. PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
  330. if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
  331. return PathDiagnosticLocation(S, getSourceManager(), LC);
  332. return PathDiagnosticLocation::createDeclEnd(N->getLocationContext(),
  333. getSourceManager());
  334. }
  335. PathDiagnosticLocation
  336. PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
  337. const ExplodedNode *N) {
  338. // Slow, but probably doesn't matter.
  339. if (os.str().empty())
  340. os << ' ';
  341. const PathDiagnosticLocation &Loc = ExecutionContinues(N);
  342. if (Loc.asStmt())
  343. os << "Execution continues on line "
  344. << getSourceManager().getExpansionLineNumber(Loc.asLocation())
  345. << '.';
  346. else {
  347. os << "Execution jumps to the end of the ";
  348. const Decl *D = N->getLocationContext()->getDecl();
  349. if (isa<ObjCMethodDecl>(D))
  350. os << "method";
  351. else if (isa<FunctionDecl>(D))
  352. os << "function";
  353. else {
  354. assert(isa<BlockDecl>(D));
  355. os << "anonymous block";
  356. }
  357. os << '.';
  358. }
  359. return Loc;
  360. }
  361. static const Stmt *getEnclosingParent(const Stmt *S, const ParentMap &PM) {
  362. if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
  363. return PM.getParentIgnoreParens(S);
  364. const Stmt *Parent = PM.getParentIgnoreParens(S);
  365. if (!Parent)
  366. return nullptr;
  367. switch (Parent->getStmtClass()) {
  368. case Stmt::ForStmtClass:
  369. case Stmt::DoStmtClass:
  370. case Stmt::WhileStmtClass:
  371. case Stmt::ObjCForCollectionStmtClass:
  372. case Stmt::CXXForRangeStmtClass:
  373. return Parent;
  374. default:
  375. break;
  376. }
  377. return nullptr;
  378. }
  379. static PathDiagnosticLocation
  380. getEnclosingStmtLocation(const Stmt *S, SourceManager &SMgr, const ParentMap &P,
  381. const LocationContext *LC, bool allowNestedContexts) {
  382. if (!S)
  383. return {};
  384. while (const Stmt *Parent = getEnclosingParent(S, P)) {
  385. switch (Parent->getStmtClass()) {
  386. case Stmt::BinaryOperatorClass: {
  387. const auto *B = cast<BinaryOperator>(Parent);
  388. if (B->isLogicalOp())
  389. return PathDiagnosticLocation(allowNestedContexts ? B : S, SMgr, LC);
  390. break;
  391. }
  392. case Stmt::CompoundStmtClass:
  393. case Stmt::StmtExprClass:
  394. return PathDiagnosticLocation(S, SMgr, LC);
  395. case Stmt::ChooseExprClass:
  396. // Similar to '?' if we are referring to condition, just have the edge
  397. // point to the entire choose expression.
  398. if (allowNestedContexts || cast<ChooseExpr>(Parent)->getCond() == S)
  399. return PathDiagnosticLocation(Parent, SMgr, LC);
  400. else
  401. return PathDiagnosticLocation(S, SMgr, LC);
  402. case Stmt::BinaryConditionalOperatorClass:
  403. case Stmt::ConditionalOperatorClass:
  404. // For '?', if we are referring to condition, just have the edge point
  405. // to the entire '?' expression.
  406. if (allowNestedContexts ||
  407. cast<AbstractConditionalOperator>(Parent)->getCond() == S)
  408. return PathDiagnosticLocation(Parent, SMgr, LC);
  409. else
  410. return PathDiagnosticLocation(S, SMgr, LC);
  411. case Stmt::CXXForRangeStmtClass:
  412. if (cast<CXXForRangeStmt>(Parent)->getBody() == S)
  413. return PathDiagnosticLocation(S, SMgr, LC);
  414. break;
  415. case Stmt::DoStmtClass:
  416. return PathDiagnosticLocation(S, SMgr, LC);
  417. case Stmt::ForStmtClass:
  418. if (cast<ForStmt>(Parent)->getBody() == S)
  419. return PathDiagnosticLocation(S, SMgr, LC);
  420. break;
  421. case Stmt::IfStmtClass:
  422. if (cast<IfStmt>(Parent)->getCond() != S)
  423. return PathDiagnosticLocation(S, SMgr, LC);
  424. break;
  425. case Stmt::ObjCForCollectionStmtClass:
  426. if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
  427. return PathDiagnosticLocation(S, SMgr, LC);
  428. break;
  429. case Stmt::WhileStmtClass:
  430. if (cast<WhileStmt>(Parent)->getCond() != S)
  431. return PathDiagnosticLocation(S, SMgr, LC);
  432. break;
  433. default:
  434. break;
  435. }
  436. S = Parent;
  437. }
  438. assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
  439. return PathDiagnosticLocation(S, SMgr, LC);
  440. }
  441. PathDiagnosticLocation
  442. PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
  443. assert(S && "Null Stmt passed to getEnclosingStmtLocation");
  444. return ::getEnclosingStmtLocation(S, getSourceManager(), getParentMap(), LC,
  445. /*allowNestedContexts=*/false);
  446. }
  447. //===----------------------------------------------------------------------===//
  448. // "Minimal" path diagnostic generation algorithm.
  449. //===----------------------------------------------------------------------===//
  450. using StackDiagPair =
  451. std::pair<PathDiagnosticCallPiece *, const ExplodedNode *>;
  452. using StackDiagVector = SmallVector<StackDiagPair, 6>;
  453. static void updateStackPiecesWithMessage(PathDiagnosticPiece &P,
  454. StackDiagVector &CallStack) {
  455. // If the piece contains a special message, add it to all the call
  456. // pieces on the active stack.
  457. if (auto *ep = dyn_cast<PathDiagnosticEventPiece>(&P)) {
  458. if (ep->hasCallStackHint())
  459. for (const auto &I : CallStack) {
  460. PathDiagnosticCallPiece *CP = I.first;
  461. const ExplodedNode *N = I.second;
  462. std::string stackMsg = ep->getCallStackMessage(N);
  463. // The last message on the path to final bug is the most important
  464. // one. Since we traverse the path backwards, do not add the message
  465. // if one has been previously added.
  466. if (!CP->hasCallStackMessage())
  467. CP->setCallStackMessage(stackMsg);
  468. }
  469. }
  470. }
  471. static void CompactMacroExpandedPieces(PathPieces &path,
  472. const SourceManager& SM);
  473. std::shared_ptr<PathDiagnosticControlFlowPiece> generateDiagForSwitchOP(
  474. const ExplodedNode *N,
  475. const CFGBlock *Dst,
  476. const SourceManager &SM,
  477. const LocationContext *LC,
  478. PathDiagnosticBuilder &PDB,
  479. PathDiagnosticLocation &Start
  480. ) {
  481. // Figure out what case arm we took.
  482. std::string sbuf;
  483. llvm::raw_string_ostream os(sbuf);
  484. PathDiagnosticLocation End;
  485. if (const Stmt *S = Dst->getLabel()) {
  486. End = PathDiagnosticLocation(S, SM, LC);
  487. switch (S->getStmtClass()) {
  488. default:
  489. os << "No cases match in the switch statement. "
  490. "Control jumps to line "
  491. << End.asLocation().getExpansionLineNumber();
  492. break;
  493. case Stmt::DefaultStmtClass:
  494. os << "Control jumps to the 'default' case at line "
  495. << End.asLocation().getExpansionLineNumber();
  496. break;
  497. case Stmt::CaseStmtClass: {
  498. os << "Control jumps to 'case ";
  499. const auto *Case = cast<CaseStmt>(S);
  500. const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
  501. // Determine if it is an enum.
  502. bool GetRawInt = true;
  503. if (const auto *DR = dyn_cast<DeclRefExpr>(LHS)) {
  504. // FIXME: Maybe this should be an assertion. Are there cases
  505. // were it is not an EnumConstantDecl?
  506. const auto *D = dyn_cast<EnumConstantDecl>(DR->getDecl());
  507. if (D) {
  508. GetRawInt = false;
  509. os << *D;
  510. }
  511. }
  512. if (GetRawInt)
  513. os << LHS->EvaluateKnownConstInt(PDB.getASTContext());
  514. os << ":' at line " << End.asLocation().getExpansionLineNumber();
  515. break;
  516. }
  517. }
  518. } else {
  519. os << "'Default' branch taken. ";
  520. End = PDB.ExecutionContinues(os, N);
  521. }
  522. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  523. os.str());
  524. }
  525. std::shared_ptr<PathDiagnosticControlFlowPiece> generateDiagForGotoOP(
  526. const Stmt *S,
  527. PathDiagnosticBuilder &PDB,
  528. PathDiagnosticLocation &Start) {
  529. std::string sbuf;
  530. llvm::raw_string_ostream os(sbuf);
  531. const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
  532. os << "Control jumps to line " << End.asLocation().getExpansionLineNumber();
  533. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str());
  534. }
  535. std::shared_ptr<PathDiagnosticControlFlowPiece> generateDiagForBinaryOP(
  536. const ExplodedNode *N,
  537. const Stmt *T,
  538. const CFGBlock *Src,
  539. const CFGBlock *Dst,
  540. const SourceManager &SM,
  541. PathDiagnosticBuilder &PDB,
  542. const LocationContext *LC) {
  543. const auto *B = cast<BinaryOperator>(T);
  544. std::string sbuf;
  545. llvm::raw_string_ostream os(sbuf);
  546. os << "Left side of '";
  547. PathDiagnosticLocation Start, End;
  548. if (B->getOpcode() == BO_LAnd) {
  549. os << "&&"
  550. << "' is ";
  551. if (*(Src->succ_begin() + 1) == Dst) {
  552. os << "false";
  553. End = PathDiagnosticLocation(B->getLHS(), SM, LC);
  554. Start =
  555. PathDiagnosticLocation::createOperatorLoc(B, SM);
  556. } else {
  557. os << "true";
  558. Start = PathDiagnosticLocation(B->getLHS(), SM, LC);
  559. End = PDB.ExecutionContinues(N);
  560. }
  561. } else {
  562. assert(B->getOpcode() == BO_LOr);
  563. os << "||"
  564. << "' is ";
  565. if (*(Src->succ_begin() + 1) == Dst) {
  566. os << "false";
  567. Start = PathDiagnosticLocation(B->getLHS(), SM, LC);
  568. End = PDB.ExecutionContinues(N);
  569. } else {
  570. os << "true";
  571. End = PathDiagnosticLocation(B->getLHS(), SM, LC);
  572. Start =
  573. PathDiagnosticLocation::createOperatorLoc(B, SM);
  574. }
  575. }
  576. return std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  577. os.str());
  578. }
  579. void generateMinimalDiagForBlockEdge(const ExplodedNode *N, BlockEdge BE,
  580. const SourceManager &SM,
  581. PathDiagnosticBuilder &PDB,
  582. PathDiagnostic &PD) {
  583. const LocationContext *LC = N->getLocationContext();
  584. const CFGBlock *Src = BE.getSrc();
  585. const CFGBlock *Dst = BE.getDst();
  586. const Stmt *T = Src->getTerminator();
  587. if (!T)
  588. return;
  589. auto Start = PathDiagnosticLocation::createBegin(T, SM, LC);
  590. switch (T->getStmtClass()) {
  591. default:
  592. break;
  593. case Stmt::GotoStmtClass:
  594. case Stmt::IndirectGotoStmtClass: {
  595. if (const Stmt *S = PathDiagnosticLocation::getNextStmt(N))
  596. PD.getActivePath().push_front(generateDiagForGotoOP(S, PDB, Start));
  597. break;
  598. }
  599. case Stmt::SwitchStmtClass: {
  600. PD.getActivePath().push_front(
  601. generateDiagForSwitchOP(N, Dst, SM, LC, PDB, Start));
  602. break;
  603. }
  604. case Stmt::BreakStmtClass:
  605. case Stmt::ContinueStmtClass: {
  606. std::string sbuf;
  607. llvm::raw_string_ostream os(sbuf);
  608. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  609. PD.getActivePath().push_front(
  610. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
  611. break;
  612. }
  613. // Determine control-flow for ternary '?'.
  614. case Stmt::BinaryConditionalOperatorClass:
  615. case Stmt::ConditionalOperatorClass: {
  616. std::string sbuf;
  617. llvm::raw_string_ostream os(sbuf);
  618. os << "'?' condition is ";
  619. if (*(Src->succ_begin() + 1) == Dst)
  620. os << "false";
  621. else
  622. os << "true";
  623. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  624. if (const Stmt *S = End.asStmt())
  625. End = PDB.getEnclosingStmtLocation(S);
  626. PD.getActivePath().push_front(
  627. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End, os.str()));
  628. break;
  629. }
  630. // Determine control-flow for short-circuited '&&' and '||'.
  631. case Stmt::BinaryOperatorClass: {
  632. if (!PDB.supportsLogicalOpControlFlow())
  633. break;
  634. std::shared_ptr<PathDiagnosticControlFlowPiece> Diag =
  635. generateDiagForBinaryOP(N, T, Src, Dst, SM, PDB, LC);
  636. PD.getActivePath().push_front(Diag);
  637. break;
  638. }
  639. case Stmt::DoStmtClass:
  640. if (*(Src->succ_begin()) == Dst) {
  641. std::string sbuf;
  642. llvm::raw_string_ostream os(sbuf);
  643. os << "Loop condition is true. ";
  644. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  645. if (const Stmt *S = End.asStmt())
  646. End = PDB.getEnclosingStmtLocation(S);
  647. PD.getActivePath().push_front(
  648. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  649. os.str()));
  650. } else {
  651. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  652. if (const Stmt *S = End.asStmt())
  653. End = PDB.getEnclosingStmtLocation(S);
  654. PD.getActivePath().push_front(
  655. std::make_shared<PathDiagnosticControlFlowPiece>(
  656. Start, End, "Loop condition is false. Exiting loop"));
  657. }
  658. break;
  659. case Stmt::WhileStmtClass:
  660. case Stmt::ForStmtClass:
  661. if (*(Src->succ_begin() + 1) == Dst) {
  662. std::string sbuf;
  663. llvm::raw_string_ostream os(sbuf);
  664. os << "Loop condition is false. ";
  665. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  666. if (const Stmt *S = End.asStmt())
  667. End = PDB.getEnclosingStmtLocation(S);
  668. PD.getActivePath().push_front(
  669. std::make_shared<PathDiagnosticControlFlowPiece>(Start, End,
  670. os.str()));
  671. } else {
  672. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  673. if (const Stmt *S = End.asStmt())
  674. End = PDB.getEnclosingStmtLocation(S);
  675. PD.getActivePath().push_front(
  676. std::make_shared<PathDiagnosticControlFlowPiece>(
  677. Start, End, "Loop condition is true. Entering loop body"));
  678. }
  679. break;
  680. case Stmt::IfStmtClass: {
  681. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  682. if (const Stmt *S = End.asStmt())
  683. End = PDB.getEnclosingStmtLocation(S);
  684. if (*(Src->succ_begin() + 1) == Dst)
  685. PD.getActivePath().push_front(
  686. std::make_shared<PathDiagnosticControlFlowPiece>(
  687. Start, End, "Taking false branch"));
  688. else
  689. PD.getActivePath().push_front(
  690. std::make_shared<PathDiagnosticControlFlowPiece>(
  691. Start, End, "Taking true branch"));
  692. break;
  693. }
  694. }
  695. }
  696. // Cone-of-influence: support the reverse propagation of "interesting" symbols
  697. // and values by tracing interesting calculations backwards through evaluated
  698. // expressions along a path. This is probably overly complicated, but the idea
  699. // is that if an expression computed an "interesting" value, the child
  700. // expressions are also likely to be "interesting" as well (which then
  701. // propagates to the values they in turn compute). This reverse propagation
  702. // is needed to track interesting correlations across function call boundaries,
  703. // where formal arguments bind to actual arguments, etc. This is also needed
  704. // because the constraint solver sometimes simplifies certain symbolic values
  705. // into constants when appropriate, and this complicates reasoning about
  706. // interesting values.
  707. using InterestingExprs = llvm::DenseSet<const Expr *>;
  708. static void reversePropagateIntererstingSymbols(BugReport &R,
  709. InterestingExprs &IE,
  710. const ProgramState *State,
  711. const Expr *Ex,
  712. const LocationContext *LCtx) {
  713. SVal V = State->getSVal(Ex, LCtx);
  714. if (!(R.isInteresting(V) || IE.count(Ex)))
  715. return;
  716. switch (Ex->getStmtClass()) {
  717. default:
  718. if (!isa<CastExpr>(Ex))
  719. break;
  720. LLVM_FALLTHROUGH;
  721. case Stmt::BinaryOperatorClass:
  722. case Stmt::UnaryOperatorClass: {
  723. for (const Stmt *SubStmt : Ex->children()) {
  724. if (const auto *child = dyn_cast_or_null<Expr>(SubStmt)) {
  725. IE.insert(child);
  726. SVal ChildV = State->getSVal(child, LCtx);
  727. R.markInteresting(ChildV);
  728. }
  729. }
  730. break;
  731. }
  732. }
  733. R.markInteresting(V);
  734. }
  735. static void reversePropagateInterestingSymbols(BugReport &R,
  736. InterestingExprs &IE,
  737. const ProgramState *State,
  738. const LocationContext *CalleeCtx)
  739. {
  740. // FIXME: Handle non-CallExpr-based CallEvents.
  741. const StackFrameContext *Callee = CalleeCtx->getStackFrame();
  742. const Stmt *CallSite = Callee->getCallSite();
  743. if (const auto *CE = dyn_cast_or_null<CallExpr>(CallSite)) {
  744. if (const auto *FD = dyn_cast<FunctionDecl>(CalleeCtx->getDecl())) {
  745. FunctionDecl::param_const_iterator PI = FD->param_begin(),
  746. PE = FD->param_end();
  747. CallExpr::const_arg_iterator AI = CE->arg_begin(), AE = CE->arg_end();
  748. for (; AI != AE && PI != PE; ++AI, ++PI) {
  749. if (const Expr *ArgE = *AI) {
  750. if (const ParmVarDecl *PD = *PI) {
  751. Loc LV = State->getLValue(PD, CalleeCtx);
  752. if (R.isInteresting(LV) || R.isInteresting(State->getRawSVal(LV)))
  753. IE.insert(ArgE);
  754. }
  755. }
  756. }
  757. }
  758. }
  759. }
  760. //===----------------------------------------------------------------------===//
  761. // Functions for determining if a loop was executed 0 times.
  762. //===----------------------------------------------------------------------===//
  763. static bool isLoop(const Stmt *Term) {
  764. switch (Term->getStmtClass()) {
  765. case Stmt::ForStmtClass:
  766. case Stmt::WhileStmtClass:
  767. case Stmt::ObjCForCollectionStmtClass:
  768. case Stmt::CXXForRangeStmtClass:
  769. return true;
  770. default:
  771. // Note that we intentionally do not include do..while here.
  772. return false;
  773. }
  774. }
  775. static bool isJumpToFalseBranch(const BlockEdge *BE) {
  776. const CFGBlock *Src = BE->getSrc();
  777. assert(Src->succ_size() == 2);
  778. return (*(Src->succ_begin()+1) == BE->getDst());
  779. }
  780. static bool isContainedByStmt(ParentMap &PM, const Stmt *S, const Stmt *SubS) {
  781. while (SubS) {
  782. if (SubS == S)
  783. return true;
  784. SubS = PM.getParent(SubS);
  785. }
  786. return false;
  787. }
  788. static const Stmt *getStmtBeforeCond(ParentMap &PM, const Stmt *Term,
  789. const ExplodedNode *N) {
  790. while (N) {
  791. Optional<StmtPoint> SP = N->getLocation().getAs<StmtPoint>();
  792. if (SP) {
  793. const Stmt *S = SP->getStmt();
  794. if (!isContainedByStmt(PM, Term, S))
  795. return S;
  796. }
  797. N = N->getFirstPred();
  798. }
  799. return nullptr;
  800. }
  801. static bool isInLoopBody(ParentMap &PM, const Stmt *S, const Stmt *Term) {
  802. const Stmt *LoopBody = nullptr;
  803. switch (Term->getStmtClass()) {
  804. case Stmt::CXXForRangeStmtClass: {
  805. const auto *FR = cast<CXXForRangeStmt>(Term);
  806. if (isContainedByStmt(PM, FR->getInc(), S))
  807. return true;
  808. if (isContainedByStmt(PM, FR->getLoopVarStmt(), S))
  809. return true;
  810. LoopBody = FR->getBody();
  811. break;
  812. }
  813. case Stmt::ForStmtClass: {
  814. const auto *FS = cast<ForStmt>(Term);
  815. if (isContainedByStmt(PM, FS->getInc(), S))
  816. return true;
  817. LoopBody = FS->getBody();
  818. break;
  819. }
  820. case Stmt::ObjCForCollectionStmtClass: {
  821. const auto *FC = cast<ObjCForCollectionStmt>(Term);
  822. LoopBody = FC->getBody();
  823. break;
  824. }
  825. case Stmt::WhileStmtClass:
  826. LoopBody = cast<WhileStmt>(Term)->getBody();
  827. break;
  828. default:
  829. return false;
  830. }
  831. return isContainedByStmt(PM, LoopBody, S);
  832. }
  833. /// Adds a sanitized control-flow diagnostic edge to a path.
  834. static void addEdgeToPath(PathPieces &path,
  835. PathDiagnosticLocation &PrevLoc,
  836. PathDiagnosticLocation NewLoc) {
  837. if (!NewLoc.isValid())
  838. return;
  839. SourceLocation NewLocL = NewLoc.asLocation();
  840. if (NewLocL.isInvalid())
  841. return;
  842. if (!PrevLoc.isValid() || !PrevLoc.asLocation().isValid()) {
  843. PrevLoc = NewLoc;
  844. return;
  845. }
  846. // Ignore self-edges, which occur when there are multiple nodes at the same
  847. // statement.
  848. if (NewLoc.asStmt() && NewLoc.asStmt() == PrevLoc.asStmt())
  849. return;
  850. path.push_front(
  851. std::make_shared<PathDiagnosticControlFlowPiece>(NewLoc, PrevLoc));
  852. PrevLoc = NewLoc;
  853. }
  854. /// A customized wrapper for CFGBlock::getTerminatorCondition()
  855. /// which returns the element for ObjCForCollectionStmts.
  856. static const Stmt *getTerminatorCondition(const CFGBlock *B) {
  857. const Stmt *S = B->getTerminatorCondition();
  858. if (const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(S))
  859. return FS->getElement();
  860. return S;
  861. }
  862. static const char StrEnteringLoop[] = "Entering loop body";
  863. static const char StrLoopBodyZero[] = "Loop body executed 0 times";
  864. static const char StrLoopRangeEmpty[] =
  865. "Loop body skipped when range is empty";
  866. static const char StrLoopCollectionEmpty[] =
  867. "Loop body skipped when collection is empty";
  868. static std::unique_ptr<FilesToLineNumsMap>
  869. findExecutedLines(SourceManager &SM, const ExplodedNode *N);
  870. /// Generate diagnostics for the node \p N,
  871. /// and write it into \p PD.
  872. /// \p AddPathEdges Whether diagnostic consumer can generate path arrows
  873. /// showing both row and column.
  874. static void generatePathDiagnosticsForNode(const ExplodedNode *N,
  875. PathDiagnostic &PD,
  876. PathDiagnosticLocation &PrevLoc,
  877. PathDiagnosticBuilder &PDB,
  878. LocationContextMap &LCM,
  879. StackDiagVector &CallStack,
  880. InterestingExprs &IE,
  881. bool AddPathEdges) {
  882. ProgramPoint P = N->getLocation();
  883. const SourceManager& SM = PDB.getSourceManager();
  884. // Have we encountered an entrance to a call? It may be
  885. // the case that we have not encountered a matching
  886. // call exit before this point. This means that the path
  887. // terminated within the call itself.
  888. if (auto CE = P.getAs<CallEnter>()) {
  889. if (AddPathEdges) {
  890. // Add an edge to the start of the function.
  891. const StackFrameContext *CalleeLC = CE->getCalleeContext();
  892. const Decl *D = CalleeLC->getDecl();
  893. // Add the edge only when the callee has body. We jump to the beginning
  894. // of the *declaration*, however we expect it to be followed by the
  895. // body. This isn't the case for autosynthesized property accessors in
  896. // Objective-C. No need for a similar extra check for CallExit points
  897. // because the exit edge comes from a statement (i.e. return),
  898. // not from declaration.
  899. if (D->hasBody())
  900. addEdgeToPath(PD.getActivePath(), PrevLoc,
  901. PathDiagnosticLocation::createBegin(D, SM));
  902. }
  903. // Did we visit an entire call?
  904. bool VisitedEntireCall = PD.isWithinCall();
  905. PD.popActivePath();
  906. PathDiagnosticCallPiece *C;
  907. if (VisitedEntireCall) {
  908. C = cast<PathDiagnosticCallPiece>(PD.getActivePath().front().get());
  909. } else {
  910. const Decl *Caller = CE->getLocationContext()->getDecl();
  911. C = PathDiagnosticCallPiece::construct(PD.getActivePath(), Caller);
  912. if (AddPathEdges) {
  913. // Since we just transferred the path over to the call piece,
  914. // reset the mapping from active to location context.
  915. assert(PD.getActivePath().size() == 1 &&
  916. PD.getActivePath().front().get() == C);
  917. LCM[&PD.getActivePath()] = nullptr;
  918. }
  919. // Record the location context mapping for the path within
  920. // the call.
  921. assert(LCM[&C->path] == nullptr ||
  922. LCM[&C->path] == CE->getCalleeContext());
  923. LCM[&C->path] = CE->getCalleeContext();
  924. // If this is the first item in the active path, record
  925. // the new mapping from active path to location context.
  926. const LocationContext *&NewLC = LCM[&PD.getActivePath()];
  927. if (!NewLC)
  928. NewLC = N->getLocationContext();
  929. PDB.LC = NewLC;
  930. }
  931. C->setCallee(*CE, SM);
  932. // Update the previous location in the active path.
  933. PrevLoc = C->getLocation();
  934. if (!CallStack.empty()) {
  935. assert(CallStack.back().first == C);
  936. CallStack.pop_back();
  937. }
  938. return;
  939. }
  940. if (AddPathEdges) {
  941. // Query the location context here and the previous location
  942. // as processing CallEnter may change the active path.
  943. PDB.LC = N->getLocationContext();
  944. // Record the mapping from the active path to the location
  945. // context.
  946. assert(!LCM[&PD.getActivePath()] || LCM[&PD.getActivePath()] == PDB.LC);
  947. LCM[&PD.getActivePath()] = PDB.LC;
  948. }
  949. // Have we encountered an exit from a function call?
  950. if (Optional<CallExitEnd> CE = P.getAs<CallExitEnd>()) {
  951. // We are descending into a call (backwards). Construct
  952. // a new call piece to contain the path pieces for that call.
  953. auto C = PathDiagnosticCallPiece::construct(*CE, SM);
  954. // Record the mapping from call piece to LocationContext.
  955. LCM[&C->path] = CE->getCalleeContext();
  956. if (AddPathEdges) {
  957. const Stmt *S = CE->getCalleeContext()->getCallSite();
  958. // Propagate the interesting symbols accordingly.
  959. if (const auto *Ex = dyn_cast_or_null<Expr>(S)) {
  960. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  961. N->getState().get(), Ex,
  962. N->getLocationContext());
  963. }
  964. // Add the edge to the return site.
  965. addEdgeToPath(PD.getActivePath(), PrevLoc, C->callReturn);
  966. PrevLoc.invalidate();
  967. }
  968. auto *P = C.get();
  969. PD.getActivePath().push_front(std::move(C));
  970. // Make the contents of the call the active path for now.
  971. PD.pushActivePath(&P->path);
  972. CallStack.push_back(StackDiagPair(P, N));
  973. return;
  974. }
  975. if (auto PS = P.getAs<PostStmt>()) {
  976. if (!AddPathEdges)
  977. return;
  978. // For expressions, make sure we propagate the
  979. // interesting symbols correctly.
  980. if (const Expr *Ex = PS->getStmtAs<Expr>())
  981. reversePropagateIntererstingSymbols(*PDB.getBugReport(), IE,
  982. N->getState().get(), Ex,
  983. N->getLocationContext());
  984. // Add an edge. If this is an ObjCForCollectionStmt do
  985. // not add an edge here as it appears in the CFG both
  986. // as a terminator and as a terminator condition.
  987. if (!isa<ObjCForCollectionStmt>(PS->getStmt())) {
  988. PathDiagnosticLocation L =
  989. PathDiagnosticLocation(PS->getStmt(), SM, PDB.LC);
  990. addEdgeToPath(PD.getActivePath(), PrevLoc, L);
  991. }
  992. } else if (auto BE = P.getAs<BlockEdge>()) {
  993. if (!AddPathEdges) {
  994. generateMinimalDiagForBlockEdge(N, *BE, SM, PDB, PD);
  995. return;
  996. }
  997. // Does this represent entering a call? If so, look at propagating
  998. // interesting symbols across call boundaries.
  999. if (const ExplodedNode *NextNode = N->getFirstPred()) {
  1000. const LocationContext *CallerCtx = NextNode->getLocationContext();
  1001. const LocationContext *CalleeCtx = PDB.LC;
  1002. if (CallerCtx != CalleeCtx && AddPathEdges) {
  1003. reversePropagateInterestingSymbols(*PDB.getBugReport(), IE,
  1004. N->getState().get(), CalleeCtx);
  1005. }
  1006. }
  1007. // Are we jumping to the head of a loop? Add a special diagnostic.
  1008. if (const Stmt *Loop = BE->getSrc()->getLoopTarget()) {
  1009. PathDiagnosticLocation L(Loop, SM, PDB.LC);
  1010. const Stmt *Body = nullptr;
  1011. if (const auto *FS = dyn_cast<ForStmt>(Loop))
  1012. Body = FS->getBody();
  1013. else if (const auto *WS = dyn_cast<WhileStmt>(Loop))
  1014. Body = WS->getBody();
  1015. else if (const auto *OFS = dyn_cast<ObjCForCollectionStmt>(Loop)) {
  1016. Body = OFS->getBody();
  1017. } else if (const auto *FRS = dyn_cast<CXXForRangeStmt>(Loop)) {
  1018. Body = FRS->getBody();
  1019. }
  1020. // do-while statements are explicitly excluded here
  1021. auto p = std::make_shared<PathDiagnosticEventPiece>(
  1022. L, "Looping back to the head "
  1023. "of the loop");
  1024. p->setPrunable(true);
  1025. addEdgeToPath(PD.getActivePath(), PrevLoc, p->getLocation());
  1026. PD.getActivePath().push_front(std::move(p));
  1027. if (const auto *CS = dyn_cast_or_null<CompoundStmt>(Body)) {
  1028. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1029. PathDiagnosticLocation::createEndBrace(CS, SM));
  1030. }
  1031. }
  1032. const CFGBlock *BSrc = BE->getSrc();
  1033. ParentMap &PM = PDB.getParentMap();
  1034. if (const Stmt *Term = BSrc->getTerminator()) {
  1035. // Are we jumping past the loop body without ever executing the
  1036. // loop (because the condition was false)?
  1037. if (isLoop(Term)) {
  1038. const Stmt *TermCond = getTerminatorCondition(BSrc);
  1039. bool IsInLoopBody =
  1040. isInLoopBody(PM, getStmtBeforeCond(PM, TermCond, N), Term);
  1041. const char *str = nullptr;
  1042. if (isJumpToFalseBranch(&*BE)) {
  1043. if (!IsInLoopBody) {
  1044. if (isa<ObjCForCollectionStmt>(Term)) {
  1045. str = StrLoopCollectionEmpty;
  1046. } else if (isa<CXXForRangeStmt>(Term)) {
  1047. str = StrLoopRangeEmpty;
  1048. } else {
  1049. str = StrLoopBodyZero;
  1050. }
  1051. }
  1052. } else {
  1053. str = StrEnteringLoop;
  1054. }
  1055. if (str) {
  1056. PathDiagnosticLocation L(TermCond ? TermCond : Term, SM, PDB.LC);
  1057. auto PE = std::make_shared<PathDiagnosticEventPiece>(L, str);
  1058. PE->setPrunable(true);
  1059. addEdgeToPath(PD.getActivePath(), PrevLoc,
  1060. PE->getLocation());
  1061. PD.getActivePath().push_front(std::move(PE));
  1062. }
  1063. } else if (isa<BreakStmt>(Term) || isa<ContinueStmt>(Term) ||
  1064. isa<GotoStmt>(Term)) {
  1065. PathDiagnosticLocation L(Term, SM, PDB.LC);
  1066. addEdgeToPath(PD.getActivePath(), PrevLoc, L);
  1067. }
  1068. }
  1069. }
  1070. }
  1071. static std::unique_ptr<PathDiagnostic>
  1072. generateEmptyDiagnosticForReport(BugReport *R, SourceManager &SM) {
  1073. const BugType &BT = R->getBugType();
  1074. return llvm::make_unique<PathDiagnostic>(
  1075. R->getBugType().getCheckName(), R->getDeclWithIssue(),
  1076. R->getBugType().getName(), R->getDescription(),
  1077. R->getShortDescription(/*Fallback=*/false), BT.getCategory(),
  1078. R->getUniqueingLocation(), R->getUniqueingDecl(),
  1079. findExecutedLines(SM, R->getErrorNode()));
  1080. }
  1081. static const Stmt *getStmtParent(const Stmt *S, const ParentMap &PM) {
  1082. if (!S)
  1083. return nullptr;
  1084. while (true) {
  1085. S = PM.getParentIgnoreParens(S);
  1086. if (!S)
  1087. break;
  1088. if (isa<FullExpr>(S) ||
  1089. isa<CXXBindTemporaryExpr>(S) ||
  1090. isa<SubstNonTypeTemplateParmExpr>(S))
  1091. continue;
  1092. break;
  1093. }
  1094. return S;
  1095. }
  1096. static bool isConditionForTerminator(const Stmt *S, const Stmt *Cond) {
  1097. switch (S->getStmtClass()) {
  1098. case Stmt::BinaryOperatorClass: {
  1099. const auto *BO = cast<BinaryOperator>(S);
  1100. if (!BO->isLogicalOp())
  1101. return false;
  1102. return BO->getLHS() == Cond || BO->getRHS() == Cond;
  1103. }
  1104. case Stmt::IfStmtClass:
  1105. return cast<IfStmt>(S)->getCond() == Cond;
  1106. case Stmt::ForStmtClass:
  1107. return cast<ForStmt>(S)->getCond() == Cond;
  1108. case Stmt::WhileStmtClass:
  1109. return cast<WhileStmt>(S)->getCond() == Cond;
  1110. case Stmt::DoStmtClass:
  1111. return cast<DoStmt>(S)->getCond() == Cond;
  1112. case Stmt::ChooseExprClass:
  1113. return cast<ChooseExpr>(S)->getCond() == Cond;
  1114. case Stmt::IndirectGotoStmtClass:
  1115. return cast<IndirectGotoStmt>(S)->getTarget() == Cond;
  1116. case Stmt::SwitchStmtClass:
  1117. return cast<SwitchStmt>(S)->getCond() == Cond;
  1118. case Stmt::BinaryConditionalOperatorClass:
  1119. return cast<BinaryConditionalOperator>(S)->getCond() == Cond;
  1120. case Stmt::ConditionalOperatorClass: {
  1121. const auto *CO = cast<ConditionalOperator>(S);
  1122. return CO->getCond() == Cond ||
  1123. CO->getLHS() == Cond ||
  1124. CO->getRHS() == Cond;
  1125. }
  1126. case Stmt::ObjCForCollectionStmtClass:
  1127. return cast<ObjCForCollectionStmt>(S)->getElement() == Cond;
  1128. case Stmt::CXXForRangeStmtClass: {
  1129. const auto *FRS = cast<CXXForRangeStmt>(S);
  1130. return FRS->getCond() == Cond || FRS->getRangeInit() == Cond;
  1131. }
  1132. default:
  1133. return false;
  1134. }
  1135. }
  1136. static bool isIncrementOrInitInForLoop(const Stmt *S, const Stmt *FL) {
  1137. if (const auto *FS = dyn_cast<ForStmt>(FL))
  1138. return FS->getInc() == S || FS->getInit() == S;
  1139. if (const auto *FRS = dyn_cast<CXXForRangeStmt>(FL))
  1140. return FRS->getInc() == S || FRS->getRangeStmt() == S ||
  1141. FRS->getLoopVarStmt() || FRS->getRangeInit() == S;
  1142. return false;
  1143. }
  1144. using OptimizedCallsSet = llvm::DenseSet<const PathDiagnosticCallPiece *>;
  1145. /// Adds synthetic edges from top-level statements to their subexpressions.
  1146. ///
  1147. /// This avoids a "swoosh" effect, where an edge from a top-level statement A
  1148. /// points to a sub-expression B.1 that's not at the start of B. In these cases,
  1149. /// we'd like to see an edge from A to B, then another one from B to B.1.
  1150. static void addContextEdges(PathPieces &pieces, SourceManager &SM,
  1151. const ParentMap &PM, const LocationContext *LCtx) {
  1152. PathPieces::iterator Prev = pieces.end();
  1153. for (PathPieces::iterator I = pieces.begin(), E = Prev; I != E;
  1154. Prev = I, ++I) {
  1155. auto *Piece = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1156. if (!Piece)
  1157. continue;
  1158. PathDiagnosticLocation SrcLoc = Piece->getStartLocation();
  1159. SmallVector<PathDiagnosticLocation, 4> SrcContexts;
  1160. PathDiagnosticLocation NextSrcContext = SrcLoc;
  1161. const Stmt *InnerStmt = nullptr;
  1162. while (NextSrcContext.isValid() && NextSrcContext.asStmt() != InnerStmt) {
  1163. SrcContexts.push_back(NextSrcContext);
  1164. InnerStmt = NextSrcContext.asStmt();
  1165. NextSrcContext = getEnclosingStmtLocation(InnerStmt, SM, PM, LCtx,
  1166. /*allowNested=*/true);
  1167. }
  1168. // Repeatedly split the edge as necessary.
  1169. // This is important for nested logical expressions (||, &&, ?:) where we
  1170. // want to show all the levels of context.
  1171. while (true) {
  1172. const Stmt *Dst = Piece->getEndLocation().getStmtOrNull();
  1173. // We are looking at an edge. Is the destination within a larger
  1174. // expression?
  1175. PathDiagnosticLocation DstContext =
  1176. getEnclosingStmtLocation(Dst, SM, PM, LCtx, /*allowNested=*/true);
  1177. if (!DstContext.isValid() || DstContext.asStmt() == Dst)
  1178. break;
  1179. // If the source is in the same context, we're already good.
  1180. if (std::find(SrcContexts.begin(), SrcContexts.end(), DstContext) !=
  1181. SrcContexts.end())
  1182. break;
  1183. // Update the subexpression node to point to the context edge.
  1184. Piece->setStartLocation(DstContext);
  1185. // Try to extend the previous edge if it's at the same level as the source
  1186. // context.
  1187. if (Prev != E) {
  1188. auto *PrevPiece = dyn_cast<PathDiagnosticControlFlowPiece>(Prev->get());
  1189. if (PrevPiece) {
  1190. if (const Stmt *PrevSrc =
  1191. PrevPiece->getStartLocation().getStmtOrNull()) {
  1192. const Stmt *PrevSrcParent = getStmtParent(PrevSrc, PM);
  1193. if (PrevSrcParent ==
  1194. getStmtParent(DstContext.getStmtOrNull(), PM)) {
  1195. PrevPiece->setEndLocation(DstContext);
  1196. break;
  1197. }
  1198. }
  1199. }
  1200. }
  1201. // Otherwise, split the current edge into a context edge and a
  1202. // subexpression edge. Note that the context statement may itself have
  1203. // context.
  1204. auto P =
  1205. std::make_shared<PathDiagnosticControlFlowPiece>(SrcLoc, DstContext);
  1206. Piece = P.get();
  1207. I = pieces.insert(I, std::move(P));
  1208. }
  1209. }
  1210. }
  1211. /// Move edges from a branch condition to a branch target
  1212. /// when the condition is simple.
  1213. ///
  1214. /// This restructures some of the work of addContextEdges. That function
  1215. /// creates edges this may destroy, but they work together to create a more
  1216. /// aesthetically set of edges around branches. After the call to
  1217. /// addContextEdges, we may have (1) an edge to the branch, (2) an edge from
  1218. /// the branch to the branch condition, and (3) an edge from the branch
  1219. /// condition to the branch target. We keep (1), but may wish to remove (2)
  1220. /// and move the source of (3) to the branch if the branch condition is simple.
  1221. static void simplifySimpleBranches(PathPieces &pieces) {
  1222. for (PathPieces::iterator I = pieces.begin(), E = pieces.end(); I != E; ++I) {
  1223. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1224. if (!PieceI)
  1225. continue;
  1226. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1227. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1228. if (!s1Start || !s1End)
  1229. continue;
  1230. PathPieces::iterator NextI = I; ++NextI;
  1231. if (NextI == E)
  1232. break;
  1233. PathDiagnosticControlFlowPiece *PieceNextI = nullptr;
  1234. while (true) {
  1235. if (NextI == E)
  1236. break;
  1237. const auto *EV = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
  1238. if (EV) {
  1239. StringRef S = EV->getString();
  1240. if (S == StrEnteringLoop || S == StrLoopBodyZero ||
  1241. S == StrLoopCollectionEmpty || S == StrLoopRangeEmpty) {
  1242. ++NextI;
  1243. continue;
  1244. }
  1245. break;
  1246. }
  1247. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1248. break;
  1249. }
  1250. if (!PieceNextI)
  1251. continue;
  1252. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1253. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1254. if (!s2Start || !s2End || s1End != s2Start)
  1255. continue;
  1256. // We only perform this transformation for specific branch kinds.
  1257. // We don't want to do this for do..while, for example.
  1258. if (!(isa<ForStmt>(s1Start) || isa<WhileStmt>(s1Start) ||
  1259. isa<IfStmt>(s1Start) || isa<ObjCForCollectionStmt>(s1Start) ||
  1260. isa<CXXForRangeStmt>(s1Start)))
  1261. continue;
  1262. // Is s1End the branch condition?
  1263. if (!isConditionForTerminator(s1Start, s1End))
  1264. continue;
  1265. // Perform the hoisting by eliminating (2) and changing the start
  1266. // location of (3).
  1267. PieceNextI->setStartLocation(PieceI->getStartLocation());
  1268. I = pieces.erase(I);
  1269. }
  1270. }
  1271. /// Returns the number of bytes in the given (character-based) SourceRange.
  1272. ///
  1273. /// If the locations in the range are not on the same line, returns None.
  1274. ///
  1275. /// Note that this does not do a precise user-visible character or column count.
  1276. static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
  1277. SourceRange Range) {
  1278. SourceRange ExpansionRange(SM.getExpansionLoc(Range.getBegin()),
  1279. SM.getExpansionRange(Range.getEnd()).getEnd());
  1280. FileID FID = SM.getFileID(ExpansionRange.getBegin());
  1281. if (FID != SM.getFileID(ExpansionRange.getEnd()))
  1282. return None;
  1283. bool Invalid;
  1284. const llvm::MemoryBuffer *Buffer = SM.getBuffer(FID, &Invalid);
  1285. if (Invalid)
  1286. return None;
  1287. unsigned BeginOffset = SM.getFileOffset(ExpansionRange.getBegin());
  1288. unsigned EndOffset = SM.getFileOffset(ExpansionRange.getEnd());
  1289. StringRef Snippet = Buffer->getBuffer().slice(BeginOffset, EndOffset);
  1290. // We're searching the raw bytes of the buffer here, which might include
  1291. // escaped newlines and such. That's okay; we're trying to decide whether the
  1292. // SourceRange is covering a large or small amount of space in the user's
  1293. // editor.
  1294. if (Snippet.find_first_of("\r\n") != StringRef::npos)
  1295. return None;
  1296. // This isn't Unicode-aware, but it doesn't need to be.
  1297. return Snippet.size();
  1298. }
  1299. /// \sa getLengthOnSingleLine(SourceManager, SourceRange)
  1300. static Optional<size_t> getLengthOnSingleLine(SourceManager &SM,
  1301. const Stmt *S) {
  1302. return getLengthOnSingleLine(SM, S->getSourceRange());
  1303. }
  1304. /// Eliminate two-edge cycles created by addContextEdges().
  1305. ///
  1306. /// Once all the context edges are in place, there are plenty of cases where
  1307. /// there's a single edge from a top-level statement to a subexpression,
  1308. /// followed by a single path note, and then a reverse edge to get back out to
  1309. /// the top level. If the statement is simple enough, the subexpression edges
  1310. /// just add noise and make it harder to understand what's going on.
  1311. ///
  1312. /// This function only removes edges in pairs, because removing only one edge
  1313. /// might leave other edges dangling.
  1314. ///
  1315. /// This will not remove edges in more complicated situations:
  1316. /// - if there is more than one "hop" leading to or from a subexpression.
  1317. /// - if there is an inlined call between the edges instead of a single event.
  1318. /// - if the whole statement is large enough that having subexpression arrows
  1319. /// might be helpful.
  1320. static void removeContextCycles(PathPieces &Path, SourceManager &SM) {
  1321. for (PathPieces::iterator I = Path.begin(), E = Path.end(); I != E; ) {
  1322. // Pattern match the current piece and its successor.
  1323. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1324. if (!PieceI) {
  1325. ++I;
  1326. continue;
  1327. }
  1328. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1329. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1330. PathPieces::iterator NextI = I; ++NextI;
  1331. if (NextI == E)
  1332. break;
  1333. const auto *PieceNextI =
  1334. dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1335. if (!PieceNextI) {
  1336. if (isa<PathDiagnosticEventPiece>(NextI->get())) {
  1337. ++NextI;
  1338. if (NextI == E)
  1339. break;
  1340. PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1341. }
  1342. if (!PieceNextI) {
  1343. ++I;
  1344. continue;
  1345. }
  1346. }
  1347. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1348. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1349. if (s1Start && s2Start && s1Start == s2End && s2Start == s1End) {
  1350. const size_t MAX_SHORT_LINE_LENGTH = 80;
  1351. Optional<size_t> s1Length = getLengthOnSingleLine(SM, s1Start);
  1352. if (s1Length && *s1Length <= MAX_SHORT_LINE_LENGTH) {
  1353. Optional<size_t> s2Length = getLengthOnSingleLine(SM, s2Start);
  1354. if (s2Length && *s2Length <= MAX_SHORT_LINE_LENGTH) {
  1355. Path.erase(I);
  1356. I = Path.erase(NextI);
  1357. continue;
  1358. }
  1359. }
  1360. }
  1361. ++I;
  1362. }
  1363. }
  1364. /// Return true if X is contained by Y.
  1365. static bool lexicalContains(ParentMap &PM, const Stmt *X, const Stmt *Y) {
  1366. while (X) {
  1367. if (X == Y)
  1368. return true;
  1369. X = PM.getParent(X);
  1370. }
  1371. return false;
  1372. }
  1373. // Remove short edges on the same line less than 3 columns in difference.
  1374. static void removePunyEdges(PathPieces &path, SourceManager &SM,
  1375. ParentMap &PM) {
  1376. bool erased = false;
  1377. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E;
  1378. erased ? I : ++I) {
  1379. erased = false;
  1380. const auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1381. if (!PieceI)
  1382. continue;
  1383. const Stmt *start = PieceI->getStartLocation().getStmtOrNull();
  1384. const Stmt *end = PieceI->getEndLocation().getStmtOrNull();
  1385. if (!start || !end)
  1386. continue;
  1387. const Stmt *endParent = PM.getParent(end);
  1388. if (!endParent)
  1389. continue;
  1390. if (isConditionForTerminator(end, endParent))
  1391. continue;
  1392. SourceLocation FirstLoc = start->getBeginLoc();
  1393. SourceLocation SecondLoc = end->getBeginLoc();
  1394. if (!SM.isWrittenInSameFile(FirstLoc, SecondLoc))
  1395. continue;
  1396. if (SM.isBeforeInTranslationUnit(SecondLoc, FirstLoc))
  1397. std::swap(SecondLoc, FirstLoc);
  1398. SourceRange EdgeRange(FirstLoc, SecondLoc);
  1399. Optional<size_t> ByteWidth = getLengthOnSingleLine(SM, EdgeRange);
  1400. // If the statements are on different lines, continue.
  1401. if (!ByteWidth)
  1402. continue;
  1403. const size_t MAX_PUNY_EDGE_LENGTH = 2;
  1404. if (*ByteWidth <= MAX_PUNY_EDGE_LENGTH) {
  1405. // FIXME: There are enough /bytes/ between the endpoints of the edge, but
  1406. // there might not be enough /columns/. A proper user-visible column count
  1407. // is probably too expensive, though.
  1408. I = path.erase(I);
  1409. erased = true;
  1410. continue;
  1411. }
  1412. }
  1413. }
  1414. static void removeIdenticalEvents(PathPieces &path) {
  1415. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ++I) {
  1416. const auto *PieceI = dyn_cast<PathDiagnosticEventPiece>(I->get());
  1417. if (!PieceI)
  1418. continue;
  1419. PathPieces::iterator NextI = I; ++NextI;
  1420. if (NextI == E)
  1421. return;
  1422. const auto *PieceNextI = dyn_cast<PathDiagnosticEventPiece>(NextI->get());
  1423. if (!PieceNextI)
  1424. continue;
  1425. // Erase the second piece if it has the same exact message text.
  1426. if (PieceI->getString() == PieceNextI->getString()) {
  1427. path.erase(NextI);
  1428. }
  1429. }
  1430. }
  1431. static bool optimizeEdges(PathPieces &path, SourceManager &SM,
  1432. OptimizedCallsSet &OCS,
  1433. LocationContextMap &LCM) {
  1434. bool hasChanges = false;
  1435. const LocationContext *LC = LCM[&path];
  1436. assert(LC);
  1437. ParentMap &PM = LC->getParentMap();
  1438. for (PathPieces::iterator I = path.begin(), E = path.end(); I != E; ) {
  1439. // Optimize subpaths.
  1440. if (auto *CallI = dyn_cast<PathDiagnosticCallPiece>(I->get())) {
  1441. // Record the fact that a call has been optimized so we only do the
  1442. // effort once.
  1443. if (!OCS.count(CallI)) {
  1444. while (optimizeEdges(CallI->path, SM, OCS, LCM)) {}
  1445. OCS.insert(CallI);
  1446. }
  1447. ++I;
  1448. continue;
  1449. }
  1450. // Pattern match the current piece and its successor.
  1451. auto *PieceI = dyn_cast<PathDiagnosticControlFlowPiece>(I->get());
  1452. if (!PieceI) {
  1453. ++I;
  1454. continue;
  1455. }
  1456. const Stmt *s1Start = PieceI->getStartLocation().getStmtOrNull();
  1457. const Stmt *s1End = PieceI->getEndLocation().getStmtOrNull();
  1458. const Stmt *level1 = getStmtParent(s1Start, PM);
  1459. const Stmt *level2 = getStmtParent(s1End, PM);
  1460. PathPieces::iterator NextI = I; ++NextI;
  1461. if (NextI == E)
  1462. break;
  1463. const auto *PieceNextI = dyn_cast<PathDiagnosticControlFlowPiece>(NextI->get());
  1464. if (!PieceNextI) {
  1465. ++I;
  1466. continue;
  1467. }
  1468. const Stmt *s2Start = PieceNextI->getStartLocation().getStmtOrNull();
  1469. const Stmt *s2End = PieceNextI->getEndLocation().getStmtOrNull();
  1470. const Stmt *level3 = getStmtParent(s2Start, PM);
  1471. const Stmt *level4 = getStmtParent(s2End, PM);
  1472. // Rule I.
  1473. //
  1474. // If we have two consecutive control edges whose end/begin locations
  1475. // are at the same level (e.g. statements or top-level expressions within
  1476. // a compound statement, or siblings share a single ancestor expression),
  1477. // then merge them if they have no interesting intermediate event.
  1478. //
  1479. // For example:
  1480. //
  1481. // (1.1 -> 1.2) -> (1.2 -> 1.3) becomes (1.1 -> 1.3) because the common
  1482. // parent is '1'. Here 'x.y.z' represents the hierarchy of statements.
  1483. //
  1484. // NOTE: this will be limited later in cases where we add barriers
  1485. // to prevent this optimization.
  1486. if (level1 && level1 == level2 && level1 == level3 && level1 == level4) {
  1487. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1488. path.erase(NextI);
  1489. hasChanges = true;
  1490. continue;
  1491. }
  1492. // Rule II.
  1493. //
  1494. // Eliminate edges between subexpressions and parent expressions
  1495. // when the subexpression is consumed.
  1496. //
  1497. // NOTE: this will be limited later in cases where we add barriers
  1498. // to prevent this optimization.
  1499. if (s1End && s1End == s2Start && level2) {
  1500. bool removeEdge = false;
  1501. // Remove edges into the increment or initialization of a
  1502. // loop that have no interleaving event. This means that
  1503. // they aren't interesting.
  1504. if (isIncrementOrInitInForLoop(s1End, level2))
  1505. removeEdge = true;
  1506. // Next only consider edges that are not anchored on
  1507. // the condition of a terminator. This are intermediate edges
  1508. // that we might want to trim.
  1509. else if (!isConditionForTerminator(level2, s1End)) {
  1510. // Trim edges on expressions that are consumed by
  1511. // the parent expression.
  1512. if (isa<Expr>(s1End) && PM.isConsumedExpr(cast<Expr>(s1End))) {
  1513. removeEdge = true;
  1514. }
  1515. // Trim edges where a lexical containment doesn't exist.
  1516. // For example:
  1517. //
  1518. // X -> Y -> Z
  1519. //
  1520. // If 'Z' lexically contains Y (it is an ancestor) and
  1521. // 'X' does not lexically contain Y (it is a descendant OR
  1522. // it has no lexical relationship at all) then trim.
  1523. //
  1524. // This can eliminate edges where we dive into a subexpression
  1525. // and then pop back out, etc.
  1526. else if (s1Start && s2End &&
  1527. lexicalContains(PM, s2Start, s2End) &&
  1528. !lexicalContains(PM, s1End, s1Start)) {
  1529. removeEdge = true;
  1530. }
  1531. // Trim edges from a subexpression back to the top level if the
  1532. // subexpression is on a different line.
  1533. //
  1534. // A.1 -> A -> B
  1535. // becomes
  1536. // A.1 -> B
  1537. //
  1538. // These edges just look ugly and don't usually add anything.
  1539. else if (s1Start && s2End &&
  1540. lexicalContains(PM, s1Start, s1End)) {
  1541. SourceRange EdgeRange(PieceI->getEndLocation().asLocation(),
  1542. PieceI->getStartLocation().asLocation());
  1543. if (!getLengthOnSingleLine(SM, EdgeRange).hasValue())
  1544. removeEdge = true;
  1545. }
  1546. }
  1547. if (removeEdge) {
  1548. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1549. path.erase(NextI);
  1550. hasChanges = true;
  1551. continue;
  1552. }
  1553. }
  1554. // Optimize edges for ObjC fast-enumeration loops.
  1555. //
  1556. // (X -> collection) -> (collection -> element)
  1557. //
  1558. // becomes:
  1559. //
  1560. // (X -> element)
  1561. if (s1End == s2Start) {
  1562. const auto *FS = dyn_cast_or_null<ObjCForCollectionStmt>(level3);
  1563. if (FS && FS->getCollection()->IgnoreParens() == s2Start &&
  1564. s2End == FS->getElement()) {
  1565. PieceI->setEndLocation(PieceNextI->getEndLocation());
  1566. path.erase(NextI);
  1567. hasChanges = true;
  1568. continue;
  1569. }
  1570. }
  1571. // No changes at this index? Move to the next one.
  1572. ++I;
  1573. }
  1574. if (!hasChanges) {
  1575. // Adjust edges into subexpressions to make them more uniform
  1576. // and aesthetically pleasing.
  1577. addContextEdges(path, SM, PM, LC);
  1578. // Remove "cyclical" edges that include one or more context edges.
  1579. removeContextCycles(path, SM);
  1580. // Hoist edges originating from branch conditions to branches
  1581. // for simple branches.
  1582. simplifySimpleBranches(path);
  1583. // Remove any puny edges left over after primary optimization pass.
  1584. removePunyEdges(path, SM, PM);
  1585. // Remove identical events.
  1586. removeIdenticalEvents(path);
  1587. }
  1588. return hasChanges;
  1589. }
  1590. /// Drop the very first edge in a path, which should be a function entry edge.
  1591. ///
  1592. /// If the first edge is not a function entry edge (say, because the first
  1593. /// statement had an invalid source location), this function does nothing.
  1594. // FIXME: We should just generate invalid edges anyway and have the optimizer
  1595. // deal with them.
  1596. static void dropFunctionEntryEdge(PathPieces &Path, LocationContextMap &LCM,
  1597. SourceManager &SM) {
  1598. const auto *FirstEdge =
  1599. dyn_cast<PathDiagnosticControlFlowPiece>(Path.front().get());
  1600. if (!FirstEdge)
  1601. return;
  1602. const Decl *D = LCM[&Path]->getDecl();
  1603. PathDiagnosticLocation EntryLoc = PathDiagnosticLocation::createBegin(D, SM);
  1604. if (FirstEdge->getStartLocation() != EntryLoc)
  1605. return;
  1606. Path.pop_front();
  1607. }
  1608. using VisitorsDiagnosticsTy = llvm::DenseMap<const ExplodedNode *,
  1609. std::vector<std::shared_ptr<PathDiagnosticPiece>>>;
  1610. /// Populate executes lines with lines containing at least one diagnostics.
  1611. static void updateExecutedLinesWithDiagnosticPieces(
  1612. PathDiagnostic &PD) {
  1613. PathPieces path = PD.path.flatten(/*ShouldFlattenMacros=*/true);
  1614. FilesToLineNumsMap &ExecutedLines = PD.getExecutedLines();
  1615. for (const auto &P : path) {
  1616. FullSourceLoc Loc = P->getLocation().asLocation().getExpansionLoc();
  1617. FileID FID = Loc.getFileID();
  1618. unsigned LineNo = Loc.getLineNumber();
  1619. assert(FID.isValid());
  1620. ExecutedLines[FID].insert(LineNo);
  1621. }
  1622. }
  1623. /// This function is responsible for generating diagnostic pieces that are
  1624. /// *not* provided by bug report visitors.
  1625. /// These diagnostics may differ depending on the consumer's settings,
  1626. /// and are therefore constructed separately for each consumer.
  1627. ///
  1628. /// There are two path diagnostics generation modes: with adding edges (used
  1629. /// for plists) and without (used for HTML and text).
  1630. /// When edges are added (\p ActiveScheme is Extensive),
  1631. /// the path is modified to insert artificially generated
  1632. /// edges.
  1633. /// Otherwise, more detailed diagnostics is emitted for block edges, explaining
  1634. /// the transitions in words.
  1635. static std::unique_ptr<PathDiagnostic> generatePathDiagnosticForConsumer(
  1636. PathDiagnosticConsumer::PathGenerationScheme ActiveScheme,
  1637. PathDiagnosticBuilder &PDB,
  1638. const ExplodedNode *ErrorNode,
  1639. const VisitorsDiagnosticsTy &VisitorsDiagnostics) {
  1640. bool GenerateDiagnostics = (ActiveScheme != PathDiagnosticConsumer::None);
  1641. bool AddPathEdges = (ActiveScheme == PathDiagnosticConsumer::Extensive);
  1642. SourceManager &SM = PDB.getSourceManager();
  1643. BugReport *R = PDB.getBugReport();
  1644. AnalyzerOptions &Opts = PDB.getBugReporter().getAnalyzerOptions();
  1645. StackDiagVector CallStack;
  1646. InterestingExprs IE;
  1647. LocationContextMap LCM;
  1648. std::unique_ptr<PathDiagnostic> PD = generateEmptyDiagnosticForReport(R, SM);
  1649. if (GenerateDiagnostics) {
  1650. auto EndNotes = VisitorsDiagnostics.find(ErrorNode);
  1651. std::shared_ptr<PathDiagnosticPiece> LastPiece;
  1652. if (EndNotes != VisitorsDiagnostics.end()) {
  1653. assert(!EndNotes->second.empty());
  1654. LastPiece = EndNotes->second[0];
  1655. } else {
  1656. LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, ErrorNode, *R);
  1657. }
  1658. PD->setEndOfPath(LastPiece);
  1659. }
  1660. PathDiagnosticLocation PrevLoc = PD->getLocation();
  1661. const ExplodedNode *NextNode = ErrorNode->getFirstPred();
  1662. while (NextNode) {
  1663. if (GenerateDiagnostics)
  1664. generatePathDiagnosticsForNode(
  1665. NextNode, *PD, PrevLoc, PDB, LCM, CallStack, IE, AddPathEdges);
  1666. auto VisitorNotes = VisitorsDiagnostics.find(NextNode);
  1667. NextNode = NextNode->getFirstPred();
  1668. if (!GenerateDiagnostics || VisitorNotes == VisitorsDiagnostics.end())
  1669. continue;
  1670. // This is a workaround due to inability to put shared PathDiagnosticPiece
  1671. // into a FoldingSet.
  1672. std::set<llvm::FoldingSetNodeID> DeduplicationSet;
  1673. // Add pieces from custom visitors.
  1674. for (const auto &Note : VisitorNotes->second) {
  1675. llvm::FoldingSetNodeID ID;
  1676. Note->Profile(ID);
  1677. auto P = DeduplicationSet.insert(ID);
  1678. if (!P.second)
  1679. continue;
  1680. if (AddPathEdges)
  1681. addEdgeToPath(PD->getActivePath(), PrevLoc, Note->getLocation());
  1682. updateStackPiecesWithMessage(*Note, CallStack);
  1683. PD->getActivePath().push_front(Note);
  1684. }
  1685. }
  1686. if (AddPathEdges) {
  1687. // Add an edge to the start of the function.
  1688. // We'll prune it out later, but it helps make diagnostics more uniform.
  1689. const StackFrameContext *CalleeLC = PDB.LC->getStackFrame();
  1690. const Decl *D = CalleeLC->getDecl();
  1691. addEdgeToPath(PD->getActivePath(), PrevLoc,
  1692. PathDiagnosticLocation::createBegin(D, SM));
  1693. }
  1694. // Finally, prune the diagnostic path of uninteresting stuff.
  1695. if (!PD->path.empty()) {
  1696. if (R->shouldPrunePath() && Opts.ShouldPrunePaths) {
  1697. bool stillHasNotes =
  1698. removeUnneededCalls(PD->getMutablePieces(), R, LCM);
  1699. assert(stillHasNotes);
  1700. (void)stillHasNotes;
  1701. }
  1702. // Redirect all call pieces to have valid locations.
  1703. adjustCallLocations(PD->getMutablePieces());
  1704. removePiecesWithInvalidLocations(PD->getMutablePieces());
  1705. if (AddPathEdges) {
  1706. // Reduce the number of edges from a very conservative set
  1707. // to an aesthetically pleasing subset that conveys the
  1708. // necessary information.
  1709. OptimizedCallsSet OCS;
  1710. while (optimizeEdges(PD->getMutablePieces(), SM, OCS, LCM)) {}
  1711. // Drop the very first function-entry edge. It's not really necessary
  1712. // for top-level functions.
  1713. dropFunctionEntryEdge(PD->getMutablePieces(), LCM, SM);
  1714. }
  1715. // Remove messages that are basically the same, and edges that may not
  1716. // make sense.
  1717. // We have to do this after edge optimization in the Extensive mode.
  1718. removeRedundantMsgs(PD->getMutablePieces());
  1719. removeEdgesToDefaultInitializers(PD->getMutablePieces());
  1720. }
  1721. if (GenerateDiagnostics && Opts.ShouldDisplayMacroExpansions)
  1722. CompactMacroExpandedPieces(PD->getMutablePieces(), SM);
  1723. return PD;
  1724. }
  1725. //===----------------------------------------------------------------------===//
  1726. // Methods for BugType and subclasses.
  1727. //===----------------------------------------------------------------------===//
  1728. void BugType::anchor() {}
  1729. void BuiltinBug::anchor() {}
  1730. //===----------------------------------------------------------------------===//
  1731. // Methods for BugReport and subclasses.
  1732. //===----------------------------------------------------------------------===//
  1733. void BugReport::NodeResolver::anchor() {}
  1734. void BugReport::addVisitor(std::unique_ptr<BugReporterVisitor> visitor) {
  1735. if (!visitor)
  1736. return;
  1737. llvm::FoldingSetNodeID ID;
  1738. visitor->Profile(ID);
  1739. void *InsertPos = nullptr;
  1740. if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
  1741. return;
  1742. }
  1743. Callbacks.push_back(std::move(visitor));
  1744. }
  1745. void BugReport::clearVisitors() {
  1746. Callbacks.clear();
  1747. }
  1748. BugReport::~BugReport() {
  1749. while (!interestingSymbols.empty()) {
  1750. popInterestingSymbolsAndRegions();
  1751. }
  1752. }
  1753. const Decl *BugReport::getDeclWithIssue() const {
  1754. if (DeclWithIssue)
  1755. return DeclWithIssue;
  1756. const ExplodedNode *N = getErrorNode();
  1757. if (!N)
  1758. return nullptr;
  1759. const LocationContext *LC = N->getLocationContext();
  1760. return LC->getStackFrame()->getDecl();
  1761. }
  1762. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  1763. hash.AddPointer(&BT);
  1764. hash.AddString(Description);
  1765. PathDiagnosticLocation UL = getUniqueingLocation();
  1766. if (UL.isValid()) {
  1767. UL.Profile(hash);
  1768. } else if (Location.isValid()) {
  1769. Location.Profile(hash);
  1770. } else {
  1771. assert(ErrorNode);
  1772. hash.AddPointer(GetCurrentOrPreviousStmt(ErrorNode));
  1773. }
  1774. for (SourceRange range : Ranges) {
  1775. if (!range.isValid())
  1776. continue;
  1777. hash.AddInteger(range.getBegin().getRawEncoding());
  1778. hash.AddInteger(range.getEnd().getRawEncoding());
  1779. }
  1780. }
  1781. void BugReport::markInteresting(SymbolRef sym) {
  1782. if (!sym)
  1783. return;
  1784. getInterestingSymbols().insert(sym);
  1785. if (const auto *meta = dyn_cast<SymbolMetadata>(sym))
  1786. getInterestingRegions().insert(meta->getRegion());
  1787. }
  1788. void BugReport::markInteresting(const MemRegion *R) {
  1789. if (!R)
  1790. return;
  1791. R = R->getBaseRegion();
  1792. getInterestingRegions().insert(R);
  1793. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1794. getInterestingSymbols().insert(SR->getSymbol());
  1795. }
  1796. void BugReport::markInteresting(SVal V) {
  1797. markInteresting(V.getAsRegion());
  1798. markInteresting(V.getAsSymbol());
  1799. }
  1800. void BugReport::markInteresting(const LocationContext *LC) {
  1801. if (!LC)
  1802. return;
  1803. InterestingLocationContexts.insert(LC);
  1804. }
  1805. bool BugReport::isInteresting(SVal V) {
  1806. return isInteresting(V.getAsRegion()) || isInteresting(V.getAsSymbol());
  1807. }
  1808. bool BugReport::isInteresting(SymbolRef sym) {
  1809. if (!sym)
  1810. return false;
  1811. // We don't currently consider metadata symbols to be interesting
  1812. // even if we know their region is interesting. Is that correct behavior?
  1813. return getInterestingSymbols().count(sym);
  1814. }
  1815. bool BugReport::isInteresting(const MemRegion *R) {
  1816. if (!R)
  1817. return false;
  1818. R = R->getBaseRegion();
  1819. bool b = getInterestingRegions().count(R);
  1820. if (b)
  1821. return true;
  1822. if (const auto *SR = dyn_cast<SymbolicRegion>(R))
  1823. return getInterestingSymbols().count(SR->getSymbol());
  1824. return false;
  1825. }
  1826. bool BugReport::isInteresting(const LocationContext *LC) {
  1827. if (!LC)
  1828. return false;
  1829. return InterestingLocationContexts.count(LC);
  1830. }
  1831. void BugReport::lazyInitializeInterestingSets() {
  1832. if (interestingSymbols.empty()) {
  1833. interestingSymbols.push_back(new Symbols());
  1834. interestingRegions.push_back(new Regions());
  1835. }
  1836. }
  1837. BugReport::Symbols &BugReport::getInterestingSymbols() {
  1838. lazyInitializeInterestingSets();
  1839. return *interestingSymbols.back();
  1840. }
  1841. BugReport::Regions &BugReport::getInterestingRegions() {
  1842. lazyInitializeInterestingSets();
  1843. return *interestingRegions.back();
  1844. }
  1845. void BugReport::pushInterestingSymbolsAndRegions() {
  1846. interestingSymbols.push_back(new Symbols(getInterestingSymbols()));
  1847. interestingRegions.push_back(new Regions(getInterestingRegions()));
  1848. }
  1849. void BugReport::popInterestingSymbolsAndRegions() {
  1850. delete interestingSymbols.pop_back_val();
  1851. delete interestingRegions.pop_back_val();
  1852. }
  1853. const Stmt *BugReport::getStmt() const {
  1854. if (!ErrorNode)
  1855. return nullptr;
  1856. ProgramPoint ProgP = ErrorNode->getLocation();
  1857. const Stmt *S = nullptr;
  1858. if (Optional<BlockEntrance> BE = ProgP.getAs<BlockEntrance>()) {
  1859. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  1860. if (BE->getBlock() == &Exit)
  1861. S = GetPreviousStmt(ErrorNode);
  1862. }
  1863. if (!S)
  1864. S = PathDiagnosticLocation::getStmt(ErrorNode);
  1865. return S;
  1866. }
  1867. llvm::iterator_range<BugReport::ranges_iterator> BugReport::getRanges() {
  1868. // If no custom ranges, add the range of the statement corresponding to
  1869. // the error node.
  1870. if (Ranges.empty()) {
  1871. if (const auto *E = dyn_cast_or_null<Expr>(getStmt()))
  1872. addRange(E->getSourceRange());
  1873. else
  1874. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1875. }
  1876. // User-specified absence of range info.
  1877. if (Ranges.size() == 1 && !Ranges.begin()->isValid())
  1878. return llvm::make_range(ranges_iterator(), ranges_iterator());
  1879. return llvm::make_range(Ranges.begin(), Ranges.end());
  1880. }
  1881. PathDiagnosticLocation BugReport::getLocation(const SourceManager &SM) const {
  1882. if (ErrorNode) {
  1883. assert(!Location.isValid() &&
  1884. "Either Location or ErrorNode should be specified but not both.");
  1885. return PathDiagnosticLocation::createEndOfPath(ErrorNode, SM);
  1886. }
  1887. assert(Location.isValid());
  1888. return Location;
  1889. }
  1890. //===----------------------------------------------------------------------===//
  1891. // Methods for BugReporter and subclasses.
  1892. //===----------------------------------------------------------------------===//
  1893. BugReportEquivClass::~BugReportEquivClass() = default;
  1894. GRBugReporter::~GRBugReporter() = default;
  1895. BugReporterData::~BugReporterData() = default;
  1896. ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
  1897. ProgramStateManager&
  1898. GRBugReporter::getStateManager() { return Eng.getStateManager(); }
  1899. BugReporter::~BugReporter() {
  1900. FlushReports();
  1901. // Free the bug reports we are tracking.
  1902. for (const auto I : EQClassesVector)
  1903. delete I;
  1904. }
  1905. void BugReporter::FlushReports() {
  1906. if (BugTypes.isEmpty())
  1907. return;
  1908. // We need to flush reports in deterministic order to ensure the order
  1909. // of the reports is consistent between runs.
  1910. for (const auto EQ : EQClassesVector)
  1911. FlushReport(*EQ);
  1912. // BugReporter owns and deletes only BugTypes created implicitly through
  1913. // EmitBasicReport.
  1914. // FIXME: There are leaks from checkers that assume that the BugTypes they
  1915. // create will be destroyed by the BugReporter.
  1916. llvm::DeleteContainerSeconds(StrBugTypes);
  1917. // Remove all references to the BugType objects.
  1918. BugTypes = F.getEmptySet();
  1919. }
  1920. //===----------------------------------------------------------------------===//
  1921. // PathDiagnostics generation.
  1922. //===----------------------------------------------------------------------===//
  1923. namespace {
  1924. /// A wrapper around a report graph, which contains only a single path, and its
  1925. /// node maps.
  1926. class ReportGraph {
  1927. public:
  1928. InterExplodedGraphMap BackMap;
  1929. std::unique_ptr<ExplodedGraph> Graph;
  1930. const ExplodedNode *ErrorNode;
  1931. size_t Index;
  1932. };
  1933. /// A wrapper around a trimmed graph and its node maps.
  1934. class TrimmedGraph {
  1935. InterExplodedGraphMap InverseMap;
  1936. using PriorityMapTy = llvm::DenseMap<const ExplodedNode *, unsigned>;
  1937. PriorityMapTy PriorityMap;
  1938. using NodeIndexPair = std::pair<const ExplodedNode *, size_t>;
  1939. SmallVector<NodeIndexPair, 32> ReportNodes;
  1940. std::unique_ptr<ExplodedGraph> G;
  1941. /// A helper class for sorting ExplodedNodes by priority.
  1942. template <bool Descending>
  1943. class PriorityCompare {
  1944. const PriorityMapTy &PriorityMap;
  1945. public:
  1946. PriorityCompare(const PriorityMapTy &M) : PriorityMap(M) {}
  1947. bool operator()(const ExplodedNode *LHS, const ExplodedNode *RHS) const {
  1948. PriorityMapTy::const_iterator LI = PriorityMap.find(LHS);
  1949. PriorityMapTy::const_iterator RI = PriorityMap.find(RHS);
  1950. PriorityMapTy::const_iterator E = PriorityMap.end();
  1951. if (LI == E)
  1952. return Descending;
  1953. if (RI == E)
  1954. return !Descending;
  1955. return Descending ? LI->second > RI->second
  1956. : LI->second < RI->second;
  1957. }
  1958. bool operator()(const NodeIndexPair &LHS, const NodeIndexPair &RHS) const {
  1959. return (*this)(LHS.first, RHS.first);
  1960. }
  1961. };
  1962. public:
  1963. TrimmedGraph(const ExplodedGraph *OriginalGraph,
  1964. ArrayRef<const ExplodedNode *> Nodes);
  1965. bool popNextReportGraph(ReportGraph &GraphWrapper);
  1966. };
  1967. } // namespace
  1968. TrimmedGraph::TrimmedGraph(const ExplodedGraph *OriginalGraph,
  1969. ArrayRef<const ExplodedNode *> Nodes) {
  1970. // The trimmed graph is created in the body of the constructor to ensure
  1971. // that the DenseMaps have been initialized already.
  1972. InterExplodedGraphMap ForwardMap;
  1973. G = OriginalGraph->trim(Nodes, &ForwardMap, &InverseMap);
  1974. // Find the (first) error node in the trimmed graph. We just need to consult
  1975. // the node map which maps from nodes in the original graph to nodes
  1976. // in the new graph.
  1977. llvm::SmallPtrSet<const ExplodedNode *, 32> RemainingNodes;
  1978. for (unsigned i = 0, count = Nodes.size(); i < count; ++i) {
  1979. if (const ExplodedNode *NewNode = ForwardMap.lookup(Nodes[i])) {
  1980. ReportNodes.push_back(std::make_pair(NewNode, i));
  1981. RemainingNodes.insert(NewNode);
  1982. }
  1983. }
  1984. assert(!RemainingNodes.empty() && "No error node found in the trimmed graph");
  1985. // Perform a forward BFS to find all the shortest paths.
  1986. std::queue<const ExplodedNode *> WS;
  1987. assert(G->num_roots() == 1);
  1988. WS.push(*G->roots_begin());
  1989. unsigned Priority = 0;
  1990. while (!WS.empty()) {
  1991. const ExplodedNode *Node = WS.front();
  1992. WS.pop();
  1993. PriorityMapTy::iterator PriorityEntry;
  1994. bool IsNew;
  1995. std::tie(PriorityEntry, IsNew) =
  1996. PriorityMap.insert(std::make_pair(Node, Priority));
  1997. ++Priority;
  1998. if (!IsNew) {
  1999. assert(PriorityEntry->second <= Priority);
  2000. continue;
  2001. }
  2002. if (RemainingNodes.erase(Node))
  2003. if (RemainingNodes.empty())
  2004. break;
  2005. for (ExplodedNode::const_pred_iterator I = Node->succ_begin(),
  2006. E = Node->succ_end();
  2007. I != E; ++I)
  2008. WS.push(*I);
  2009. }
  2010. // Sort the error paths from longest to shortest.
  2011. llvm::sort(ReportNodes, PriorityCompare<true>(PriorityMap));
  2012. }
  2013. bool TrimmedGraph::popNextReportGraph(ReportGraph &GraphWrapper) {
  2014. if (ReportNodes.empty())
  2015. return false;
  2016. const ExplodedNode *OrigN;
  2017. std::tie(OrigN, GraphWrapper.Index) = ReportNodes.pop_back_val();
  2018. assert(PriorityMap.find(OrigN) != PriorityMap.end() &&
  2019. "error node not accessible from root");
  2020. // Create a new graph with a single path. This is the graph
  2021. // that will be returned to the caller.
  2022. auto GNew = llvm::make_unique<ExplodedGraph>();
  2023. GraphWrapper.BackMap.clear();
  2024. // Now walk from the error node up the BFS path, always taking the
  2025. // predeccessor with the lowest number.
  2026. ExplodedNode *Succ = nullptr;
  2027. while (true) {
  2028. // Create the equivalent node in the new graph with the same state
  2029. // and location.
  2030. ExplodedNode *NewN = GNew->createUncachedNode(OrigN->getLocation(), OrigN->getState(),
  2031. OrigN->isSink());
  2032. // Store the mapping to the original node.
  2033. InterExplodedGraphMap::const_iterator IMitr = InverseMap.find(OrigN);
  2034. assert(IMitr != InverseMap.end() && "No mapping to original node.");
  2035. GraphWrapper.BackMap[NewN] = IMitr->second;
  2036. // Link up the new node with the previous node.
  2037. if (Succ)
  2038. Succ->addPredecessor(NewN, *GNew);
  2039. else
  2040. GraphWrapper.ErrorNode = NewN;
  2041. Succ = NewN;
  2042. // Are we at the final node?
  2043. if (OrigN->pred_empty()) {
  2044. GNew->addRoot(NewN);
  2045. break;
  2046. }
  2047. // Find the next predeccessor node. We choose the node that is marked
  2048. // with the lowest BFS number.
  2049. OrigN = *std::min_element(OrigN->pred_begin(), OrigN->pred_end(),
  2050. PriorityCompare<false>(PriorityMap));
  2051. }
  2052. GraphWrapper.Graph = std::move(GNew);
  2053. return true;
  2054. }
  2055. /// CompactMacroExpandedPieces - This function postprocesses a PathDiagnostic
  2056. /// object and collapses PathDiagosticPieces that are expanded by macros.
  2057. static void CompactMacroExpandedPieces(PathPieces &path,
  2058. const SourceManager& SM) {
  2059. using MacroStackTy =
  2060. std::vector<
  2061. std::pair<std::shared_ptr<PathDiagnosticMacroPiece>, SourceLocation>>;
  2062. using PiecesTy = std::vector<std::shared_ptr<PathDiagnosticPiece>>;
  2063. MacroStackTy MacroStack;
  2064. PiecesTy Pieces;
  2065. for (PathPieces::const_iterator I = path.begin(), E = path.end();
  2066. I != E; ++I) {
  2067. const auto &piece = *I;
  2068. // Recursively compact calls.
  2069. if (auto *call = dyn_cast<PathDiagnosticCallPiece>(&*piece)) {
  2070. CompactMacroExpandedPieces(call->path, SM);
  2071. }
  2072. // Get the location of the PathDiagnosticPiece.
  2073. const FullSourceLoc Loc = piece->getLocation().asLocation();
  2074. // Determine the instantiation location, which is the location we group
  2075. // related PathDiagnosticPieces.
  2076. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  2077. SM.getExpansionLoc(Loc) :
  2078. SourceLocation();
  2079. if (Loc.isFileID()) {
  2080. MacroStack.clear();
  2081. Pieces.push_back(piece);
  2082. continue;
  2083. }
  2084. assert(Loc.isMacroID());
  2085. // Is the PathDiagnosticPiece within the same macro group?
  2086. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  2087. MacroStack.back().first->subPieces.push_back(piece);
  2088. continue;
  2089. }
  2090. // We aren't in the same group. Are we descending into a new macro
  2091. // or are part of an old one?
  2092. std::shared_ptr<PathDiagnosticMacroPiece> MacroGroup;
  2093. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  2094. SM.getExpansionLoc(Loc) :
  2095. SourceLocation();
  2096. // Walk the entire macro stack.
  2097. while (!MacroStack.empty()) {
  2098. if (InstantiationLoc == MacroStack.back().second) {
  2099. MacroGroup = MacroStack.back().first;
  2100. break;
  2101. }
  2102. if (ParentInstantiationLoc == MacroStack.back().second) {
  2103. MacroGroup = MacroStack.back().first;
  2104. break;
  2105. }
  2106. MacroStack.pop_back();
  2107. }
  2108. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  2109. // Create a new macro group and add it to the stack.
  2110. auto NewGroup = std::make_shared<PathDiagnosticMacroPiece>(
  2111. PathDiagnosticLocation::createSingleLocation(piece->getLocation()));
  2112. if (MacroGroup)
  2113. MacroGroup->subPieces.push_back(NewGroup);
  2114. else {
  2115. assert(InstantiationLoc.isFileID());
  2116. Pieces.push_back(NewGroup);
  2117. }
  2118. MacroGroup = NewGroup;
  2119. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  2120. }
  2121. // Finally, add the PathDiagnosticPiece to the group.
  2122. MacroGroup->subPieces.push_back(piece);
  2123. }
  2124. // Now take the pieces and construct a new PathDiagnostic.
  2125. path.clear();
  2126. path.insert(path.end(), Pieces.begin(), Pieces.end());
  2127. }
  2128. /// Generate notes from all visitors.
  2129. /// Notes associated with {@code ErrorNode} are generated using
  2130. /// {@code getEndPath}, and the rest are generated with {@code VisitNode}.
  2131. static std::unique_ptr<VisitorsDiagnosticsTy>
  2132. generateVisitorsDiagnostics(BugReport *R, const ExplodedNode *ErrorNode,
  2133. BugReporterContext &BRC) {
  2134. auto Notes = llvm::make_unique<VisitorsDiagnosticsTy>();
  2135. BugReport::VisitorList visitors;
  2136. // Run visitors on all nodes starting from the node *before* the last one.
  2137. // The last node is reserved for notes generated with {@code getEndPath}.
  2138. const ExplodedNode *NextNode = ErrorNode->getFirstPred();
  2139. while (NextNode) {
  2140. // At each iteration, move all visitors from report to visitor list.
  2141. for (BugReport::visitor_iterator I = R->visitor_begin(),
  2142. E = R->visitor_end();
  2143. I != E; ++I) {
  2144. visitors.push_back(std::move(*I));
  2145. }
  2146. R->clearVisitors();
  2147. const ExplodedNode *Pred = NextNode->getFirstPred();
  2148. if (!Pred) {
  2149. std::shared_ptr<PathDiagnosticPiece> LastPiece;
  2150. for (auto &V : visitors) {
  2151. V->finalizeVisitor(BRC, ErrorNode, *R);
  2152. if (auto Piece = V->getEndPath(BRC, ErrorNode, *R)) {
  2153. assert(!LastPiece &&
  2154. "There can only be one final piece in a diagnostic.");
  2155. LastPiece = std::move(Piece);
  2156. (*Notes)[ErrorNode].push_back(LastPiece);
  2157. }
  2158. }
  2159. break;
  2160. }
  2161. for (auto &V : visitors) {
  2162. auto P = V->VisitNode(NextNode, BRC, *R);
  2163. if (P)
  2164. (*Notes)[NextNode].push_back(std::move(P));
  2165. }
  2166. if (!R->isValid())
  2167. break;
  2168. NextNode = Pred;
  2169. }
  2170. return Notes;
  2171. }
  2172. /// Find a non-invalidated report for a given equivalence class,
  2173. /// and return together with a cache of visitors notes.
  2174. /// If none found, return a nullptr paired with an empty cache.
  2175. static
  2176. std::pair<BugReport*, std::unique_ptr<VisitorsDiagnosticsTy>> findValidReport(
  2177. TrimmedGraph &TrimG,
  2178. ReportGraph &ErrorGraph,
  2179. ArrayRef<BugReport *> &bugReports,
  2180. AnalyzerOptions &Opts,
  2181. GRBugReporter &Reporter) {
  2182. while (TrimG.popNextReportGraph(ErrorGraph)) {
  2183. // Find the BugReport with the original location.
  2184. assert(ErrorGraph.Index < bugReports.size());
  2185. BugReport *R = bugReports[ErrorGraph.Index];
  2186. assert(R && "No original report found for sliced graph.");
  2187. assert(R->isValid() && "Report selected by trimmed graph marked invalid.");
  2188. const ExplodedNode *ErrorNode = ErrorGraph.ErrorNode;
  2189. // Register refutation visitors first, if they mark the bug invalid no
  2190. // further analysis is required
  2191. R->addVisitor(llvm::make_unique<LikelyFalsePositiveSuppressionBRVisitor>());
  2192. // Register additional node visitors.
  2193. R->addVisitor(llvm::make_unique<NilReceiverBRVisitor>());
  2194. R->addVisitor(llvm::make_unique<ConditionBRVisitor>());
  2195. R->addVisitor(llvm::make_unique<CXXSelfAssignmentBRVisitor>());
  2196. R->addVisitor(llvm::make_unique<TagVisitor>());
  2197. BugReporterContext BRC(Reporter, ErrorGraph.BackMap);
  2198. // Run all visitors on a given graph, once.
  2199. std::unique_ptr<VisitorsDiagnosticsTy> visitorNotes =
  2200. generateVisitorsDiagnostics(R, ErrorNode, BRC);
  2201. if (R->isValid()) {
  2202. if (Opts.ShouldCrosscheckWithZ3) {
  2203. // If crosscheck is enabled, remove all visitors, add the refutation
  2204. // visitor and check again
  2205. R->clearVisitors();
  2206. R->addVisitor(llvm::make_unique<FalsePositiveRefutationBRVisitor>());
  2207. // We don't overrite the notes inserted by other visitors because the
  2208. // refutation manager does not add any new note to the path
  2209. generateVisitorsDiagnostics(R, ErrorGraph.ErrorNode, BRC);
  2210. }
  2211. // Check if the bug is still valid
  2212. if (R->isValid())
  2213. return std::make_pair(R, std::move(visitorNotes));
  2214. }
  2215. }
  2216. return std::make_pair(nullptr, llvm::make_unique<VisitorsDiagnosticsTy>());
  2217. }
  2218. std::unique_ptr<DiagnosticForConsumerMapTy>
  2219. GRBugReporter::generatePathDiagnostics(
  2220. ArrayRef<PathDiagnosticConsumer *> consumers,
  2221. ArrayRef<BugReport *> &bugReports) {
  2222. assert(!bugReports.empty());
  2223. auto Out = llvm::make_unique<DiagnosticForConsumerMapTy>();
  2224. bool HasValid = false;
  2225. SmallVector<const ExplodedNode *, 32> errorNodes;
  2226. for (const auto I : bugReports) {
  2227. if (I->isValid()) {
  2228. HasValid = true;
  2229. errorNodes.push_back(I->getErrorNode());
  2230. } else {
  2231. // Keep the errorNodes list in sync with the bugReports list.
  2232. errorNodes.push_back(nullptr);
  2233. }
  2234. }
  2235. // If all the reports have been marked invalid by a previous path generation,
  2236. // we're done.
  2237. if (!HasValid)
  2238. return Out;
  2239. TrimmedGraph TrimG(&getGraph(), errorNodes);
  2240. ReportGraph ErrorGraph;
  2241. auto ReportInfo = findValidReport(TrimG, ErrorGraph, bugReports,
  2242. getAnalyzerOptions(), *this);
  2243. BugReport *R = ReportInfo.first;
  2244. if (R && R->isValid()) {
  2245. const ExplodedNode *ErrorNode = ErrorGraph.ErrorNode;
  2246. for (PathDiagnosticConsumer *PC : consumers) {
  2247. PathDiagnosticBuilder PDB(*this, R, ErrorGraph.BackMap, PC);
  2248. std::unique_ptr<PathDiagnostic> PD = generatePathDiagnosticForConsumer(
  2249. PC->getGenerationScheme(), PDB, ErrorNode, *ReportInfo.second);
  2250. (*Out)[PC] = std::move(PD);
  2251. }
  2252. }
  2253. return Out;
  2254. }
  2255. void BugReporter::Register(const BugType *BT) {
  2256. BugTypes = F.add(BugTypes, BT);
  2257. }
  2258. void BugReporter::emitReport(std::unique_ptr<BugReport> R) {
  2259. if (const ExplodedNode *E = R->getErrorNode()) {
  2260. // An error node must either be a sink or have a tag, otherwise
  2261. // it could get reclaimed before the path diagnostic is created.
  2262. assert((E->isSink() || E->getLocation().getTag()) &&
  2263. "Error node must either be a sink or have a tag");
  2264. const AnalysisDeclContext *DeclCtx =
  2265. E->getLocationContext()->getAnalysisDeclContext();
  2266. // The source of autosynthesized body can be handcrafted AST or a model
  2267. // file. The locations from handcrafted ASTs have no valid source locations
  2268. // and have to be discarded. Locations from model files should be preserved
  2269. // for processing and reporting.
  2270. if (DeclCtx->isBodyAutosynthesized() &&
  2271. !DeclCtx->isBodyAutosynthesizedFromModelFile())
  2272. return;
  2273. }
  2274. bool ValidSourceLoc = R->getLocation(getSourceManager()).isValid();
  2275. assert(ValidSourceLoc);
  2276. // If we mess up in a release build, we'd still prefer to just drop the bug
  2277. // instead of trying to go on.
  2278. if (!ValidSourceLoc)
  2279. return;
  2280. // Compute the bug report's hash to determine its equivalence class.
  2281. llvm::FoldingSetNodeID ID;
  2282. R->Profile(ID);
  2283. // Lookup the equivance class. If there isn't one, create it.
  2284. const BugType& BT = R->getBugType();
  2285. Register(&BT);
  2286. void *InsertPos;
  2287. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  2288. if (!EQ) {
  2289. EQ = new BugReportEquivClass(std::move(R));
  2290. EQClasses.InsertNode(EQ, InsertPos);
  2291. EQClassesVector.push_back(EQ);
  2292. } else
  2293. EQ->AddReport(std::move(R));
  2294. }
  2295. //===----------------------------------------------------------------------===//
  2296. // Emitting reports in equivalence classes.
  2297. //===----------------------------------------------------------------------===//
  2298. namespace {
  2299. struct FRIEC_WLItem {
  2300. const ExplodedNode *N;
  2301. ExplodedNode::const_succ_iterator I, E;
  2302. FRIEC_WLItem(const ExplodedNode *n)
  2303. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  2304. };
  2305. } // namespace
  2306. static const CFGBlock *findBlockForNode(const ExplodedNode *N) {
  2307. ProgramPoint P = N->getLocation();
  2308. if (auto BEP = P.getAs<BlockEntrance>())
  2309. return BEP->getBlock();
  2310. // Find the node's current statement in the CFG.
  2311. if (const Stmt *S = PathDiagnosticLocation::getStmt(N))
  2312. return N->getLocationContext()->getAnalysisDeclContext()
  2313. ->getCFGStmtMap()->getBlock(S);
  2314. return nullptr;
  2315. }
  2316. // Returns true if by simply looking at the block, we can be sure that it
  2317. // results in a sink during analysis. This is useful to know when the analysis
  2318. // was interrupted, and we try to figure out if it would sink eventually.
  2319. // There may be many more reasons why a sink would appear during analysis
  2320. // (eg. checkers may generate sinks arbitrarily), but here we only consider
  2321. // sinks that would be obvious by looking at the CFG.
  2322. static bool isImmediateSinkBlock(const CFGBlock *Blk) {
  2323. if (Blk->hasNoReturnElement())
  2324. return true;
  2325. // FIXME: Throw-expressions are currently generating sinks during analysis:
  2326. // they're not supported yet, and also often used for actually terminating
  2327. // the program. So we should treat them as sinks in this analysis as well,
  2328. // at least for now, but once we have better support for exceptions,
  2329. // we'd need to carefully handle the case when the throw is being
  2330. // immediately caught.
  2331. if (std::any_of(Blk->begin(), Blk->end(), [](const CFGElement &Elm) {
  2332. if (Optional<CFGStmt> StmtElm = Elm.getAs<CFGStmt>())
  2333. if (isa<CXXThrowExpr>(StmtElm->getStmt()))
  2334. return true;
  2335. return false;
  2336. }))
  2337. return true;
  2338. return false;
  2339. }
  2340. // Returns true if by looking at the CFG surrounding the node's program
  2341. // point, we can be sure that any analysis starting from this point would
  2342. // eventually end with a sink. We scan the child CFG blocks in a depth-first
  2343. // manner and see if all paths eventually end up in an immediate sink block.
  2344. static bool isInevitablySinking(const ExplodedNode *N) {
  2345. const CFG &Cfg = N->getCFG();
  2346. const CFGBlock *StartBlk = findBlockForNode(N);
  2347. if (!StartBlk)
  2348. return false;
  2349. if (isImmediateSinkBlock(StartBlk))
  2350. return true;
  2351. llvm::SmallVector<const CFGBlock *, 32> DFSWorkList;
  2352. llvm::SmallPtrSet<const CFGBlock *, 32> Visited;
  2353. DFSWorkList.push_back(StartBlk);
  2354. while (!DFSWorkList.empty()) {
  2355. const CFGBlock *Blk = DFSWorkList.back();
  2356. DFSWorkList.pop_back();
  2357. Visited.insert(Blk);
  2358. // If at least one path reaches the CFG exit, it means that control is
  2359. // returned to the caller. For now, say that we are not sure what
  2360. // happens next. If necessary, this can be improved to analyze
  2361. // the parent StackFrameContext's call site in a similar manner.
  2362. if (Blk == &Cfg.getExit())
  2363. return false;
  2364. for (const auto &Succ : Blk->succs()) {
  2365. if (const CFGBlock *SuccBlk = Succ.getReachableBlock()) {
  2366. if (!isImmediateSinkBlock(SuccBlk) && !Visited.count(SuccBlk)) {
  2367. // If the block has reachable child blocks that aren't no-return,
  2368. // add them to the worklist.
  2369. DFSWorkList.push_back(SuccBlk);
  2370. }
  2371. }
  2372. }
  2373. }
  2374. // Nothing reached the exit. It can only mean one thing: there's no return.
  2375. return true;
  2376. }
  2377. static BugReport *
  2378. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  2379. SmallVectorImpl<BugReport*> &bugReports) {
  2380. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  2381. assert(I != E);
  2382. const BugType& BT = I->getBugType();
  2383. // If we don't need to suppress any of the nodes because they are
  2384. // post-dominated by a sink, simply add all the nodes in the equivalence class
  2385. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  2386. if (!BT.isSuppressOnSink()) {
  2387. BugReport *R = &*I;
  2388. for (auto &I : EQ) {
  2389. const ExplodedNode *N = I.getErrorNode();
  2390. if (N) {
  2391. R = &I;
  2392. bugReports.push_back(R);
  2393. }
  2394. }
  2395. return R;
  2396. }
  2397. // For bug reports that should be suppressed when all paths are post-dominated
  2398. // by a sink node, iterate through the reports in the equivalence class
  2399. // until we find one that isn't post-dominated (if one exists). We use a
  2400. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  2401. // this as a recursive function, but we don't want to risk blowing out the
  2402. // stack for very long paths.
  2403. BugReport *exampleReport = nullptr;
  2404. for (; I != E; ++I) {
  2405. const ExplodedNode *errorNode = I->getErrorNode();
  2406. if (!errorNode)
  2407. continue;
  2408. if (errorNode->isSink()) {
  2409. llvm_unreachable(
  2410. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  2411. }
  2412. // No successors? By definition this nodes isn't post-dominated by a sink.
  2413. if (errorNode->succ_empty()) {
  2414. bugReports.push_back(&*I);
  2415. if (!exampleReport)
  2416. exampleReport = &*I;
  2417. continue;
  2418. }
  2419. // See if we are in a no-return CFG block. If so, treat this similarly
  2420. // to being post-dominated by a sink. This works better when the analysis
  2421. // is incomplete and we have never reached the no-return function call(s)
  2422. // that we'd inevitably bump into on this path.
  2423. if (isInevitablySinking(errorNode))
  2424. continue;
  2425. // At this point we know that 'N' is not a sink and it has at least one
  2426. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  2427. using WLItem = FRIEC_WLItem;
  2428. using DFSWorkList = SmallVector<WLItem, 10>;
  2429. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  2430. DFSWorkList WL;
  2431. WL.push_back(errorNode);
  2432. Visited[errorNode] = 1;
  2433. while (!WL.empty()) {
  2434. WLItem &WI = WL.back();
  2435. assert(!WI.N->succ_empty());
  2436. for (; WI.I != WI.E; ++WI.I) {
  2437. const ExplodedNode *Succ = *WI.I;
  2438. // End-of-path node?
  2439. if (Succ->succ_empty()) {
  2440. // If we found an end-of-path node that is not a sink.
  2441. if (!Succ->isSink()) {
  2442. bugReports.push_back(&*I);
  2443. if (!exampleReport)
  2444. exampleReport = &*I;
  2445. WL.clear();
  2446. break;
  2447. }
  2448. // Found a sink? Continue on to the next successor.
  2449. continue;
  2450. }
  2451. // Mark the successor as visited. If it hasn't been explored,
  2452. // enqueue it to the DFS worklist.
  2453. unsigned &mark = Visited[Succ];
  2454. if (!mark) {
  2455. mark = 1;
  2456. WL.push_back(Succ);
  2457. break;
  2458. }
  2459. }
  2460. // The worklist may have been cleared at this point. First
  2461. // check if it is empty before checking the last item.
  2462. if (!WL.empty() && &WL.back() == &WI)
  2463. WL.pop_back();
  2464. }
  2465. }
  2466. // ExampleReport will be NULL if all the nodes in the equivalence class
  2467. // were post-dominated by sinks.
  2468. return exampleReport;
  2469. }
  2470. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  2471. SmallVector<BugReport*, 10> bugReports;
  2472. BugReport *report = FindReportInEquivalenceClass(EQ, bugReports);
  2473. if (!report)
  2474. return;
  2475. ArrayRef<PathDiagnosticConsumer*> Consumers = getPathDiagnosticConsumers();
  2476. std::unique_ptr<DiagnosticForConsumerMapTy> Diagnostics =
  2477. generateDiagnosticForConsumerMap(report, Consumers, bugReports);
  2478. for (auto &P : *Diagnostics) {
  2479. PathDiagnosticConsumer *Consumer = P.first;
  2480. std::unique_ptr<PathDiagnostic> &PD = P.second;
  2481. // If the path is empty, generate a single step path with the location
  2482. // of the issue.
  2483. if (PD->path.empty()) {
  2484. PathDiagnosticLocation L = report->getLocation(getSourceManager());
  2485. auto piece = llvm::make_unique<PathDiagnosticEventPiece>(
  2486. L, report->getDescription());
  2487. for (SourceRange Range : report->getRanges())
  2488. piece->addRange(Range);
  2489. PD->setEndOfPath(std::move(piece));
  2490. }
  2491. PathPieces &Pieces = PD->getMutablePieces();
  2492. if (getAnalyzerOptions().ShouldDisplayNotesAsEvents) {
  2493. // For path diagnostic consumers that don't support extra notes,
  2494. // we may optionally convert those to path notes.
  2495. for (auto I = report->getNotes().rbegin(),
  2496. E = report->getNotes().rend(); I != E; ++I) {
  2497. PathDiagnosticNotePiece *Piece = I->get();
  2498. auto ConvertedPiece = std::make_shared<PathDiagnosticEventPiece>(
  2499. Piece->getLocation(), Piece->getString());
  2500. for (const auto &R: Piece->getRanges())
  2501. ConvertedPiece->addRange(R);
  2502. Pieces.push_front(std::move(ConvertedPiece));
  2503. }
  2504. } else {
  2505. for (auto I = report->getNotes().rbegin(),
  2506. E = report->getNotes().rend(); I != E; ++I)
  2507. Pieces.push_front(*I);
  2508. }
  2509. // Get the meta data.
  2510. const BugReport::ExtraTextList &Meta = report->getExtraText();
  2511. for (const auto &i : Meta)
  2512. PD->addMeta(i);
  2513. updateExecutedLinesWithDiagnosticPieces(*PD);
  2514. Consumer->HandlePathDiagnostic(std::move(PD));
  2515. }
  2516. }
  2517. /// Insert all lines participating in the function signature \p Signature
  2518. /// into \p ExecutedLines.
  2519. static void populateExecutedLinesWithFunctionSignature(
  2520. const Decl *Signature, SourceManager &SM,
  2521. FilesToLineNumsMap &ExecutedLines) {
  2522. SourceRange SignatureSourceRange;
  2523. const Stmt* Body = Signature->getBody();
  2524. if (const auto FD = dyn_cast<FunctionDecl>(Signature)) {
  2525. SignatureSourceRange = FD->getSourceRange();
  2526. } else if (const auto OD = dyn_cast<ObjCMethodDecl>(Signature)) {
  2527. SignatureSourceRange = OD->getSourceRange();
  2528. } else {
  2529. return;
  2530. }
  2531. SourceLocation Start = SignatureSourceRange.getBegin();
  2532. SourceLocation End = Body ? Body->getSourceRange().getBegin()
  2533. : SignatureSourceRange.getEnd();
  2534. if (!Start.isValid() || !End.isValid())
  2535. return;
  2536. unsigned StartLine = SM.getExpansionLineNumber(Start);
  2537. unsigned EndLine = SM.getExpansionLineNumber(End);
  2538. FileID FID = SM.getFileID(SM.getExpansionLoc(Start));
  2539. for (unsigned Line = StartLine; Line <= EndLine; Line++)
  2540. ExecutedLines[FID].insert(Line);
  2541. }
  2542. static void populateExecutedLinesWithStmt(
  2543. const Stmt *S, SourceManager &SM,
  2544. FilesToLineNumsMap &ExecutedLines) {
  2545. SourceLocation Loc = S->getSourceRange().getBegin();
  2546. if (!Loc.isValid())
  2547. return;
  2548. SourceLocation ExpansionLoc = SM.getExpansionLoc(Loc);
  2549. FileID FID = SM.getFileID(ExpansionLoc);
  2550. unsigned LineNo = SM.getExpansionLineNumber(ExpansionLoc);
  2551. ExecutedLines[FID].insert(LineNo);
  2552. }
  2553. /// \return all executed lines including function signatures on the path
  2554. /// starting from \p N.
  2555. static std::unique_ptr<FilesToLineNumsMap>
  2556. findExecutedLines(SourceManager &SM, const ExplodedNode *N) {
  2557. auto ExecutedLines = llvm::make_unique<FilesToLineNumsMap>();
  2558. while (N) {
  2559. if (N->getFirstPred() == nullptr) {
  2560. // First node: show signature of the entrance point.
  2561. const Decl *D = N->getLocationContext()->getDecl();
  2562. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2563. } else if (auto CE = N->getLocationAs<CallEnter>()) {
  2564. // Inlined function: show signature.
  2565. const Decl* D = CE->getCalleeContext()->getDecl();
  2566. populateExecutedLinesWithFunctionSignature(D, SM, *ExecutedLines);
  2567. } else if (const Stmt *S = PathDiagnosticLocation::getStmt(N)) {
  2568. populateExecutedLinesWithStmt(S, SM, *ExecutedLines);
  2569. // Show extra context for some parent kinds.
  2570. const Stmt *P = N->getParentMap().getParent(S);
  2571. // The path exploration can die before the node with the associated
  2572. // return statement is generated, but we do want to show the whole
  2573. // return.
  2574. if (const auto *RS = dyn_cast_or_null<ReturnStmt>(P)) {
  2575. populateExecutedLinesWithStmt(RS, SM, *ExecutedLines);
  2576. P = N->getParentMap().getParent(RS);
  2577. }
  2578. if (P && (isa<SwitchCase>(P) || isa<LabelStmt>(P)))
  2579. populateExecutedLinesWithStmt(P, SM, *ExecutedLines);
  2580. }
  2581. N = N->getFirstPred();
  2582. }
  2583. return ExecutedLines;
  2584. }
  2585. std::unique_ptr<DiagnosticForConsumerMapTy>
  2586. BugReporter::generateDiagnosticForConsumerMap(
  2587. BugReport *report, ArrayRef<PathDiagnosticConsumer *> consumers,
  2588. ArrayRef<BugReport *> bugReports) {
  2589. if (!report->isPathSensitive()) {
  2590. auto Out = llvm::make_unique<DiagnosticForConsumerMapTy>();
  2591. for (auto *Consumer : consumers)
  2592. (*Out)[Consumer] = generateEmptyDiagnosticForReport(report,
  2593. getSourceManager());
  2594. return Out;
  2595. }
  2596. // Generate the full path sensitive diagnostic, using the generation scheme
  2597. // specified by the PathDiagnosticConsumer. Note that we have to generate
  2598. // path diagnostics even for consumers which do not support paths, because
  2599. // the BugReporterVisitors may mark this bug as a false positive.
  2600. assert(!bugReports.empty());
  2601. MaxBugClassSize.updateMax(bugReports.size());
  2602. std::unique_ptr<DiagnosticForConsumerMapTy> Out =
  2603. generatePathDiagnostics(consumers, bugReports);
  2604. if (Out->empty())
  2605. return Out;
  2606. MaxValidBugClassSize.updateMax(bugReports.size());
  2607. // Examine the report and see if the last piece is in a header. Reset the
  2608. // report location to the last piece in the main source file.
  2609. AnalyzerOptions &Opts = getAnalyzerOptions();
  2610. for (auto const &P : *Out)
  2611. if (Opts.ShouldReportIssuesInMainSourceFile && !Opts.AnalyzeAll)
  2612. P.second->resetDiagnosticLocationToMainFile();
  2613. return Out;
  2614. }
  2615. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2616. const CheckerBase *Checker,
  2617. StringRef Name, StringRef Category,
  2618. StringRef Str, PathDiagnosticLocation Loc,
  2619. ArrayRef<SourceRange> Ranges) {
  2620. EmitBasicReport(DeclWithIssue, Checker->getCheckName(), Name, Category, Str,
  2621. Loc, Ranges);
  2622. }
  2623. void BugReporter::EmitBasicReport(const Decl *DeclWithIssue,
  2624. CheckName CheckName,
  2625. StringRef name, StringRef category,
  2626. StringRef str, PathDiagnosticLocation Loc,
  2627. ArrayRef<SourceRange> Ranges) {
  2628. // 'BT' is owned by BugReporter.
  2629. BugType *BT = getBugTypeForName(CheckName, name, category);
  2630. auto R = llvm::make_unique<BugReport>(*BT, str, Loc);
  2631. R->setDeclWithIssue(DeclWithIssue);
  2632. for (ArrayRef<SourceRange>::iterator I = Ranges.begin(), E = Ranges.end();
  2633. I != E; ++I)
  2634. R->addRange(*I);
  2635. emitReport(std::move(R));
  2636. }
  2637. BugType *BugReporter::getBugTypeForName(CheckName CheckName, StringRef name,
  2638. StringRef category) {
  2639. SmallString<136> fullDesc;
  2640. llvm::raw_svector_ostream(fullDesc) << CheckName.getName() << ":" << name
  2641. << ":" << category;
  2642. BugType *&BT = StrBugTypes[fullDesc];
  2643. if (!BT)
  2644. BT = new BugType(CheckName, name, category);
  2645. return BT;
  2646. }