BugReporter.cpp 105 KB

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