BugReporter.cpp 118 KB

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