BugReporter.cpp 116 KB

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