BugReporter.cpp 120 KB

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