clang 24.0.0git
ASTUtils.cpp
Go to the documentation of this file.
1//=======- ASTUtils.cpp ------------------------------------------*- C++ -*-==//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "ASTUtils.h"
10#include "PtrTypesSemantics.h"
11#include "clang/AST/Attr.h"
12#include "clang/AST/Decl.h"
13#include "clang/AST/DeclCXX.h"
14#include "clang/AST/ExprCXX.h"
15#include "clang/AST/ExprObjC.h"
17#include <optional>
18
19namespace clang {
20
24
26 const Expr *E, bool StopAtFirstRefCountedObj,
28 std::function<bool(const clang::QualType)> isSafePtrType,
29 std::function<bool(const clang::Decl *)> isSafeGlobalDecl,
30 std::function<bool(const clang::Expr *, bool)> callback) {
31 while (E) {
32 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
33 if (auto *VD = dyn_cast_or_null<VarDecl>(DRE->getDecl())) {
34 auto QT = VD->getType();
35 auto IsImmortal = safeGetName(VD) == "NSApp";
36 if (VD->hasGlobalStorage() && (IsImmortal || QT.isConstQualified()))
37 return callback(E, true);
38 if (VD->hasGlobalStorage() && isSafeGlobalDecl(VD))
39 return callback(E, true);
40 }
41 }
42 if (auto *tempExpr = dyn_cast<MaterializeTemporaryExpr>(E)) {
43 E = tempExpr->getSubExpr();
44 continue;
45 }
46 if (auto *tempExpr = dyn_cast<CXXBindTemporaryExpr>(E)) {
47 E = tempExpr->getSubExpr();
48 continue;
49 }
50 if (auto *tempExpr = dyn_cast<CXXConstructExpr>(E)) {
51 if (auto *C = tempExpr->getConstructor()) {
52 if (auto *Class = C->getParent(); Class && isSafePtr(Class))
53 return callback(E, true);
54 break;
55 }
56 }
57 if (auto *TempExpr = dyn_cast<CXXUnresolvedConstructExpr>(E)) {
58 if (isSafePtrType(TempExpr->getTypeAsWritten()))
59 return callback(TempExpr, true);
60 }
61 if (auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
62 if (auto *RF = POE->getResultExpr()) {
63 E = RF;
64 continue;
65 }
66 }
67 if (auto *tempExpr = dyn_cast<ParenExpr>(E)) {
68 E = tempExpr->getSubExpr();
69 continue;
70 }
71 if (auto *OpaqueValue = dyn_cast<OpaqueValueExpr>(E)) {
72 E = OpaqueValue->getSourceExpr();
73 continue;
74 }
75 if (auto *Expr = dyn_cast<ConditionalOperator>(E)) {
76 return tryToFindPtrOrigin(Expr->getTrueExpr(), StopAtFirstRefCountedObj,
77 isSafePtr, isSafePtrType, isSafeGlobalDecl,
78 callback) &&
79 tryToFindPtrOrigin(Expr->getFalseExpr(), StopAtFirstRefCountedObj,
80 isSafePtr, isSafePtrType, isSafeGlobalDecl,
81 callback);
82 }
83 if (auto *cast = dyn_cast<CastExpr>(E)) {
84 if (StopAtFirstRefCountedObj) {
85 if (auto *ConversionFunc =
86 dyn_cast_or_null<FunctionDecl>(cast->getConversionFunction())) {
87 if (isCtorOfSafePtr(ConversionFunc))
88 return callback(E, true);
89 }
90 if (isa<CXXFunctionalCastExpr>(E) && isSafePtrType(cast->getType()))
91 return callback(E, true);
92 }
93 // FIXME: This can give false "origin" that would lead to false negatives
94 // in checkers. See https://reviews.llvm.org/D37023 for reference.
95 E = cast->getSubExpr();
96 continue;
97 }
98 if (auto *call = dyn_cast<CallExpr>(E)) {
99 if (auto *Callee = call->getCalleeDecl()) {
100 if (Callee->hasAttr<CFReturnsRetainedAttr>() ||
101 Callee->hasAttr<NSReturnsRetainedAttr>() ||
102 Callee->hasAttr<NSReturnsAutoreleasedAttr>()) {
103 return callback(E, true);
104 }
105 }
106
107 if (isSafePtrType(call->getType()))
108 return callback(E, true);
109
110 if (auto *memberCall = dyn_cast<CXXMemberCallExpr>(call)) {
111 if (auto *decl = memberCall->getMethodDecl()) {
112 std::optional<bool> IsGetterOfRefCt = isGetterOfSafePtr(decl);
113 if (IsGetterOfRefCt && *IsGetterOfRefCt) {
114 E = memberCall->getImplicitObjectArgument()->IgnoreParenCasts();
115 if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
116 if (auto *Decl = dyn_cast_or_null<VarDecl>(DRE->getDecl())) {
117 if (Decl->isLocalVarDeclOrParm()) {
118 if (StopAtFirstRefCountedObj)
119 return callback(E, true);
120 }
121 }
122 }
123 continue;
124 }
125 }
126 }
127
128 if (auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(E)) {
129 if (auto *Callee = operatorCall->getDirectCallee()) {
130 auto ClsName = safeGetName(Callee->getParent());
131 if (isRefType(ClsName) || isCheckedPtr(ClsName) ||
132 isRetainPtrOrOSPtr(ClsName) || ClsName == "unique_ptr" ||
133 ClsName == "UniqueRef" || ClsName == "WeakPtr" ||
134 ClsName == "WeakRef") {
135 if (operatorCall->getNumArgs() == 1) {
136 E = operatorCall->getArg(0);
137 continue;
138 }
139 }
140 }
141 }
142
143 if (auto *callee = call->getDirectCallee()) {
144 if (isCtorOfSafePtr(callee)) {
145 if (StopAtFirstRefCountedObj)
146 return callback(E, true);
147
148 E = call->getArg(0);
149 continue;
150 }
151
152 if (isStdOrWTFMove(callee) && call->getNumArgs() == 1) {
153 E = call->getArg(0)->IgnoreParenCasts();
154 continue;
155 }
156
157 if (isSafePtrType(callee->getReturnType()))
158 return callback(E, true);
159
160 if (isSingleton(callee))
161 return callback(E, true);
162
163 if (callee->isInStdNamespace() && safeGetName(callee) == "forward") {
164 E = call->getArg(0);
165 continue;
166 }
167
168 if (isPtrConversion(callee)) {
169 E = call->getArg(0);
170 continue;
171 }
172
173 auto Name = safeGetName(callee);
174 if (Name == "__builtin___CFStringMakeConstantString" ||
175 Name == "NSStringFromSelector" || Name == "NSSelectorFromString" ||
176 Name == "NSStringFromClass" || Name == "NSClassFromString" ||
177 Name == "NSStringFromProtocol" || Name == "NSProtocolFromString")
178 return callback(E, true);
179 } else if (auto *CalleeE = call->getCallee()) {
180 if (auto *E = dyn_cast<DeclRefExpr>(CalleeE->IgnoreParenCasts())) {
181 if (isSingleton(E->getFoundDecl()))
182 return callback(E, true);
183 }
184
185 if (auto *MemberExpr = dyn_cast<CXXDependentScopeMemberExpr>(CalleeE)) {
186 auto *Base = MemberExpr->getBase();
187 auto MemberName = MemberExpr->getMember().getAsString();
188 bool IsGetter = MemberName == "get" || MemberName == "ptr";
189 if (Base && isSafePtrType(Base->getType()) && IsGetter)
190 return callback(E, true);
191 }
192 }
193
194 // Sometimes, canonical type erroneously turns Ref<T> into T.
195 // Workaround this problem by checking again if the original type was
196 // a SubstTemplateTypeParmType of a safe smart pointer type (e.g. Ref).
197 if (auto *CalleeDecl = call->getCalleeDecl()) {
198 if (auto *FD = dyn_cast<FunctionDecl>(CalleeDecl)) {
199 auto RetType = FD->getReturnType();
200 if (auto *Subst = dyn_cast<SubstTemplateTypeParmType>(RetType)) {
201 if (auto *SubstType = Subst->desugar().getTypePtr()) {
202 if (auto *RD = dyn_cast<RecordType>(SubstType)) {
203 if (auto *CXX = dyn_cast<CXXRecordDecl>(RD->getDecl()))
204 if (isSafePtr(CXX))
205 return callback(E, true);
206 }
207 }
208 }
209 }
210 }
211 }
212 if (auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(E)) {
213 if (auto *Method = ObjCMsgExpr->getMethodDecl()) {
214 if (isSafePtrType(Method->getReturnType()))
215 return callback(E, true);
216 }
217 if (ObjCMsgExpr->isClassMessage())
218 return callback(E, true);
219 auto Selector = ObjCMsgExpr->getSelector();
220 auto NameForFirstSlot = Selector.getNameForSlot(0);
221 if ((NameForFirstSlot == "class" || NameForFirstSlot == "superclass") &&
223 return callback(E, true);
224 }
225 if (auto *ObjCProtocol = dyn_cast<ObjCProtocolExpr>(E))
226 return callback(ObjCProtocol, true);
227 if (auto *ObjCDict = dyn_cast<ObjCDictionaryLiteral>(E))
228 return callback(ObjCDict, true);
229 if (auto *ObjCArray = dyn_cast<ObjCArrayLiteral>(E))
230 return callback(ObjCArray, true);
231 if (auto *ObjCStr = dyn_cast<ObjCStringLiteral>(E))
232 return callback(ObjCStr, true);
233 if (auto *unaryOp = dyn_cast<UnaryOperator>(E)) {
234 // FIXME: Currently accepts ANY unary operator. Is it OK?
235 E = unaryOp->getSubExpr();
236 continue;
237 }
238 if (auto *BoxedExpr = dyn_cast<ObjCBoxedExpr>(E)) {
239 if (StopAtFirstRefCountedObj)
240 return callback(BoxedExpr, true);
241 E = BoxedExpr->getSubExpr();
242 continue;
243 }
244 break;
245 }
246 // Some other expression.
247 return callback(E, false);
248}
249
250bool isASafeCallArg(const Expr *E) {
251 assert(E);
252 auto IsCheckedLocalVarOrParam = [](const VarDecl *Decl) {
253 auto Ty = Decl->getType();
254 const CXXRecordDecl *CXXRD = Ty->getAsCXXRecordDecl();
255 if (!CXXRD)
256 CXXRD = Ty->getPointeeCXXRecordDecl();
257 if (CXXRD && isWeakPtr(CXXRD))
258 return false;
259 return Decl->isLocalVarDeclOrParm();
260 };
261 if (auto *Ref = dyn_cast<DeclRefExpr>(E)) {
262 auto *FoundDecl = Ref->getFoundDecl();
263 if (auto *D = dyn_cast_or_null<VarDecl>(FoundDecl)) {
264 if (IsCheckedLocalVarOrParam(D))
265 return true;
266 if (auto *ImplicitP = dyn_cast<ImplicitParamDecl>(D)) {
267 auto Kind = ImplicitP->getParameterKind();
268 if (Kind == ImplicitParamKind::ObjCSelf ||
272 return true;
273 }
274 } else if (auto *BD = dyn_cast_or_null<BindingDecl>(FoundDecl)) {
275 if (VarDecl *VD = BD->getHoldingVar()) {
276 if (IsCheckedLocalVarOrParam(VD))
277 return true;
278 }
279 }
280 }
282 return true; // A temporary lives until the end of this statement.
284 return true;
285
286 // TODO: checker for method calls on non-refcounted objects
287 return isa<CXXThisExpr>(E);
288}
289
290bool isNullPtr(const clang::Expr *E) {
292 return true;
293 if (auto *Int = dyn_cast_or_null<IntegerLiteral>(E)) {
294 if (Int->getValue().isZero())
295 return true;
296 }
297 return false;
298}
299
301 if (auto *MCE = dyn_cast<CXXMemberCallExpr>(E)) {
302 if (auto *Callee = MCE->getDirectCallee()) {
303 auto Name = safeGetName(Callee);
304 if (Name == "get" || Name == "ptr")
305 E = MCE->getImplicitObjectArgument();
306 if (isa<CXXConversionDecl>(Callee))
307 E = MCE->getImplicitObjectArgument();
308 }
309 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) {
310 if (OCE->getOperator() == OO_Star && OCE->getNumArgs() == 1)
311 E = OCE->getArg(0);
312 }
313 const ValueDecl *D = nullptr;
314 if (auto *ME = dyn_cast<MemberExpr>(E))
315 D = ME->getMemberDecl();
316 else if (auto *IVR = dyn_cast<ObjCIvarRefExpr>(E))
317 D = IVR->getDecl();
318 if (!D)
319 return false;
320 auto T = D->getType();
321 return isOwnerPtrType(T) && T.isConstQualified();
322}
323
325 auto *ME = dyn_cast<MemberExpr>(E);
326 if (!ME)
327 return false;
328 auto *Base = ME->getBase();
329 if (!Base)
330 return false;
331 if (!isa<CXXThisExpr>(Base->IgnoreParenCasts()))
332 return false;
333 auto *D = ME->getMemberDecl();
334 if (!D)
335 return false;
336 auto T = D->getType();
337 auto *CXXRD = T->getAsCXXRecordDecl();
338 if (!CXXRD)
339 return false;
340 auto result = isCheckedPtrCapable(CXXRD);
341 return result && *result;
342}
343
344bool isAllocInit(const Expr *E, const Expr **InnerExpr) {
345 auto *ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(E);
346 if (auto *POE = dyn_cast<PseudoObjectExpr>(E)) {
347 if (unsigned ExprCount = POE->getNumSemanticExprs()) {
348 auto *Expr = POE->getSemanticExpr(ExprCount - 1)->IgnoreParenCasts();
349 ObjCMsgExpr = dyn_cast<ObjCMessageExpr>(Expr);
350 if (InnerExpr)
351 *InnerExpr = ObjCMsgExpr;
352 }
353 }
354 if (!ObjCMsgExpr)
355 return false;
356 auto Selector = ObjCMsgExpr->getSelector();
357 auto NameForFirstSlot = Selector.getNameForSlot(0);
358 if (NameForFirstSlot.starts_with("alloc") ||
359 NameForFirstSlot.starts_with("copy") ||
360 NameForFirstSlot.starts_with("mutableCopy")) {
361 if (auto *MD = ObjCMsgExpr->getMethodDecl()) {
362 if (MD->getReturnType()->isVoidType())
363 return false;
364 }
365 return true;
366 }
367 if (!NameForFirstSlot.starts_with("init") &&
368 !NameForFirstSlot.starts_with("_init"))
369 return false;
370 if (!ObjCMsgExpr->isInstanceMessage())
371 return false;
372 auto *Receiver = ObjCMsgExpr->getInstanceReceiver();
373 if (!Receiver)
374 return false;
375 Receiver = Receiver->IgnoreParenCasts();
376 if (auto *Inner = dyn_cast<ObjCMessageExpr>(Receiver)) {
377 if (InnerExpr)
378 *InnerExpr = Inner;
379 auto InnerSelector = Inner->getSelector();
380 return InnerSelector.getNameForSlot(0).starts_with("alloc");
381 } else if (auto *CE = dyn_cast<CallExpr>(Receiver)) {
382 if (InnerExpr)
383 *InnerExpr = CE;
384 if (auto *Callee = CE->getDirectCallee()) {
385 if (Callee->getDeclName().isIdentifier()) {
386 auto CalleeName = Callee->getName();
387 return CalleeName.starts_with("alloc");
388 }
389 }
390 }
391 return false;
392}
393
395 auto *PointeeType = TypePtr->getPointeeType().getTypePtrOrNull();
396 if (!PointeeType)
397 return nullptr;
398 auto *Desugared = PointeeType->getUnqualifiedDesugaredType();
399 if (!Desugared)
400 return nullptr;
401 if (auto *ObjCType = dyn_cast<ObjCInterfaceType>(Desugared))
402 return ObjCType->getDecl();
403 if (auto *ObjCType = dyn_cast<ObjCObjectType>(Desugared))
404 return ObjCType->getInterface();
405 return nullptr;
406}
407
409 : public ConstStmtVisitor<EnsureFunctionVisitor, bool> {
410public:
411 bool VisitStmt(const Stmt *S) {
412 for (const Stmt *Child : S->children()) {
413 if (Child && !Visit(Child))
414 return false;
415 }
416 return true;
417 }
418
419 bool VisitReturnStmt(const ReturnStmt *RS) {
420 if (auto *RV = RS->getRetValue()) {
421 RV = RV->IgnoreParenCasts();
422 if (isNullPtr(RV))
423 return true;
424 return isConstOwnerPtrMemberExpr(RV);
425 }
426 return false;
427 }
428};
429
431 auto *MCE = dyn_cast<CXXMemberCallExpr>(E);
432 if (!MCE)
433 return false;
434 auto *Callee = MCE->getDirectCallee();
435 if (!Callee)
436 return false;
437 auto *Body = Callee->getBody();
438 if (!Body || Callee->isVirtualAsWritten())
439 return false;
440 auto [CacheIt, IsNew] = Cache.insert(std::make_pair(Callee, false));
441 if (IsNew)
442 CacheIt->second = EnsureFunctionVisitor().Visit(Body);
443 return CacheIt->second;
444}
445
446} // namespace clang
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the clang::Expr interface and subclasses for C++ expressions.
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
ConstStmtVisitor - This class implements a simple visitor for Stmt subclasses.
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isACallToEnsureFn(const Expr *E) const
Definition ASTUtils.cpp:430
bool VisitReturnStmt(const ReturnStmt *RS)
Definition ASTUtils.cpp:419
bool VisitStmt(const Stmt *S)
Definition ASTUtils.cpp:411
This represents one expression.
Definition Expr.h:113
Expr * IgnoreParenCasts() LLVM_READONLY
Skip past any parentheses and casts which might surround this expression until reaching a fixed point...
Definition Expr.cpp:3128
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3408
Expr * getBase() const
Definition Expr.h:3485
Represents an ObjC class declaration.
Definition DeclObjC.h:1160
A (possibly-)qualified type.
Definition TypeBase.h:938
const Type * getTypePtrOrNull() const
Definition TypeBase.h:8462
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
Expr * getRetValue()
Definition Stmt.h:3199
Smart pointer class that efficiently represents Objective-C method names.
StringRef getNameForSlot(unsigned argIndex) const
Retrieve the name at a given position in the selector.
unsigned getNumArgs() const
Stmt - This represents one statement.
Definition Stmt.h:85
child_range children()
Definition Stmt.cpp:304
The base class of the type hierarchy.
Definition TypeBase.h:1879
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
const Type * getUnqualifiedDesugaredType() const
Return the specified type with any "sugar" removed from the type, removing any typedefs,...
Definition Type.cpp:690
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Top level wrappers for InstallAPI frontend operations.
bool isCtorOfSafePtr(const clang::FunctionDecl *F)
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool isExprToGetCheckedPtrCapableMember(const clang::Expr *E)
Definition ASTUtils.cpp:324
bool isPtrConversion(const FunctionDecl *F)
std::optional< bool > isCheckedPtrCapable(const clang::CXXRecordDecl *R)
bool tryToFindPtrOrigin(const Expr *E, bool StopAtFirstRefCountedObj, std::function< bool(const clang::CXXRecordDecl *)> isSafePtr, std::function< bool(const clang::QualType)> isSafePtrType, std::function< bool(const clang::Decl *)> isSafeGlobalDecl, std::function< bool(const clang::Expr *, bool)> callback)
This function de-facto defines a set of transformations that we consider safe (in heuristical sense).
Definition ASTUtils.cpp:25
bool isASafeCallArg(const Expr *E)
For E referring to a ref-countable/-counted pointer/reference we return whether it's a safe call argu...
Definition ASTUtils.cpp:250
const FunctionProtoType * T
bool isRefCounted(const CXXRecordDecl *R)
bool isOwnerPtrType(const clang::QualType T)
std::optional< bool > isGetterOfSafePtr(const CXXMethodDecl *M)
bool isRetainPtrOrOSPtr(const std::string &Name)
bool isRefType(const std::string &Name)
bool isSafePtr(clang::CXXRecordDecl *Decl)
Definition ASTUtils.cpp:21
std::string safeGetName(const T *ASTNode)
Definition ASTUtils.h:98
ObjCInterfaceDecl * getObjCDeclFromObjCPtr(const Type *TypePtr)
Definition ASTUtils.cpp:394
bool isSingleton(const NamedDecl *F)
bool isNullPtr(const clang::Expr *E)
Definition ASTUtils.cpp:290
bool isCheckedPtr(const std::string &Name)
bool isStdOrWTFMove(const clang::FunctionDecl *F)
U cast(CodeGen::Address addr)
Definition Address.h:327
bool isAllocInit(const Expr *E, const Expr **InnerExpr)
Definition ASTUtils.cpp:344
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:5999
@ CXXThis
Parameter for C++ 'this' argument.
Definition Decl.h:1763
@ CXXVTT
Parameter for C++ virtual table pointers.
Definition Decl.h:1766
@ ObjCSelf
Parameter for Objective-C 'self' argument.
Definition Decl.h:1757
@ ObjCCmd
Parameter for Objective-C '_cmd' argument.
Definition Decl.h:1760
bool isConstOwnerPtrMemberExpr(const clang::Expr *E)
Definition ASTUtils.cpp:300
bool isWeakPtr(const CXXRecordDecl *R)
int const char * function
Definition c++config.h:31