BugReporter.cpp 103 KB

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