BugReporter.cpp 117 KB

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