BugReporter.cpp 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942
  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/StaticAnalyzer/Core/BugReporter/BugType.h"
  16. #include "clang/StaticAnalyzer/Core/PathSensitive/ExprEngine.h"
  17. #include "clang/AST/ASTContext.h"
  18. #include "clang/Analysis/CFG.h"
  19. #include "clang/AST/Expr.h"
  20. #include "clang/AST/ParentMap.h"
  21. #include "clang/AST/StmtObjC.h"
  22. #include "clang/Basic/SourceManager.h"
  23. #include "clang/Analysis/ProgramPoint.h"
  24. #include "clang/StaticAnalyzer/Core/BugReporter/PathDiagnostic.h"
  25. #include "llvm/Support/raw_ostream.h"
  26. #include "llvm/ADT/DenseMap.h"
  27. #include "llvm/ADT/STLExtras.h"
  28. #include "llvm/ADT/OwningPtr.h"
  29. #include <queue>
  30. using namespace clang;
  31. using namespace ento;
  32. BugReporterVisitor::~BugReporterVisitor() {}
  33. //===----------------------------------------------------------------------===//
  34. // Helper routines for walking the ExplodedGraph and fetching statements.
  35. //===----------------------------------------------------------------------===//
  36. static inline const Stmt *GetStmt(const ProgramPoint &P) {
  37. if (const StmtPoint* SP = dyn_cast<StmtPoint>(&P))
  38. return SP->getStmt();
  39. else if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P))
  40. return BE->getSrc()->getTerminator();
  41. return 0;
  42. }
  43. static inline const ExplodedNode*
  44. GetPredecessorNode(const ExplodedNode *N) {
  45. return N->pred_empty() ? NULL : *(N->pred_begin());
  46. }
  47. static inline const ExplodedNode*
  48. GetSuccessorNode(const ExplodedNode *N) {
  49. return N->succ_empty() ? NULL : *(N->succ_begin());
  50. }
  51. static const Stmt *GetPreviousStmt(const ExplodedNode *N) {
  52. for (N = GetPredecessorNode(N); N; N = GetPredecessorNode(N))
  53. if (const Stmt *S = GetStmt(N->getLocation()))
  54. return S;
  55. return 0;
  56. }
  57. static const Stmt *GetNextStmt(const ExplodedNode *N) {
  58. for (N = GetSuccessorNode(N); N; N = GetSuccessorNode(N))
  59. if (const Stmt *S = GetStmt(N->getLocation())) {
  60. // Check if the statement is '?' or '&&'/'||'. These are "merges",
  61. // not actual statement points.
  62. switch (S->getStmtClass()) {
  63. case Stmt::ChooseExprClass:
  64. case Stmt::BinaryConditionalOperatorClass: continue;
  65. case Stmt::ConditionalOperatorClass: continue;
  66. case Stmt::BinaryOperatorClass: {
  67. BinaryOperatorKind Op = cast<BinaryOperator>(S)->getOpcode();
  68. if (Op == BO_LAnd || Op == BO_LOr)
  69. continue;
  70. break;
  71. }
  72. default:
  73. break;
  74. }
  75. // Some expressions don't have locations.
  76. if (S->getLocStart().isInvalid())
  77. continue;
  78. return S;
  79. }
  80. return 0;
  81. }
  82. static inline const Stmt*
  83. GetCurrentOrPreviousStmt(const ExplodedNode *N) {
  84. if (const Stmt *S = GetStmt(N->getLocation()))
  85. return S;
  86. return GetPreviousStmt(N);
  87. }
  88. static inline const Stmt*
  89. GetCurrentOrNextStmt(const ExplodedNode *N) {
  90. if (const Stmt *S = GetStmt(N->getLocation()))
  91. return S;
  92. return GetNextStmt(N);
  93. }
  94. //===----------------------------------------------------------------------===//
  95. // PathDiagnosticBuilder and its associated routines and helper objects.
  96. //===----------------------------------------------------------------------===//
  97. typedef llvm::DenseMap<const ExplodedNode*,
  98. const ExplodedNode*> NodeBackMap;
  99. namespace {
  100. class NodeMapClosure : public BugReport::NodeResolver {
  101. NodeBackMap& M;
  102. public:
  103. NodeMapClosure(NodeBackMap *m) : M(*m) {}
  104. ~NodeMapClosure() {}
  105. const ExplodedNode *getOriginalNode(const ExplodedNode *N) {
  106. NodeBackMap::iterator I = M.find(N);
  107. return I == M.end() ? 0 : I->second;
  108. }
  109. };
  110. class PathDiagnosticBuilder : public BugReporterContext {
  111. BugReport *R;
  112. PathDiagnosticClient *PDC;
  113. llvm::OwningPtr<ParentMap> PM;
  114. NodeMapClosure NMC;
  115. public:
  116. PathDiagnosticBuilder(GRBugReporter &br,
  117. BugReport *r, NodeBackMap *Backmap,
  118. PathDiagnosticClient *pdc)
  119. : BugReporterContext(br),
  120. R(r), PDC(pdc), NMC(Backmap) {}
  121. PathDiagnosticLocation ExecutionContinues(const ExplodedNode *N);
  122. PathDiagnosticLocation ExecutionContinues(llvm::raw_string_ostream &os,
  123. const ExplodedNode *N);
  124. BugReport *getBugReport() { return R; }
  125. Decl const &getCodeDecl() { return R->getErrorNode()->getCodeDecl(); }
  126. ParentMap& getParentMap() { return R->getErrorNode()->getParentMap(); }
  127. const Stmt *getParent(const Stmt *S) {
  128. return getParentMap().getParent(S);
  129. }
  130. virtual NodeMapClosure& getNodeResolver() { return NMC; }
  131. PathDiagnosticLocation getEnclosingStmtLocation(const Stmt *S);
  132. PathDiagnosticClient::PathGenerationScheme getGenerationScheme() const {
  133. return PDC ? PDC->getGenerationScheme() : PathDiagnosticClient::Extensive;
  134. }
  135. bool supportsLogicalOpControlFlow() const {
  136. return PDC ? PDC->supportsLogicalOpControlFlow() : true;
  137. }
  138. };
  139. } // end anonymous namespace
  140. PathDiagnosticLocation
  141. PathDiagnosticBuilder::ExecutionContinues(const ExplodedNode *N) {
  142. if (const Stmt *S = GetNextStmt(N))
  143. return PathDiagnosticLocation(S, getSourceManager());
  144. return FullSourceLoc(N->getLocationContext()->getDecl()->getBodyRBrace(),
  145. getSourceManager());
  146. }
  147. PathDiagnosticLocation
  148. PathDiagnosticBuilder::ExecutionContinues(llvm::raw_string_ostream &os,
  149. const ExplodedNode *N) {
  150. // Slow, but probably doesn't matter.
  151. if (os.str().empty())
  152. os << ' ';
  153. const PathDiagnosticLocation &Loc = ExecutionContinues(N);
  154. if (Loc.asStmt())
  155. os << "Execution continues on line "
  156. << getSourceManager().getExpansionLineNumber(Loc.asLocation())
  157. << '.';
  158. else {
  159. os << "Execution jumps to the end of the ";
  160. const Decl *D = N->getLocationContext()->getDecl();
  161. if (isa<ObjCMethodDecl>(D))
  162. os << "method";
  163. else if (isa<FunctionDecl>(D))
  164. os << "function";
  165. else {
  166. assert(isa<BlockDecl>(D));
  167. os << "anonymous block";
  168. }
  169. os << '.';
  170. }
  171. return Loc;
  172. }
  173. static bool IsNested(const Stmt *S, ParentMap &PM) {
  174. if (isa<Expr>(S) && PM.isConsumedExpr(cast<Expr>(S)))
  175. return true;
  176. const Stmt *Parent = PM.getParentIgnoreParens(S);
  177. if (Parent)
  178. switch (Parent->getStmtClass()) {
  179. case Stmt::ForStmtClass:
  180. case Stmt::DoStmtClass:
  181. case Stmt::WhileStmtClass:
  182. return true;
  183. default:
  184. break;
  185. }
  186. return false;
  187. }
  188. PathDiagnosticLocation
  189. PathDiagnosticBuilder::getEnclosingStmtLocation(const Stmt *S) {
  190. assert(S && "Null Stmt *passed to getEnclosingStmtLocation");
  191. ParentMap &P = getParentMap();
  192. SourceManager &SMgr = getSourceManager();
  193. while (IsNested(S, P)) {
  194. const Stmt *Parent = P.getParentIgnoreParens(S);
  195. if (!Parent)
  196. break;
  197. switch (Parent->getStmtClass()) {
  198. case Stmt::BinaryOperatorClass: {
  199. const BinaryOperator *B = cast<BinaryOperator>(Parent);
  200. if (B->isLogicalOp())
  201. return PathDiagnosticLocation(S, SMgr);
  202. break;
  203. }
  204. case Stmt::CompoundStmtClass:
  205. case Stmt::StmtExprClass:
  206. return PathDiagnosticLocation(S, SMgr);
  207. case Stmt::ChooseExprClass:
  208. // Similar to '?' if we are referring to condition, just have the edge
  209. // point to the entire choose expression.
  210. if (cast<ChooseExpr>(Parent)->getCond() == S)
  211. return PathDiagnosticLocation(Parent, SMgr);
  212. else
  213. return PathDiagnosticLocation(S, SMgr);
  214. case Stmt::BinaryConditionalOperatorClass:
  215. case Stmt::ConditionalOperatorClass:
  216. // For '?', if we are referring to condition, just have the edge point
  217. // to the entire '?' expression.
  218. if (cast<AbstractConditionalOperator>(Parent)->getCond() == S)
  219. return PathDiagnosticLocation(Parent, SMgr);
  220. else
  221. return PathDiagnosticLocation(S, SMgr);
  222. case Stmt::DoStmtClass:
  223. return PathDiagnosticLocation(S, SMgr);
  224. case Stmt::ForStmtClass:
  225. if (cast<ForStmt>(Parent)->getBody() == S)
  226. return PathDiagnosticLocation(S, SMgr);
  227. break;
  228. case Stmt::IfStmtClass:
  229. if (cast<IfStmt>(Parent)->getCond() != S)
  230. return PathDiagnosticLocation(S, SMgr);
  231. break;
  232. case Stmt::ObjCForCollectionStmtClass:
  233. if (cast<ObjCForCollectionStmt>(Parent)->getBody() == S)
  234. return PathDiagnosticLocation(S, SMgr);
  235. break;
  236. case Stmt::WhileStmtClass:
  237. if (cast<WhileStmt>(Parent)->getCond() != S)
  238. return PathDiagnosticLocation(S, SMgr);
  239. break;
  240. default:
  241. break;
  242. }
  243. S = Parent;
  244. }
  245. assert(S && "Cannot have null Stmt for PathDiagnosticLocation");
  246. // Special case: DeclStmts can appear in for statement declarations, in which
  247. // case the ForStmt is the context.
  248. if (isa<DeclStmt>(S)) {
  249. if (const Stmt *Parent = P.getParent(S)) {
  250. switch (Parent->getStmtClass()) {
  251. case Stmt::ForStmtClass:
  252. case Stmt::ObjCForCollectionStmtClass:
  253. return PathDiagnosticLocation(Parent, SMgr);
  254. default:
  255. break;
  256. }
  257. }
  258. }
  259. else if (isa<BinaryOperator>(S)) {
  260. // Special case: the binary operator represents the initialization
  261. // code in a for statement (this can happen when the variable being
  262. // initialized is an old variable.
  263. if (const ForStmt *FS =
  264. dyn_cast_or_null<ForStmt>(P.getParentIgnoreParens(S))) {
  265. if (FS->getInit() == S)
  266. return PathDiagnosticLocation(FS, SMgr);
  267. }
  268. }
  269. return PathDiagnosticLocation(S, SMgr);
  270. }
  271. //===----------------------------------------------------------------------===//
  272. // ScanNotableSymbols: closure-like callback for scanning Store bindings.
  273. //===----------------------------------------------------------------------===//
  274. static const VarDecl* GetMostRecentVarDeclBinding(const ExplodedNode *N,
  275. ProgramStateManager& VMgr,
  276. SVal X) {
  277. for ( ; N ; N = N->pred_empty() ? 0 : *N->pred_begin()) {
  278. ProgramPoint P = N->getLocation();
  279. if (!isa<PostStmt>(P))
  280. continue;
  281. const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(cast<PostStmt>(P).getStmt());
  282. if (!DR)
  283. continue;
  284. SVal Y = N->getState()->getSVal(DR);
  285. if (X != Y)
  286. continue;
  287. const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl());
  288. if (!VD)
  289. continue;
  290. return VD;
  291. }
  292. return 0;
  293. }
  294. namespace {
  295. class NotableSymbolHandler
  296. : public StoreManager::BindingsHandler {
  297. SymbolRef Sym;
  298. const ProgramState *PrevSt;
  299. const Stmt *S;
  300. ProgramStateManager& VMgr;
  301. const ExplodedNode *Pred;
  302. PathDiagnostic& PD;
  303. BugReporter& BR;
  304. public:
  305. NotableSymbolHandler(SymbolRef sym,
  306. const ProgramState *prevst,
  307. const Stmt *s,
  308. ProgramStateManager& vmgr,
  309. const ExplodedNode *pred,
  310. PathDiagnostic& pd,
  311. BugReporter& br)
  312. : Sym(sym),
  313. PrevSt(prevst),
  314. S(s),
  315. VMgr(vmgr),
  316. Pred(pred),
  317. PD(pd),
  318. BR(br) {}
  319. bool HandleBinding(StoreManager& SMgr, Store store, const MemRegion* R,
  320. SVal V) {
  321. SymbolRef ScanSym = V.getAsSymbol();
  322. if (ScanSym != Sym)
  323. return true;
  324. // Check if the previous state has this binding.
  325. SVal X = PrevSt->getSVal(loc::MemRegionVal(R));
  326. if (X == V) // Same binding?
  327. return true;
  328. // Different binding. Only handle assignments for now. We don't pull
  329. // this check out of the loop because we will eventually handle other
  330. // cases.
  331. VarDecl *VD = 0;
  332. if (const BinaryOperator* B = dyn_cast<BinaryOperator>(S)) {
  333. if (!B->isAssignmentOp())
  334. return true;
  335. // What variable did we assign to?
  336. DeclRefExpr *DR = dyn_cast<DeclRefExpr>(B->getLHS()->IgnoreParenCasts());
  337. if (!DR)
  338. return true;
  339. VD = dyn_cast<VarDecl>(DR->getDecl());
  340. }
  341. else if (const DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
  342. // FIXME: Eventually CFGs won't have DeclStmts. Right now we
  343. // assume that each DeclStmt has a single Decl. This invariant
  344. // holds by construction in the CFG.
  345. VD = dyn_cast<VarDecl>(*DS->decl_begin());
  346. }
  347. if (!VD)
  348. return true;
  349. // What is the most recently referenced variable with this binding?
  350. const VarDecl *MostRecent = GetMostRecentVarDeclBinding(Pred, VMgr, V);
  351. if (!MostRecent)
  352. return true;
  353. // Create the diagnostic.
  354. FullSourceLoc L(S->getLocStart(), BR.getSourceManager());
  355. if (Loc::isLocType(VD->getType())) {
  356. std::string msg = "'" + std::string(VD->getNameAsString()) +
  357. "' now aliases '" + MostRecent->getNameAsString() + "'";
  358. PD.push_front(new PathDiagnosticEventPiece(L, msg));
  359. }
  360. return true;
  361. }
  362. };
  363. }
  364. static void HandleNotableSymbol(const ExplodedNode *N,
  365. const Stmt *S,
  366. SymbolRef Sym, BugReporter& BR,
  367. PathDiagnostic& PD) {
  368. const ExplodedNode *Pred = N->pred_empty() ? 0 : *N->pred_begin();
  369. const ProgramState *PrevSt = Pred ? Pred->getState() : 0;
  370. if (!PrevSt)
  371. return;
  372. // Look at the region bindings of the current state that map to the
  373. // specified symbol. Are any of them not in the previous state?
  374. ProgramStateManager& VMgr = cast<GRBugReporter>(BR).getStateManager();
  375. NotableSymbolHandler H(Sym, PrevSt, S, VMgr, Pred, PD, BR);
  376. cast<GRBugReporter>(BR).getStateManager().iterBindings(N->getState(), H);
  377. }
  378. namespace {
  379. class ScanNotableSymbols
  380. : public StoreManager::BindingsHandler {
  381. llvm::SmallSet<SymbolRef, 10> AlreadyProcessed;
  382. const ExplodedNode *N;
  383. const Stmt *S;
  384. GRBugReporter& BR;
  385. PathDiagnostic& PD;
  386. public:
  387. ScanNotableSymbols(const ExplodedNode *n, const Stmt *s,
  388. GRBugReporter& br, PathDiagnostic& pd)
  389. : N(n), S(s), BR(br), PD(pd) {}
  390. bool HandleBinding(StoreManager& SMgr, Store store,
  391. const MemRegion* R, SVal V) {
  392. SymbolRef ScanSym = V.getAsSymbol();
  393. if (!ScanSym)
  394. return true;
  395. if (!BR.isNotable(ScanSym))
  396. return true;
  397. if (AlreadyProcessed.count(ScanSym))
  398. return true;
  399. AlreadyProcessed.insert(ScanSym);
  400. HandleNotableSymbol(N, S, ScanSym, BR, PD);
  401. return true;
  402. }
  403. };
  404. } // end anonymous namespace
  405. //===----------------------------------------------------------------------===//
  406. // "Minimal" path diagnostic generation algorithm.
  407. //===----------------------------------------------------------------------===//
  408. static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM);
  409. static void GenerateMinimalPathDiagnostic(PathDiagnostic& PD,
  410. PathDiagnosticBuilder &PDB,
  411. const ExplodedNode *N) {
  412. SourceManager& SMgr = PDB.getSourceManager();
  413. const ExplodedNode *NextNode = N->pred_empty()
  414. ? NULL : *(N->pred_begin());
  415. while (NextNode) {
  416. N = NextNode;
  417. NextNode = GetPredecessorNode(N);
  418. ProgramPoint P = N->getLocation();
  419. if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
  420. const CFGBlock *Src = BE->getSrc();
  421. const CFGBlock *Dst = BE->getDst();
  422. const Stmt *T = Src->getTerminator();
  423. if (!T)
  424. continue;
  425. FullSourceLoc Start(T->getLocStart(), SMgr);
  426. switch (T->getStmtClass()) {
  427. default:
  428. break;
  429. case Stmt::GotoStmtClass:
  430. case Stmt::IndirectGotoStmtClass: {
  431. const Stmt *S = GetNextStmt(N);
  432. if (!S)
  433. continue;
  434. std::string sbuf;
  435. llvm::raw_string_ostream os(sbuf);
  436. const PathDiagnosticLocation &End = PDB.getEnclosingStmtLocation(S);
  437. os << "Control jumps to line "
  438. << End.asLocation().getExpansionLineNumber();
  439. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  440. os.str()));
  441. break;
  442. }
  443. case Stmt::SwitchStmtClass: {
  444. // Figure out what case arm we took.
  445. std::string sbuf;
  446. llvm::raw_string_ostream os(sbuf);
  447. if (const Stmt *S = Dst->getLabel()) {
  448. PathDiagnosticLocation End(S, SMgr);
  449. switch (S->getStmtClass()) {
  450. default:
  451. os << "No cases match in the switch statement. "
  452. "Control jumps to line "
  453. << End.asLocation().getExpansionLineNumber();
  454. break;
  455. case Stmt::DefaultStmtClass:
  456. os << "Control jumps to the 'default' case at line "
  457. << End.asLocation().getExpansionLineNumber();
  458. break;
  459. case Stmt::CaseStmtClass: {
  460. os << "Control jumps to 'case ";
  461. const CaseStmt *Case = cast<CaseStmt>(S);
  462. const Expr *LHS = Case->getLHS()->IgnoreParenCasts();
  463. // Determine if it is an enum.
  464. bool GetRawInt = true;
  465. if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(LHS)) {
  466. // FIXME: Maybe this should be an assertion. Are there cases
  467. // were it is not an EnumConstantDecl?
  468. const EnumConstantDecl *D =
  469. dyn_cast<EnumConstantDecl>(DR->getDecl());
  470. if (D) {
  471. GetRawInt = false;
  472. os << D;
  473. }
  474. }
  475. if (GetRawInt)
  476. os << LHS->EvaluateAsInt(PDB.getASTContext());
  477. os << ":' at line "
  478. << End.asLocation().getExpansionLineNumber();
  479. break;
  480. }
  481. }
  482. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  483. os.str()));
  484. }
  485. else {
  486. os << "'Default' branch taken. ";
  487. const PathDiagnosticLocation &End = PDB.ExecutionContinues(os, N);
  488. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  489. os.str()));
  490. }
  491. break;
  492. }
  493. case Stmt::BreakStmtClass:
  494. case Stmt::ContinueStmtClass: {
  495. std::string sbuf;
  496. llvm::raw_string_ostream os(sbuf);
  497. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  498. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  499. os.str()));
  500. break;
  501. }
  502. // Determine control-flow for ternary '?'.
  503. case Stmt::BinaryConditionalOperatorClass:
  504. case Stmt::ConditionalOperatorClass: {
  505. std::string sbuf;
  506. llvm::raw_string_ostream os(sbuf);
  507. os << "'?' condition is ";
  508. if (*(Src->succ_begin()+1) == Dst)
  509. os << "false";
  510. else
  511. os << "true";
  512. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  513. if (const Stmt *S = End.asStmt())
  514. End = PDB.getEnclosingStmtLocation(S);
  515. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  516. os.str()));
  517. break;
  518. }
  519. // Determine control-flow for short-circuited '&&' and '||'.
  520. case Stmt::BinaryOperatorClass: {
  521. if (!PDB.supportsLogicalOpControlFlow())
  522. break;
  523. const BinaryOperator *B = cast<BinaryOperator>(T);
  524. std::string sbuf;
  525. llvm::raw_string_ostream os(sbuf);
  526. os << "Left side of '";
  527. if (B->getOpcode() == BO_LAnd) {
  528. os << "&&" << "' is ";
  529. if (*(Src->succ_begin()+1) == Dst) {
  530. os << "false";
  531. PathDiagnosticLocation End(B->getLHS(), SMgr);
  532. PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
  533. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  534. os.str()));
  535. }
  536. else {
  537. os << "true";
  538. PathDiagnosticLocation Start(B->getLHS(), SMgr);
  539. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  540. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  541. os.str()));
  542. }
  543. }
  544. else {
  545. assert(B->getOpcode() == BO_LOr);
  546. os << "||" << "' is ";
  547. if (*(Src->succ_begin()+1) == Dst) {
  548. os << "false";
  549. PathDiagnosticLocation Start(B->getLHS(), SMgr);
  550. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  551. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  552. os.str()));
  553. }
  554. else {
  555. os << "true";
  556. PathDiagnosticLocation End(B->getLHS(), SMgr);
  557. PathDiagnosticLocation Start(B->getOperatorLoc(), SMgr);
  558. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  559. os.str()));
  560. }
  561. }
  562. break;
  563. }
  564. case Stmt::DoStmtClass: {
  565. if (*(Src->succ_begin()) == Dst) {
  566. std::string sbuf;
  567. llvm::raw_string_ostream os(sbuf);
  568. os << "Loop condition is true. ";
  569. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  570. if (const Stmt *S = End.asStmt())
  571. End = PDB.getEnclosingStmtLocation(S);
  572. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  573. os.str()));
  574. }
  575. else {
  576. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  577. if (const Stmt *S = End.asStmt())
  578. End = PDB.getEnclosingStmtLocation(S);
  579. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  580. "Loop condition is false. Exiting loop"));
  581. }
  582. break;
  583. }
  584. case Stmt::WhileStmtClass:
  585. case Stmt::ForStmtClass: {
  586. if (*(Src->succ_begin()+1) == Dst) {
  587. std::string sbuf;
  588. llvm::raw_string_ostream os(sbuf);
  589. os << "Loop condition is false. ";
  590. PathDiagnosticLocation End = PDB.ExecutionContinues(os, N);
  591. if (const Stmt *S = End.asStmt())
  592. End = PDB.getEnclosingStmtLocation(S);
  593. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  594. os.str()));
  595. }
  596. else {
  597. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  598. if (const Stmt *S = End.asStmt())
  599. End = PDB.getEnclosingStmtLocation(S);
  600. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  601. "Loop condition is true. Entering loop body"));
  602. }
  603. break;
  604. }
  605. case Stmt::IfStmtClass: {
  606. PathDiagnosticLocation End = PDB.ExecutionContinues(N);
  607. if (const Stmt *S = End.asStmt())
  608. End = PDB.getEnclosingStmtLocation(S);
  609. if (*(Src->succ_begin()+1) == Dst)
  610. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  611. "Taking false branch"));
  612. else
  613. PD.push_front(new PathDiagnosticControlFlowPiece(Start, End,
  614. "Taking true branch"));
  615. break;
  616. }
  617. }
  618. }
  619. if (NextNode) {
  620. // Add diagnostic pieces from custom visitors.
  621. BugReport *R = PDB.getBugReport();
  622. for (BugReport::visitor_iterator I = R->visitor_begin(),
  623. E = R->visitor_end(); I!=E; ++I) {
  624. if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R))
  625. PD.push_front(p);
  626. }
  627. }
  628. if (const PostStmt *PS = dyn_cast<PostStmt>(&P)) {
  629. // Scan the region bindings, and see if a "notable" symbol has a new
  630. // lval binding.
  631. ScanNotableSymbols SNS(N, PS->getStmt(), PDB.getBugReporter(), PD);
  632. PDB.getStateManager().iterBindings(N->getState(), SNS);
  633. }
  634. }
  635. // After constructing the full PathDiagnostic, do a pass over it to compact
  636. // PathDiagnosticPieces that occur within a macro.
  637. CompactPathDiagnostic(PD, PDB.getSourceManager());
  638. }
  639. //===----------------------------------------------------------------------===//
  640. // "Extensive" PathDiagnostic generation.
  641. //===----------------------------------------------------------------------===//
  642. static bool IsControlFlowExpr(const Stmt *S) {
  643. const Expr *E = dyn_cast<Expr>(S);
  644. if (!E)
  645. return false;
  646. E = E->IgnoreParenCasts();
  647. if (isa<AbstractConditionalOperator>(E))
  648. return true;
  649. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(E))
  650. if (B->isLogicalOp())
  651. return true;
  652. return false;
  653. }
  654. namespace {
  655. class ContextLocation : public PathDiagnosticLocation {
  656. bool IsDead;
  657. public:
  658. ContextLocation(const PathDiagnosticLocation &L, bool isdead = false)
  659. : PathDiagnosticLocation(L), IsDead(isdead) {}
  660. void markDead() { IsDead = true; }
  661. bool isDead() const { return IsDead; }
  662. };
  663. class EdgeBuilder {
  664. std::vector<ContextLocation> CLocs;
  665. typedef std::vector<ContextLocation>::iterator iterator;
  666. PathDiagnostic &PD;
  667. PathDiagnosticBuilder &PDB;
  668. PathDiagnosticLocation PrevLoc;
  669. bool IsConsumedExpr(const PathDiagnosticLocation &L);
  670. bool containsLocation(const PathDiagnosticLocation &Container,
  671. const PathDiagnosticLocation &Containee);
  672. PathDiagnosticLocation getContextLocation(const PathDiagnosticLocation &L);
  673. PathDiagnosticLocation cleanUpLocation(PathDiagnosticLocation L,
  674. bool firstCharOnly = false) {
  675. if (const Stmt *S = L.asStmt()) {
  676. const Stmt *Original = S;
  677. while (1) {
  678. // Adjust the location for some expressions that are best referenced
  679. // by one of their subexpressions.
  680. switch (S->getStmtClass()) {
  681. default:
  682. break;
  683. case Stmt::ParenExprClass:
  684. case Stmt::GenericSelectionExprClass:
  685. S = cast<Expr>(S)->IgnoreParens();
  686. firstCharOnly = true;
  687. continue;
  688. case Stmt::BinaryConditionalOperatorClass:
  689. case Stmt::ConditionalOperatorClass:
  690. S = cast<AbstractConditionalOperator>(S)->getCond();
  691. firstCharOnly = true;
  692. continue;
  693. case Stmt::ChooseExprClass:
  694. S = cast<ChooseExpr>(S)->getCond();
  695. firstCharOnly = true;
  696. continue;
  697. case Stmt::BinaryOperatorClass:
  698. S = cast<BinaryOperator>(S)->getLHS();
  699. firstCharOnly = true;
  700. continue;
  701. }
  702. break;
  703. }
  704. if (S != Original)
  705. L = PathDiagnosticLocation(S, L.getManager());
  706. }
  707. if (firstCharOnly)
  708. L = PathDiagnosticLocation(L.asLocation());
  709. return L;
  710. }
  711. void popLocation() {
  712. if (!CLocs.back().isDead() && CLocs.back().asLocation().isFileID()) {
  713. // For contexts, we only one the first character as the range.
  714. rawAddEdge(cleanUpLocation(CLocs.back(), true));
  715. }
  716. CLocs.pop_back();
  717. }
  718. public:
  719. EdgeBuilder(PathDiagnostic &pd, PathDiagnosticBuilder &pdb)
  720. : PD(pd), PDB(pdb) {
  721. // If the PathDiagnostic already has pieces, add the enclosing statement
  722. // of the first piece as a context as well.
  723. if (!PD.empty()) {
  724. PrevLoc = PD.begin()->getLocation();
  725. if (const Stmt *S = PrevLoc.asStmt())
  726. addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  727. }
  728. }
  729. ~EdgeBuilder() {
  730. while (!CLocs.empty()) popLocation();
  731. // Finally, add an initial edge from the start location of the first
  732. // statement (if it doesn't already exist).
  733. // FIXME: Should handle CXXTryStmt if analyser starts supporting C++.
  734. if (const CompoundStmt *CS =
  735. dyn_cast_or_null<CompoundStmt>(PDB.getCodeDecl().getBody()))
  736. if (!CS->body_empty()) {
  737. SourceLocation Loc = (*CS->body_begin())->getLocStart();
  738. rawAddEdge(PathDiagnosticLocation(Loc, PDB.getSourceManager()));
  739. }
  740. }
  741. void addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd = false);
  742. void rawAddEdge(PathDiagnosticLocation NewLoc);
  743. void addContext(const Stmt *S);
  744. void addExtendedContext(const Stmt *S);
  745. };
  746. } // end anonymous namespace
  747. PathDiagnosticLocation
  748. EdgeBuilder::getContextLocation(const PathDiagnosticLocation &L) {
  749. if (const Stmt *S = L.asStmt()) {
  750. if (IsControlFlowExpr(S))
  751. return L;
  752. return PDB.getEnclosingStmtLocation(S);
  753. }
  754. return L;
  755. }
  756. bool EdgeBuilder::containsLocation(const PathDiagnosticLocation &Container,
  757. const PathDiagnosticLocation &Containee) {
  758. if (Container == Containee)
  759. return true;
  760. if (Container.asDecl())
  761. return true;
  762. if (const Stmt *S = Containee.asStmt())
  763. if (const Stmt *ContainerS = Container.asStmt()) {
  764. while (S) {
  765. if (S == ContainerS)
  766. return true;
  767. S = PDB.getParent(S);
  768. }
  769. return false;
  770. }
  771. // Less accurate: compare using source ranges.
  772. SourceRange ContainerR = Container.asRange();
  773. SourceRange ContaineeR = Containee.asRange();
  774. SourceManager &SM = PDB.getSourceManager();
  775. SourceLocation ContainerRBeg = SM.getExpansionLoc(ContainerR.getBegin());
  776. SourceLocation ContainerREnd = SM.getExpansionLoc(ContainerR.getEnd());
  777. SourceLocation ContaineeRBeg = SM.getExpansionLoc(ContaineeR.getBegin());
  778. SourceLocation ContaineeREnd = SM.getExpansionLoc(ContaineeR.getEnd());
  779. unsigned ContainerBegLine = SM.getExpansionLineNumber(ContainerRBeg);
  780. unsigned ContainerEndLine = SM.getExpansionLineNumber(ContainerREnd);
  781. unsigned ContaineeBegLine = SM.getExpansionLineNumber(ContaineeRBeg);
  782. unsigned ContaineeEndLine = SM.getExpansionLineNumber(ContaineeREnd);
  783. assert(ContainerBegLine <= ContainerEndLine);
  784. assert(ContaineeBegLine <= ContaineeEndLine);
  785. return (ContainerBegLine <= ContaineeBegLine &&
  786. ContainerEndLine >= ContaineeEndLine &&
  787. (ContainerBegLine != ContaineeBegLine ||
  788. SM.getExpansionColumnNumber(ContainerRBeg) <=
  789. SM.getExpansionColumnNumber(ContaineeRBeg)) &&
  790. (ContainerEndLine != ContaineeEndLine ||
  791. SM.getExpansionColumnNumber(ContainerREnd) >=
  792. SM.getExpansionColumnNumber(ContainerREnd)));
  793. }
  794. void EdgeBuilder::rawAddEdge(PathDiagnosticLocation NewLoc) {
  795. if (!PrevLoc.isValid()) {
  796. PrevLoc = NewLoc;
  797. return;
  798. }
  799. const PathDiagnosticLocation &NewLocClean = cleanUpLocation(NewLoc);
  800. const PathDiagnosticLocation &PrevLocClean = cleanUpLocation(PrevLoc);
  801. if (NewLocClean.asLocation() == PrevLocClean.asLocation())
  802. return;
  803. // FIXME: Ignore intra-macro edges for now.
  804. if (NewLocClean.asLocation().getExpansionLoc() ==
  805. PrevLocClean.asLocation().getExpansionLoc())
  806. return;
  807. PD.push_front(new PathDiagnosticControlFlowPiece(NewLocClean, PrevLocClean));
  808. PrevLoc = NewLoc;
  809. }
  810. void EdgeBuilder::addEdge(PathDiagnosticLocation NewLoc, bool alwaysAdd) {
  811. if (!alwaysAdd && NewLoc.asLocation().isMacroID())
  812. return;
  813. const PathDiagnosticLocation &CLoc = getContextLocation(NewLoc);
  814. while (!CLocs.empty()) {
  815. ContextLocation &TopContextLoc = CLocs.back();
  816. // Is the top location context the same as the one for the new location?
  817. if (TopContextLoc == CLoc) {
  818. if (alwaysAdd) {
  819. if (IsConsumedExpr(TopContextLoc) &&
  820. !IsControlFlowExpr(TopContextLoc.asStmt()))
  821. TopContextLoc.markDead();
  822. rawAddEdge(NewLoc);
  823. }
  824. return;
  825. }
  826. if (containsLocation(TopContextLoc, CLoc)) {
  827. if (alwaysAdd) {
  828. rawAddEdge(NewLoc);
  829. if (IsConsumedExpr(CLoc) && !IsControlFlowExpr(CLoc.asStmt())) {
  830. CLocs.push_back(ContextLocation(CLoc, true));
  831. return;
  832. }
  833. }
  834. CLocs.push_back(CLoc);
  835. return;
  836. }
  837. // Context does not contain the location. Flush it.
  838. popLocation();
  839. }
  840. // If we reach here, there is no enclosing context. Just add the edge.
  841. rawAddEdge(NewLoc);
  842. }
  843. bool EdgeBuilder::IsConsumedExpr(const PathDiagnosticLocation &L) {
  844. if (const Expr *X = dyn_cast_or_null<Expr>(L.asStmt()))
  845. return PDB.getParentMap().isConsumedExpr(X) && !IsControlFlowExpr(X);
  846. return false;
  847. }
  848. void EdgeBuilder::addExtendedContext(const Stmt *S) {
  849. if (!S)
  850. return;
  851. const Stmt *Parent = PDB.getParent(S);
  852. while (Parent) {
  853. if (isa<CompoundStmt>(Parent))
  854. Parent = PDB.getParent(Parent);
  855. else
  856. break;
  857. }
  858. if (Parent) {
  859. switch (Parent->getStmtClass()) {
  860. case Stmt::DoStmtClass:
  861. case Stmt::ObjCAtSynchronizedStmtClass:
  862. addContext(Parent);
  863. default:
  864. break;
  865. }
  866. }
  867. addContext(S);
  868. }
  869. void EdgeBuilder::addContext(const Stmt *S) {
  870. if (!S)
  871. return;
  872. PathDiagnosticLocation L(S, PDB.getSourceManager());
  873. while (!CLocs.empty()) {
  874. const PathDiagnosticLocation &TopContextLoc = CLocs.back();
  875. // Is the top location context the same as the one for the new location?
  876. if (TopContextLoc == L)
  877. return;
  878. if (containsLocation(TopContextLoc, L)) {
  879. CLocs.push_back(L);
  880. return;
  881. }
  882. // Context does not contain the location. Flush it.
  883. popLocation();
  884. }
  885. CLocs.push_back(L);
  886. }
  887. static void GenerateExtensivePathDiagnostic(PathDiagnostic& PD,
  888. PathDiagnosticBuilder &PDB,
  889. const ExplodedNode *N) {
  890. EdgeBuilder EB(PD, PDB);
  891. const ExplodedNode *NextNode = N->pred_empty() ? NULL : *(N->pred_begin());
  892. while (NextNode) {
  893. N = NextNode;
  894. NextNode = GetPredecessorNode(N);
  895. ProgramPoint P = N->getLocation();
  896. do {
  897. // Block edges.
  898. if (const BlockEdge *BE = dyn_cast<BlockEdge>(&P)) {
  899. const CFGBlock &Blk = *BE->getSrc();
  900. const Stmt *Term = Blk.getTerminator();
  901. // Are we jumping to the head of a loop? Add a special diagnostic.
  902. if (const Stmt *Loop = BE->getDst()->getLoopTarget()) {
  903. PathDiagnosticLocation L(Loop, PDB.getSourceManager());
  904. const CompoundStmt *CS = NULL;
  905. if (!Term) {
  906. if (const ForStmt *FS = dyn_cast<ForStmt>(Loop))
  907. CS = dyn_cast<CompoundStmt>(FS->getBody());
  908. else if (const WhileStmt *WS = dyn_cast<WhileStmt>(Loop))
  909. CS = dyn_cast<CompoundStmt>(WS->getBody());
  910. }
  911. PathDiagnosticEventPiece *p =
  912. new PathDiagnosticEventPiece(L,
  913. "Looping back to the head of the loop");
  914. EB.addEdge(p->getLocation(), true);
  915. PD.push_front(p);
  916. if (CS) {
  917. PathDiagnosticLocation BL(CS->getRBracLoc(),
  918. PDB.getSourceManager());
  919. BL = PathDiagnosticLocation(BL.asLocation());
  920. EB.addEdge(BL);
  921. }
  922. }
  923. if (Term)
  924. EB.addContext(Term);
  925. break;
  926. }
  927. if (const BlockEntrance *BE = dyn_cast<BlockEntrance>(&P)) {
  928. if (const CFGStmt *S = BE->getFirstElement().getAs<CFGStmt>()) {
  929. const Stmt *stmt = S->getStmt();
  930. if (IsControlFlowExpr(stmt)) {
  931. // Add the proper context for '&&', '||', and '?'.
  932. EB.addContext(stmt);
  933. }
  934. else
  935. EB.addExtendedContext(PDB.getEnclosingStmtLocation(stmt).asStmt());
  936. }
  937. break;
  938. }
  939. } while (0);
  940. if (!NextNode)
  941. continue;
  942. // Add pieces from custom visitors.
  943. BugReport *R = PDB.getBugReport();
  944. for (BugReport::visitor_iterator I = R->visitor_begin(),
  945. E = R->visitor_end(); I!=E; ++I) {
  946. if (PathDiagnosticPiece *p = (*I)->VisitNode(N, NextNode, PDB, *R)) {
  947. const PathDiagnosticLocation &Loc = p->getLocation();
  948. EB.addEdge(Loc, true);
  949. PD.push_front(p);
  950. if (const Stmt *S = Loc.asStmt())
  951. EB.addExtendedContext(PDB.getEnclosingStmtLocation(S).asStmt());
  952. }
  953. }
  954. }
  955. }
  956. //===----------------------------------------------------------------------===//
  957. // Methods for BugType and subclasses.
  958. //===----------------------------------------------------------------------===//
  959. BugType::~BugType() { }
  960. void BugType::FlushReports(BugReporter &BR) {}
  961. //===----------------------------------------------------------------------===//
  962. // Methods for BugReport and subclasses.
  963. //===----------------------------------------------------------------------===//
  964. void BugReport::addVisitor(BugReporterVisitor* visitor) {
  965. if (!visitor)
  966. return;
  967. llvm::FoldingSetNodeID ID;
  968. visitor->Profile(ID);
  969. void *InsertPos;
  970. if (CallbacksSet.FindNodeOrInsertPos(ID, InsertPos)) {
  971. delete visitor;
  972. return;
  973. }
  974. CallbacksSet.InsertNode(visitor, InsertPos);
  975. Callbacks = F.add(visitor, Callbacks);
  976. }
  977. BugReport::~BugReport() {
  978. for (visitor_iterator I = visitor_begin(), E = visitor_end(); I != E; ++I) {
  979. delete *I;
  980. }
  981. }
  982. void BugReport::Profile(llvm::FoldingSetNodeID& hash) const {
  983. hash.AddPointer(&BT);
  984. hash.AddInteger(getLocation().getRawEncoding());
  985. hash.AddString(Description);
  986. for (SmallVectorImpl<SourceRange>::const_iterator I =
  987. Ranges.begin(), E = Ranges.end(); I != E; ++I) {
  988. const SourceRange range = *I;
  989. if (!range.isValid())
  990. continue;
  991. hash.AddInteger(range.getBegin().getRawEncoding());
  992. hash.AddInteger(range.getEnd().getRawEncoding());
  993. }
  994. }
  995. const Stmt *BugReport::getStmt() const {
  996. if (!ErrorNode)
  997. return 0;
  998. ProgramPoint ProgP = ErrorNode->getLocation();
  999. const Stmt *S = NULL;
  1000. if (BlockEntrance *BE = dyn_cast<BlockEntrance>(&ProgP)) {
  1001. CFGBlock &Exit = ProgP.getLocationContext()->getCFG()->getExit();
  1002. if (BE->getBlock() == &Exit)
  1003. S = GetPreviousStmt(ErrorNode);
  1004. }
  1005. if (!S)
  1006. S = GetStmt(ProgP);
  1007. return S;
  1008. }
  1009. std::pair<BugReport::ranges_iterator, BugReport::ranges_iterator>
  1010. BugReport::getRanges() {
  1011. // If no custom ranges, add the range of the statement corresponding to
  1012. // the error node.
  1013. if (Ranges.empty()) {
  1014. if (const Expr *E = dyn_cast_or_null<Expr>(getStmt()))
  1015. addRange(E->getSourceRange());
  1016. else
  1017. return std::make_pair(ranges_iterator(), ranges_iterator());
  1018. }
  1019. return std::make_pair(Ranges.begin(), Ranges.end());
  1020. }
  1021. SourceLocation BugReport::getLocation() const {
  1022. if (ErrorNode) {
  1023. (Location.isInvalid() &&
  1024. "Either Location or ErrorNode should be specified but not both.");
  1025. if (const Stmt *S = GetCurrentOrPreviousStmt(ErrorNode)) {
  1026. // For member expressions, return the location of the '.' or '->'.
  1027. if (const MemberExpr *ME = dyn_cast<MemberExpr>(S))
  1028. return ME->getMemberLoc();
  1029. // For binary operators, return the location of the operator.
  1030. if (const BinaryOperator *B = dyn_cast<BinaryOperator>(S))
  1031. return B->getOperatorLoc();
  1032. return S->getLocStart();
  1033. }
  1034. } else {
  1035. assert(Location.isValid());
  1036. return Location;
  1037. }
  1038. return FullSourceLoc();
  1039. }
  1040. //===----------------------------------------------------------------------===//
  1041. // Methods for BugReporter and subclasses.
  1042. //===----------------------------------------------------------------------===//
  1043. BugReportEquivClass::~BugReportEquivClass() {
  1044. for (iterator I=begin(), E=end(); I!=E; ++I) delete *I;
  1045. }
  1046. GRBugReporter::~GRBugReporter() { }
  1047. BugReporterData::~BugReporterData() {}
  1048. ExplodedGraph &GRBugReporter::getGraph() { return Eng.getGraph(); }
  1049. ProgramStateManager&
  1050. GRBugReporter::getStateManager() { return Eng.getStateManager(); }
  1051. BugReporter::~BugReporter() {
  1052. FlushReports();
  1053. // Free the bug reports we are tracking.
  1054. typedef std::vector<BugReportEquivClass *> ContTy;
  1055. for (ContTy::iterator I = EQClassesVector.begin(), E = EQClassesVector.end();
  1056. I != E; ++I) {
  1057. delete *I;
  1058. }
  1059. }
  1060. void BugReporter::FlushReports() {
  1061. if (BugTypes.isEmpty())
  1062. return;
  1063. // First flush the warnings for each BugType. This may end up creating new
  1064. // warnings and new BugTypes.
  1065. // FIXME: Only NSErrorChecker needs BugType's FlushReports.
  1066. // Turn NSErrorChecker into a proper checker and remove this.
  1067. SmallVector<const BugType*, 16> bugTypes;
  1068. for (BugTypesTy::iterator I=BugTypes.begin(), E=BugTypes.end(); I!=E; ++I)
  1069. bugTypes.push_back(*I);
  1070. for (SmallVector<const BugType*, 16>::iterator
  1071. I = bugTypes.begin(), E = bugTypes.end(); I != E; ++I)
  1072. const_cast<BugType*>(*I)->FlushReports(*this);
  1073. typedef llvm::FoldingSet<BugReportEquivClass> SetTy;
  1074. for (SetTy::iterator EI=EQClasses.begin(), EE=EQClasses.end(); EI!=EE;++EI){
  1075. BugReportEquivClass& EQ = *EI;
  1076. FlushReport(EQ);
  1077. }
  1078. // BugReporter owns and deletes only BugTypes created implicitly through
  1079. // EmitBasicReport.
  1080. // FIXME: There are leaks from checkers that assume that the BugTypes they
  1081. // create will be destroyed by the BugReporter.
  1082. for (llvm::StringMap<BugType*>::iterator
  1083. I = StrBugTypes.begin(), E = StrBugTypes.end(); I != E; ++I)
  1084. delete I->second;
  1085. // Remove all references to the BugType objects.
  1086. BugTypes = F.getEmptySet();
  1087. }
  1088. //===----------------------------------------------------------------------===//
  1089. // PathDiagnostics generation.
  1090. //===----------------------------------------------------------------------===//
  1091. static std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
  1092. std::pair<ExplodedNode*, unsigned> >
  1093. MakeReportGraph(const ExplodedGraph* G,
  1094. SmallVectorImpl<const ExplodedNode*> &nodes) {
  1095. // Create the trimmed graph. It will contain the shortest paths from the
  1096. // error nodes to the root. In the new graph we should only have one
  1097. // error node unless there are two or more error nodes with the same minimum
  1098. // path length.
  1099. ExplodedGraph* GTrim;
  1100. InterExplodedGraphMap* NMap;
  1101. llvm::DenseMap<const void*, const void*> InverseMap;
  1102. llvm::tie(GTrim, NMap) = G->Trim(nodes.data(), nodes.data() + nodes.size(),
  1103. &InverseMap);
  1104. // Create owning pointers for GTrim and NMap just to ensure that they are
  1105. // released when this function exists.
  1106. llvm::OwningPtr<ExplodedGraph> AutoReleaseGTrim(GTrim);
  1107. llvm::OwningPtr<InterExplodedGraphMap> AutoReleaseNMap(NMap);
  1108. // Find the (first) error node in the trimmed graph. We just need to consult
  1109. // the node map (NMap) which maps from nodes in the original graph to nodes
  1110. // in the new graph.
  1111. std::queue<const ExplodedNode*> WS;
  1112. typedef llvm::DenseMap<const ExplodedNode*, unsigned> IndexMapTy;
  1113. IndexMapTy IndexMap;
  1114. for (unsigned nodeIndex = 0 ; nodeIndex < nodes.size(); ++nodeIndex) {
  1115. const ExplodedNode *originalNode = nodes[nodeIndex];
  1116. if (const ExplodedNode *N = NMap->getMappedNode(originalNode)) {
  1117. WS.push(N);
  1118. IndexMap[originalNode] = nodeIndex;
  1119. }
  1120. }
  1121. assert(!WS.empty() && "No error node found in the trimmed graph.");
  1122. // Create a new (third!) graph with a single path. This is the graph
  1123. // that will be returned to the caller.
  1124. ExplodedGraph *GNew = new ExplodedGraph();
  1125. // Sometimes the trimmed graph can contain a cycle. Perform a reverse BFS
  1126. // to the root node, and then construct a new graph that contains only
  1127. // a single path.
  1128. llvm::DenseMap<const void*,unsigned> Visited;
  1129. unsigned cnt = 0;
  1130. const ExplodedNode *Root = 0;
  1131. while (!WS.empty()) {
  1132. const ExplodedNode *Node = WS.front();
  1133. WS.pop();
  1134. if (Visited.find(Node) != Visited.end())
  1135. continue;
  1136. Visited[Node] = cnt++;
  1137. if (Node->pred_empty()) {
  1138. Root = Node;
  1139. break;
  1140. }
  1141. for (ExplodedNode::const_pred_iterator I=Node->pred_begin(),
  1142. E=Node->pred_end(); I!=E; ++I)
  1143. WS.push(*I);
  1144. }
  1145. assert(Root);
  1146. // Now walk from the root down the BFS path, always taking the successor
  1147. // with the lowest number.
  1148. ExplodedNode *Last = 0, *First = 0;
  1149. NodeBackMap *BM = new NodeBackMap();
  1150. unsigned NodeIndex = 0;
  1151. for ( const ExplodedNode *N = Root ;;) {
  1152. // Lookup the number associated with the current node.
  1153. llvm::DenseMap<const void*,unsigned>::iterator I = Visited.find(N);
  1154. assert(I != Visited.end());
  1155. // Create the equivalent node in the new graph with the same state
  1156. // and location.
  1157. ExplodedNode *NewN = GNew->getNode(N->getLocation(), N->getState());
  1158. // Store the mapping to the original node.
  1159. llvm::DenseMap<const void*, const void*>::iterator IMitr=InverseMap.find(N);
  1160. assert(IMitr != InverseMap.end() && "No mapping to original node.");
  1161. (*BM)[NewN] = (const ExplodedNode*) IMitr->second;
  1162. // Link up the new node with the previous node.
  1163. if (Last)
  1164. NewN->addPredecessor(Last, *GNew);
  1165. Last = NewN;
  1166. // Are we at the final node?
  1167. IndexMapTy::iterator IMI =
  1168. IndexMap.find((const ExplodedNode*)(IMitr->second));
  1169. if (IMI != IndexMap.end()) {
  1170. First = NewN;
  1171. NodeIndex = IMI->second;
  1172. break;
  1173. }
  1174. // Find the next successor node. We choose the node that is marked
  1175. // with the lowest DFS number.
  1176. ExplodedNode::const_succ_iterator SI = N->succ_begin();
  1177. ExplodedNode::const_succ_iterator SE = N->succ_end();
  1178. N = 0;
  1179. for (unsigned MinVal = 0; SI != SE; ++SI) {
  1180. I = Visited.find(*SI);
  1181. if (I == Visited.end())
  1182. continue;
  1183. if (!N || I->second < MinVal) {
  1184. N = *SI;
  1185. MinVal = I->second;
  1186. }
  1187. }
  1188. assert(N);
  1189. }
  1190. assert(First);
  1191. return std::make_pair(std::make_pair(GNew, BM),
  1192. std::make_pair(First, NodeIndex));
  1193. }
  1194. /// CompactPathDiagnostic - This function postprocesses a PathDiagnostic object
  1195. /// and collapses PathDiagosticPieces that are expanded by macros.
  1196. static void CompactPathDiagnostic(PathDiagnostic &PD, const SourceManager& SM) {
  1197. typedef std::vector<std::pair<PathDiagnosticMacroPiece*, SourceLocation> >
  1198. MacroStackTy;
  1199. typedef std::vector<PathDiagnosticPiece*>
  1200. PiecesTy;
  1201. MacroStackTy MacroStack;
  1202. PiecesTy Pieces;
  1203. for (PathDiagnostic::iterator I = PD.begin(), E = PD.end(); I!=E; ++I) {
  1204. // Get the location of the PathDiagnosticPiece.
  1205. const FullSourceLoc Loc = I->getLocation().asLocation();
  1206. // Determine the instantiation location, which is the location we group
  1207. // related PathDiagnosticPieces.
  1208. SourceLocation InstantiationLoc = Loc.isMacroID() ?
  1209. SM.getExpansionLoc(Loc) :
  1210. SourceLocation();
  1211. if (Loc.isFileID()) {
  1212. MacroStack.clear();
  1213. Pieces.push_back(&*I);
  1214. continue;
  1215. }
  1216. assert(Loc.isMacroID());
  1217. // Is the PathDiagnosticPiece within the same macro group?
  1218. if (!MacroStack.empty() && InstantiationLoc == MacroStack.back().second) {
  1219. MacroStack.back().first->push_back(&*I);
  1220. continue;
  1221. }
  1222. // We aren't in the same group. Are we descending into a new macro
  1223. // or are part of an old one?
  1224. PathDiagnosticMacroPiece *MacroGroup = 0;
  1225. SourceLocation ParentInstantiationLoc = InstantiationLoc.isMacroID() ?
  1226. SM.getExpansionLoc(Loc) :
  1227. SourceLocation();
  1228. // Walk the entire macro stack.
  1229. while (!MacroStack.empty()) {
  1230. if (InstantiationLoc == MacroStack.back().second) {
  1231. MacroGroup = MacroStack.back().first;
  1232. break;
  1233. }
  1234. if (ParentInstantiationLoc == MacroStack.back().second) {
  1235. MacroGroup = MacroStack.back().first;
  1236. break;
  1237. }
  1238. MacroStack.pop_back();
  1239. }
  1240. if (!MacroGroup || ParentInstantiationLoc == MacroStack.back().second) {
  1241. // Create a new macro group and add it to the stack.
  1242. PathDiagnosticMacroPiece *NewGroup = new PathDiagnosticMacroPiece(Loc);
  1243. if (MacroGroup)
  1244. MacroGroup->push_back(NewGroup);
  1245. else {
  1246. assert(InstantiationLoc.isFileID());
  1247. Pieces.push_back(NewGroup);
  1248. }
  1249. MacroGroup = NewGroup;
  1250. MacroStack.push_back(std::make_pair(MacroGroup, InstantiationLoc));
  1251. }
  1252. // Finally, add the PathDiagnosticPiece to the group.
  1253. MacroGroup->push_back(&*I);
  1254. }
  1255. // Now take the pieces and construct a new PathDiagnostic.
  1256. PD.resetPath(false);
  1257. for (PiecesTy::iterator I=Pieces.begin(), E=Pieces.end(); I!=E; ++I) {
  1258. if (PathDiagnosticMacroPiece *MP=dyn_cast<PathDiagnosticMacroPiece>(*I))
  1259. if (!MP->containsEvent()) {
  1260. delete MP;
  1261. continue;
  1262. }
  1263. PD.push_back(*I);
  1264. }
  1265. }
  1266. void GRBugReporter::GeneratePathDiagnostic(PathDiagnostic& PD,
  1267. SmallVectorImpl<BugReport *> &bugReports) {
  1268. assert(!bugReports.empty());
  1269. SmallVector<const ExplodedNode *, 10> errorNodes;
  1270. for (SmallVectorImpl<BugReport*>::iterator I = bugReports.begin(),
  1271. E = bugReports.end(); I != E; ++I) {
  1272. errorNodes.push_back((*I)->getErrorNode());
  1273. }
  1274. // Construct a new graph that contains only a single path from the error
  1275. // node to a root.
  1276. const std::pair<std::pair<ExplodedGraph*, NodeBackMap*>,
  1277. std::pair<ExplodedNode*, unsigned> >&
  1278. GPair = MakeReportGraph(&getGraph(), errorNodes);
  1279. // Find the BugReport with the original location.
  1280. assert(GPair.second.second < bugReports.size());
  1281. BugReport *R = bugReports[GPair.second.second];
  1282. assert(R && "No original report found for sliced graph.");
  1283. llvm::OwningPtr<ExplodedGraph> ReportGraph(GPair.first.first);
  1284. llvm::OwningPtr<NodeBackMap> BackMap(GPair.first.second);
  1285. const ExplodedNode *N = GPair.second.first;
  1286. // Start building the path diagnostic...
  1287. PathDiagnosticBuilder PDB(*this, R, BackMap.get(), getPathDiagnosticClient());
  1288. // Register additional node visitors.
  1289. R->addVisitor(new NilReceiverBRVisitor());
  1290. R->addVisitor(new ConditionBRVisitor());
  1291. // Generate the very last diagnostic piece - the piece is visible before
  1292. // the trace is expanded.
  1293. PathDiagnosticPiece *LastPiece = 0;
  1294. for (BugReport::visitor_iterator I = R->visitor_begin(),
  1295. E = R->visitor_end(); I!=E; ++I) {
  1296. if (PathDiagnosticPiece *Piece = (*I)->getEndPath(PDB, N, *R)) {
  1297. assert (!LastPiece &&
  1298. "There can only be one final piece in a diagnostic.");
  1299. LastPiece = Piece;
  1300. }
  1301. }
  1302. if (!LastPiece)
  1303. LastPiece = BugReporterVisitor::getDefaultEndPath(PDB, N, *R);
  1304. if (LastPiece)
  1305. PD.push_back(LastPiece);
  1306. else
  1307. return;
  1308. switch (PDB.getGenerationScheme()) {
  1309. case PathDiagnosticClient::Extensive:
  1310. GenerateExtensivePathDiagnostic(PD, PDB, N);
  1311. break;
  1312. case PathDiagnosticClient::Minimal:
  1313. GenerateMinimalPathDiagnostic(PD, PDB, N);
  1314. break;
  1315. }
  1316. }
  1317. void BugReporter::Register(BugType *BT) {
  1318. BugTypes = F.add(BugTypes, BT);
  1319. }
  1320. void BugReporter::EmitReport(BugReport* R) {
  1321. // Compute the bug report's hash to determine its equivalence class.
  1322. llvm::FoldingSetNodeID ID;
  1323. R->Profile(ID);
  1324. // Lookup the equivance class. If there isn't one, create it.
  1325. BugType& BT = R->getBugType();
  1326. Register(&BT);
  1327. void *InsertPos;
  1328. BugReportEquivClass* EQ = EQClasses.FindNodeOrInsertPos(ID, InsertPos);
  1329. if (!EQ) {
  1330. EQ = new BugReportEquivClass(R);
  1331. EQClasses.InsertNode(EQ, InsertPos);
  1332. EQClassesVector.push_back(EQ);
  1333. }
  1334. else
  1335. EQ->AddReport(R);
  1336. }
  1337. //===----------------------------------------------------------------------===//
  1338. // Emitting reports in equivalence classes.
  1339. //===----------------------------------------------------------------------===//
  1340. namespace {
  1341. struct FRIEC_WLItem {
  1342. const ExplodedNode *N;
  1343. ExplodedNode::const_succ_iterator I, E;
  1344. FRIEC_WLItem(const ExplodedNode *n)
  1345. : N(n), I(N->succ_begin()), E(N->succ_end()) {}
  1346. };
  1347. }
  1348. static BugReport *
  1349. FindReportInEquivalenceClass(BugReportEquivClass& EQ,
  1350. SmallVectorImpl<BugReport*> &bugReports) {
  1351. BugReportEquivClass::iterator I = EQ.begin(), E = EQ.end();
  1352. assert(I != E);
  1353. BugReport *R = *I;
  1354. BugType& BT = R->getBugType();
  1355. // If we don't need to suppress any of the nodes because they are
  1356. // post-dominated by a sink, simply add all the nodes in the equivalence class
  1357. // to 'Nodes'. Any of the reports will serve as a "representative" report.
  1358. if (!BT.isSuppressOnSink()) {
  1359. for (BugReportEquivClass::iterator I=EQ.begin(), E=EQ.end(); I!=E; ++I) {
  1360. const ExplodedNode *N = I->getErrorNode();
  1361. if (N) {
  1362. R = *I;
  1363. bugReports.push_back(R);
  1364. }
  1365. }
  1366. return R;
  1367. }
  1368. // For bug reports that should be suppressed when all paths are post-dominated
  1369. // by a sink node, iterate through the reports in the equivalence class
  1370. // until we find one that isn't post-dominated (if one exists). We use a
  1371. // DFS traversal of the ExplodedGraph to find a non-sink node. We could write
  1372. // this as a recursive function, but we don't want to risk blowing out the
  1373. // stack for very long paths.
  1374. BugReport *exampleReport = 0;
  1375. for (; I != E; ++I) {
  1376. R = *I;
  1377. const ExplodedNode *errorNode = R->getErrorNode();
  1378. if (!errorNode)
  1379. continue;
  1380. if (errorNode->isSink()) {
  1381. assert(false &&
  1382. "BugType::isSuppressSink() should not be 'true' for sink end nodes");
  1383. return 0;
  1384. }
  1385. // No successors? By definition this nodes isn't post-dominated by a sink.
  1386. if (errorNode->succ_empty()) {
  1387. bugReports.push_back(R);
  1388. if (!exampleReport)
  1389. exampleReport = R;
  1390. continue;
  1391. }
  1392. // At this point we know that 'N' is not a sink and it has at least one
  1393. // successor. Use a DFS worklist to find a non-sink end-of-path node.
  1394. typedef FRIEC_WLItem WLItem;
  1395. typedef SmallVector<WLItem, 10> DFSWorkList;
  1396. llvm::DenseMap<const ExplodedNode *, unsigned> Visited;
  1397. DFSWorkList WL;
  1398. WL.push_back(errorNode);
  1399. Visited[errorNode] = 1;
  1400. while (!WL.empty()) {
  1401. WLItem &WI = WL.back();
  1402. assert(!WI.N->succ_empty());
  1403. for (; WI.I != WI.E; ++WI.I) {
  1404. const ExplodedNode *Succ = *WI.I;
  1405. // End-of-path node?
  1406. if (Succ->succ_empty()) {
  1407. // If we found an end-of-path node that is not a sink.
  1408. if (!Succ->isSink()) {
  1409. bugReports.push_back(R);
  1410. if (!exampleReport)
  1411. exampleReport = R;
  1412. WL.clear();
  1413. break;
  1414. }
  1415. // Found a sink? Continue on to the next successor.
  1416. continue;
  1417. }
  1418. // Mark the successor as visited. If it hasn't been explored,
  1419. // enqueue it to the DFS worklist.
  1420. unsigned &mark = Visited[Succ];
  1421. if (!mark) {
  1422. mark = 1;
  1423. WL.push_back(Succ);
  1424. break;
  1425. }
  1426. }
  1427. // The worklist may have been cleared at this point. First
  1428. // check if it is empty before checking the last item.
  1429. if (!WL.empty() && &WL.back() == &WI)
  1430. WL.pop_back();
  1431. }
  1432. }
  1433. // ExampleReport will be NULL if all the nodes in the equivalence class
  1434. // were post-dominated by sinks.
  1435. return exampleReport;
  1436. }
  1437. //===----------------------------------------------------------------------===//
  1438. // DiagnosticCache. This is a hack to cache analyzer diagnostics. It
  1439. // uses global state, which eventually should go elsewhere.
  1440. //===----------------------------------------------------------------------===//
  1441. namespace {
  1442. class DiagCacheItem : public llvm::FoldingSetNode {
  1443. llvm::FoldingSetNodeID ID;
  1444. public:
  1445. DiagCacheItem(BugReport *R, PathDiagnostic *PD) {
  1446. ID.AddString(R->getBugType().getName());
  1447. ID.AddString(R->getBugType().getCategory());
  1448. ID.AddString(R->getDescription());
  1449. ID.AddInteger(R->getLocation().getRawEncoding());
  1450. PD->Profile(ID);
  1451. }
  1452. void Profile(llvm::FoldingSetNodeID &id) {
  1453. id = ID;
  1454. }
  1455. llvm::FoldingSetNodeID &getID() { return ID; }
  1456. };
  1457. }
  1458. static bool IsCachedDiagnostic(BugReport *R, PathDiagnostic *PD) {
  1459. // FIXME: Eventually this diagnostic cache should reside in something
  1460. // like AnalysisManager instead of being a static variable. This is
  1461. // really unsafe in the long term.
  1462. typedef llvm::FoldingSet<DiagCacheItem> DiagnosticCache;
  1463. static DiagnosticCache DC;
  1464. void *InsertPos;
  1465. DiagCacheItem *Item = new DiagCacheItem(R, PD);
  1466. if (DC.FindNodeOrInsertPos(Item->getID(), InsertPos)) {
  1467. delete Item;
  1468. return true;
  1469. }
  1470. DC.InsertNode(Item, InsertPos);
  1471. return false;
  1472. }
  1473. void BugReporter::FlushReport(BugReportEquivClass& EQ) {
  1474. SmallVector<BugReport*, 10> bugReports;
  1475. BugReport *exampleReport = FindReportInEquivalenceClass(EQ, bugReports);
  1476. if (!exampleReport)
  1477. return;
  1478. PathDiagnosticClient* PD = getPathDiagnosticClient();
  1479. // FIXME: Make sure we use the 'R' for the path that was actually used.
  1480. // Probably doesn't make a difference in practice.
  1481. BugType& BT = exampleReport->getBugType();
  1482. llvm::OwningPtr<PathDiagnostic>
  1483. D(new PathDiagnostic(exampleReport->getBugType().getName(),
  1484. !PD || PD->useVerboseDescription()
  1485. ? exampleReport->getDescription()
  1486. : exampleReport->getShortDescription(),
  1487. BT.getCategory()));
  1488. if (!bugReports.empty())
  1489. GeneratePathDiagnostic(*D.get(), bugReports);
  1490. if (IsCachedDiagnostic(exampleReport, D.get()))
  1491. return;
  1492. // Get the meta data.
  1493. std::pair<const char**, const char**> Meta =
  1494. exampleReport->getExtraDescriptiveText();
  1495. for (const char** s = Meta.first; s != Meta.second; ++s)
  1496. D->addMeta(*s);
  1497. // Emit a summary diagnostic to the regular Diagnostics engine.
  1498. BugReport::ranges_iterator Beg, End;
  1499. llvm::tie(Beg, End) = exampleReport->getRanges();
  1500. Diagnostic &Diag = getDiagnostic();
  1501. FullSourceLoc L(exampleReport->getLocation(), getSourceManager());
  1502. // Search the description for '%', as that will be interpretted as a
  1503. // format character by FormatDiagnostics.
  1504. StringRef desc = exampleReport->getShortDescription();
  1505. unsigned ErrorDiag;
  1506. {
  1507. llvm::SmallString<512> TmpStr;
  1508. llvm::raw_svector_ostream Out(TmpStr);
  1509. for (StringRef::iterator I=desc.begin(), E=desc.end(); I!=E; ++I)
  1510. if (*I == '%')
  1511. Out << "%%";
  1512. else
  1513. Out << *I;
  1514. Out.flush();
  1515. ErrorDiag = Diag.getCustomDiagID(Diagnostic::Warning, TmpStr);
  1516. }
  1517. {
  1518. DiagnosticBuilder diagBuilder = Diag.Report(L, ErrorDiag);
  1519. for (BugReport::ranges_iterator I = Beg; I != End; ++I)
  1520. diagBuilder << *I;
  1521. }
  1522. // Emit a full diagnostic for the path if we have a PathDiagnosticClient.
  1523. if (!PD)
  1524. return;
  1525. if (D->empty()) {
  1526. PathDiagnosticPiece *piece =
  1527. new PathDiagnosticEventPiece(L, exampleReport->getDescription());
  1528. for ( ; Beg != End; ++Beg) piece->addRange(*Beg);
  1529. D->push_back(piece);
  1530. }
  1531. PD->HandlePathDiagnostic(D.take());
  1532. }
  1533. void BugReporter::EmitBasicReport(StringRef name, StringRef str,
  1534. SourceLocation Loc,
  1535. SourceRange* RBeg, unsigned NumRanges) {
  1536. EmitBasicReport(name, "", str, Loc, RBeg, NumRanges);
  1537. }
  1538. void BugReporter::EmitBasicReport(StringRef name,
  1539. StringRef category,
  1540. StringRef str, SourceLocation Loc,
  1541. SourceRange* RBeg, unsigned NumRanges) {
  1542. // 'BT' is owned by BugReporter.
  1543. BugType *BT = getBugTypeForName(name, category);
  1544. FullSourceLoc L = getContext().getFullLoc(Loc);
  1545. BugReport *R = new BugReport(*BT, str, L);
  1546. for ( ; NumRanges > 0 ; --NumRanges, ++RBeg) R->addRange(*RBeg);
  1547. EmitReport(R);
  1548. }
  1549. BugType *BugReporter::getBugTypeForName(StringRef name,
  1550. StringRef category) {
  1551. llvm::SmallString<136> fullDesc;
  1552. llvm::raw_svector_ostream(fullDesc) << name << ":" << category;
  1553. llvm::StringMapEntry<BugType *> &
  1554. entry = StrBugTypes.GetOrCreateValue(fullDesc);
  1555. BugType *BT = entry.getValue();
  1556. if (!BT) {
  1557. BT = new BugType(name, category);
  1558. entry.setValue(BT);
  1559. }
  1560. return BT;
  1561. }