BugReporter.cpp 104 KB

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