1 //=== LLVMConventionsChecker.cpp - Check LLVM codebase conventions ---*- C++ -*-
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This defines LLVMConventionsChecker, a bunch of small little checks
11 // for checking specific coding conventions in the LLVM/Clang codebase.
13 //===----------------------------------------------------------------------===//
15 #include "ClangSACheckers.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/StmtVisitor.h"
18 #include "clang/StaticAnalyzer/Core/BugReporter/BugReporter.h"
19 #include "clang/StaticAnalyzer/Core/Checker.h"
20 #include "llvm/ADT/SmallString.h"
21 #include "llvm/Support/raw_ostream.h"
23 using namespace clang;
26 //===----------------------------------------------------------------------===//
27 // Generic type checking routines.
28 //===----------------------------------------------------------------------===//
30 static bool IsLLVMStringRef(QualType T) {
31 const RecordType *RT = T->getAs<RecordType>();
35 return StringRef(QualType(RT, 0).getAsString()) ==
39 /// Check whether the declaration is semantically inside the top-level
40 /// namespace named by ns.
41 static bool InNamespace(const Decl *D, StringRef NS) {
42 const NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D->getDeclContext());
45 const IdentifierInfo *II = ND->getIdentifier();
46 if (!II || !II->getName().equals(NS))
48 return isa<TranslationUnitDecl>(ND->getDeclContext());
51 static bool IsStdString(QualType T) {
52 if (const ElaboratedType *QT = T->getAs<ElaboratedType>())
53 T = QT->getNamedType();
55 const TypedefType *TT = T->getAs<TypedefType>();
59 const TypedefNameDecl *TD = TT->getDecl();
61 if (!InNamespace(TD, "std"))
64 return TD->getName() == "string";
67 static bool IsClangType(const RecordDecl *RD) {
68 return RD->getName() == "Type" && InNamespace(RD, "clang");
71 static bool IsClangDecl(const RecordDecl *RD) {
72 return RD->getName() == "Decl" && InNamespace(RD, "clang");
75 static bool IsClangStmt(const RecordDecl *RD) {
76 return RD->getName() == "Stmt" && InNamespace(RD, "clang");
79 static bool IsClangAttr(const RecordDecl *RD) {
80 return RD->getName() == "Attr" && InNamespace(RD, "clang");
83 static bool IsStdVector(QualType T) {
84 const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
88 TemplateName TM = TS->getTemplateName();
89 TemplateDecl *TD = TM.getAsTemplateDecl();
91 if (!TD || !InNamespace(TD, "std"))
94 return TD->getName() == "vector";
97 static bool IsSmallVector(QualType T) {
98 const TemplateSpecializationType *TS = T->getAs<TemplateSpecializationType>();
102 TemplateName TM = TS->getTemplateName();
103 TemplateDecl *TD = TM.getAsTemplateDecl();
105 if (!TD || !InNamespace(TD, "llvm"))
108 return TD->getName() == "SmallVector";
111 //===----------------------------------------------------------------------===//
112 // CHECK: a StringRef should not be bound to a temporary std::string whose
113 // lifetime is shorter than the StringRef's.
114 //===----------------------------------------------------------------------===//
117 class StringRefCheckerVisitor : public StmtVisitor<StringRefCheckerVisitor> {
119 const Decl *DeclWithIssue;
121 StringRefCheckerVisitor(const Decl *declWithIssue, BugReporter &br)
122 : BR(br), DeclWithIssue(declWithIssue) {}
123 void VisitChildren(Stmt *S) {
124 for (Stmt::child_iterator I = S->child_begin(), E = S->child_end() ;
126 if (Stmt *child = *I)
129 void VisitStmt(Stmt *S) { VisitChildren(S); }
130 void VisitDeclStmt(DeclStmt *DS);
132 void VisitVarDecl(VarDecl *VD);
134 } // end anonymous namespace
136 static void CheckStringRefAssignedTemporary(const Decl *D, BugReporter &BR) {
137 StringRefCheckerVisitor walker(D, BR);
138 walker.Visit(D->getBody());
141 void StringRefCheckerVisitor::VisitDeclStmt(DeclStmt *S) {
144 for (DeclStmt::decl_iterator I = S->decl_begin(), E = S->decl_end();I!=E; ++I)
145 if (VarDecl *VD = dyn_cast<VarDecl>(*I))
149 void StringRefCheckerVisitor::VisitVarDecl(VarDecl *VD) {
150 Expr *Init = VD->getInit();
154 // Pattern match for:
155 // StringRef x = call() (where call returns std::string)
156 if (!IsLLVMStringRef(VD->getType()))
158 ExprWithCleanups *Ex1 = dyn_cast<ExprWithCleanups>(Init);
161 CXXConstructExpr *Ex2 = dyn_cast<CXXConstructExpr>(Ex1->getSubExpr());
162 if (!Ex2 || Ex2->getNumArgs() != 1)
164 ImplicitCastExpr *Ex3 = dyn_cast<ImplicitCastExpr>(Ex2->getArg(0));
167 CXXConstructExpr *Ex4 = dyn_cast<CXXConstructExpr>(Ex3->getSubExpr());
168 if (!Ex4 || Ex4->getNumArgs() != 1)
170 ImplicitCastExpr *Ex5 = dyn_cast<ImplicitCastExpr>(Ex4->getArg(0));
173 CXXBindTemporaryExpr *Ex6 = dyn_cast<CXXBindTemporaryExpr>(Ex5->getSubExpr());
174 if (!Ex6 || !IsStdString(Ex6->getType()))
177 // Okay, badness! Report an error.
178 const char *desc = "StringRef should not be bound to temporary "
179 "std::string that it outlives";
180 PathDiagnosticLocation VDLoc =
181 PathDiagnosticLocation::createBegin(VD, BR.getSourceManager());
182 BR.EmitBasicReport(DeclWithIssue, desc, "LLVM Conventions", desc,
183 VDLoc, Init->getSourceRange());
186 //===----------------------------------------------------------------------===//
187 // CHECK: Clang AST nodes should not have fields that can allocate
189 //===----------------------------------------------------------------------===//
191 static bool AllocatesMemory(QualType T) {
192 return IsStdVector(T) || IsStdString(T) || IsSmallVector(T);
195 // This type checking could be sped up via dynamic programming.
196 static bool IsPartOfAST(const CXXRecordDecl *R) {
197 if (IsClangStmt(R) || IsClangType(R) || IsClangDecl(R) || IsClangAttr(R))
200 for (CXXRecordDecl::base_class_const_iterator I = R->bases_begin(),
201 E = R->bases_end(); I!=E; ++I) {
202 CXXBaseSpecifier BS = *I;
203 QualType T = BS.getType();
204 if (const RecordType *baseT = T->getAs<RecordType>()) {
205 CXXRecordDecl *baseD = cast<CXXRecordDecl>(baseT->getDecl());
206 if (IsPartOfAST(baseD))
215 class ASTFieldVisitor {
216 SmallVector<FieldDecl*, 10> FieldChain;
217 const CXXRecordDecl *Root;
220 ASTFieldVisitor(const CXXRecordDecl *root, BugReporter &br)
221 : Root(root), BR(br) {}
223 void Visit(FieldDecl *D);
224 void ReportError(QualType T);
226 } // end anonymous namespace
228 static void CheckASTMemory(const CXXRecordDecl *R, BugReporter &BR) {
232 for (RecordDecl::field_iterator I = R->field_begin(), E = R->field_end();
234 ASTFieldVisitor walker(R, BR);
239 void ASTFieldVisitor::Visit(FieldDecl *D) {
240 FieldChain.push_back(D);
242 QualType T = D->getType();
244 if (AllocatesMemory(T))
247 if (const RecordType *RT = T->getAs<RecordType>()) {
248 const RecordDecl *RD = RT->getDecl()->getDefinition();
249 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
254 FieldChain.pop_back();
257 void ASTFieldVisitor::ReportError(QualType T) {
258 SmallString<1024> buf;
259 llvm::raw_svector_ostream os(buf);
261 os << "AST class '" << Root->getName() << "' has a field '"
262 << FieldChain.front()->getName() << "' that allocates heap memory";
263 if (FieldChain.size() > 1) {
264 os << " via the following chain: ";
266 for (SmallVectorImpl<FieldDecl*>::iterator I=FieldChain.begin(),
267 E=FieldChain.end(); I!=E; ++I) {
272 os << (*I)->getName();
275 os << " (type " << FieldChain.back()->getType().getAsString() << ")";
278 // Note that this will fire for every translation unit that uses this
279 // class. This is suboptimal, but at least scan-build will merge
280 // duplicate HTML reports. In the future we need a unified way of merging
281 // duplicate reports across translation units. For C++ classes we cannot
282 // just report warnings when we see an out-of-line method definition for a
283 // class, as that heuristic doesn't always work (the complete definition of
284 // the class may be in the header file, for example).
285 PathDiagnosticLocation L = PathDiagnosticLocation::createBegin(
286 FieldChain.front(), BR.getSourceManager());
287 BR.EmitBasicReport(Root, "AST node allocates heap memory", "LLVM Conventions",
291 //===----------------------------------------------------------------------===//
292 // LLVMConventionsChecker
293 //===----------------------------------------------------------------------===//
296 class LLVMConventionsChecker : public Checker<
297 check::ASTDecl<CXXRecordDecl>,
298 check::ASTCodeBody > {
300 void checkASTDecl(const CXXRecordDecl *R, AnalysisManager& mgr,
301 BugReporter &BR) const {
302 if (R->isCompleteDefinition())
303 CheckASTMemory(R, BR);
306 void checkASTCodeBody(const Decl *D, AnalysisManager& mgr,
307 BugReporter &BR) const {
308 CheckStringRefAssignedTemporary(D, BR);
313 void ento::registerLLVMConventionsChecker(CheckerManager &mgr) {
314 mgr.registerChecker<LLVMConventionsChecker>();