BugReporter.cpp 61 KB

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